Select Git revision
telemetry_middleware.go
auth.go 3.91 KiB
package perxis
import (
"context"
"runtime"
"strings"
"git.perx.ru/perxis/perxis-go/pkg/errors"
)
var (
ErrAccessDenied = errors.New("access denied")
)
type Principal interface {
GetID() string
}
// Authenticator интерфейс для аутентификации
type Authenticator interface {
// Authenticate аутентификация
Authenticate(ctx context.Context) (Principal, error)
}
type Authorization struct {
Authorizer Authorizer
}
// Authorizer интерфейс для авторизации
type Authorizer interface {
Authorize(principal Principal, action string, resource any) (*Authorization, error)
}
var (
authorizer Authorizer
authenticator Authenticator
)
func SetAuthorizer(a Authorizer) {
authorizer = a
}
func SetAuthenticator(a Authenticator) {
authenticator = a
}
func Authenticate(ctx context.Context) (Principal, error) {
if authenticator == nil {
return nil, nil
}
return authenticator.Authenticate(ctx)
}
func Authorize(principal Principal, action string, resource any) (*Authorization, error) {
if authorizer == nil {
return nil, nil
}
return authorizer.Authorize(principal, action, resource)
}
func AuthorizeContext(ctx context.Context, action string, resource any) (*Authorization, error) {
principal, err := Authenticate(ctx)
if err != nil {
return nil, err
}
return Authorize(principal, action, resource)
}
func IsAllowed(ctx context.Context, res any) (*Authorization, error) {
pc, _, _, _ := runtime.Caller(1)