feat: add permission check

This commit is contained in:
Vyacheslav1557 2024-08-20 16:18:23 +05:00
parent 56135ff5df
commit bebc7f3076
14 changed files with 490 additions and 95 deletions

View file

@ -0,0 +1,39 @@
package services
import (
"context"
"git.sch9.ru/new_gate/ms-tester/internal/models"
"github.com/open-policy-agent/opa/rego"
)
type PermissionService struct {
query *rego.PreparedEvalQuery
}
func NewPermissionService() *PermissionService {
query, err := rego.New(
rego.Query("allow = data.problem.rbac.allow"),
rego.Load([]string{"./opa/problem.rego"}, nil),
).PrepareForEval(context.TODO())
if err != nil {
panic(err)
}
return &PermissionService{
query: &query,
}
}
func (s *PermissionService) Allowed(ctx context.Context, user *models.User, action string) bool {
input := map[string]interface{}{
"user": user,
"action": action,
}
result, err := s.query.Eval(ctx, rego.EvalInput(input))
if err != nil {
panic(err)
}
return result[0].Bindings["allow"].(bool)
}

29
internal/services/user.go Normal file
View file

@ -0,0 +1,29 @@
package services
import (
"context"
"git.sch9.ru/new_gate/ms-tester/internal/models"
)
type UserStorage interface {
CreateUser(ctx context.Context, user *models.User) error
ReadUserById(ctx context.Context, userId int32) (*models.User, error)
}
type UserService struct {
userStorage UserStorage
}
func NewUserService(userStorage UserStorage) *UserService {
return &UserService{
userStorage: userStorage,
}
}
func (s *UserService) CreateUser(ctx context.Context, user *models.User) error {
return s.userStorage.CreateUser(ctx, user)
}
func (s *UserService) ReadUserById(ctx context.Context, userId int32) (*models.User, error) {
return s.userStorage.ReadUserById(ctx, userId)
}