Skip to content

Commit

Permalink
feat: add api key checker
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored May 5, 2024
1 parent c97b092 commit eed7a35
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
32 changes: 32 additions & 0 deletions openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
4 changes: 2 additions & 2 deletions tbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit eed7a35

Please sign in to comment.