From eed7a35d2400b242bf87b3bc8e1fd433e730dc1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20D=C3=B6ll?= Date: Sun, 5 May 2024 19:41:39 +0000 Subject: [PATCH] feat: add api key checker --- openapi.go | 32 ++++++++++++++++++++++++++++++++ tbac.go | 4 ++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/openapi.go b/openapi.go index eccdcc8..0a078b3 100644 --- a/openapi.go +++ b/openapi.go @@ -8,6 +8,7 @@ import ( "github.com/getkin/kin-openapi/openapi3filter" "github.com/gofiber/fiber/v2" middleware "github.com/oapi-codegen/fiber-middleware" + "gorm.io/gorm" ) // OpenAPIAuthenticatorOpts are the OpenAPI authenticator options. @@ -115,3 +116,34 @@ func GetAPIKeyFromContext(ctx context.Context) (string, error) { func GetAPIKeyFromRequest(req *http.Request) (string, error) { return req.Header.Get("x-api-key"), nil } + +var _ AuthzChecker = (*apiKey)(nil) + +type apiKey struct { + db *gorm.DB +} + +// NewAPIKey returns a new API key authenticator. +func NewAPIKey(db *gorm.DB) *apiKey { + return &apiKey{ + db: db, + } +} + +// Allowed is a method that returns true if the principal is allowed to perform the action on the user. +func (t *apiKey) Allowed(ctx context.Context, principal AuthzPrincipal, object AuthzObject, action AuthzAction) (bool, error) { + var allowed int64 + + team := t.db.WithContext(ctx).Model(&apiKey{}).Select("id").Where("slug = ?", object) + + err := t.db.Raw("SELECT COUNT(1) FROM vw_user_team_permissions WHERE user_id = ? AND team_id = (?) AND permission = ?", principal, team, action).Count(&allowed).Error + if err != nil { + return false, err + } + + if allowed > 0 { + return true, nil + } + + return false, nil +} diff --git a/tbac.go b/tbac.go index 7e50bb7..4970146 100644 --- a/tbac.go +++ b/tbac.go @@ -217,9 +217,9 @@ func NewTBAC(db *gorm.DB) *tbac { func (t *tbac) Allowed(ctx context.Context, principal AuthzPrincipal, object AuthzObject, action AuthzAction) (bool, error) { var allowed int64 - teamScope := t.db.WithContext(ctx).Model(&Team{}).Select("id").Where("scope = ?", object) + team := t.db.WithContext(ctx).Model(&Team{}).Select("id").Where("slug = ?", object) - err := t.db.Raw("SELECT COUNT(1) FROM vw_user_team_permissions WHERE user_id = ? AND team_id = (?) AND permission = ?", principal, teamScope, action).Count(&allowed).Error + err := t.db.Raw("SELECT COUNT(1) FROM vw_user_team_permissions WHERE user_id = ? AND team_id = (?) AND permission = ?", principal, team, action).Count(&allowed).Error if err != nil { return false, err }