feat: own shared user API tokens
This commit is contained in:
112
classes/api_tokens.go
Normal file
112
classes/api_tokens.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const DefaultAPITokenPrefix = "usr_"
|
||||
|
||||
var (
|
||||
DefaultAPITokenScopes = []string{"read"}
|
||||
AllowedAPITokenScopes = []string{"read", "write", "ai"}
|
||||
)
|
||||
|
||||
// APITokenPrefix returns the configured on-wire prefix. Applications may keep
|
||||
// a legacy prefix while every plugin still consumes the same token table.
|
||||
func APITokenPrefix(app *backpack.App) (string, error) {
|
||||
prefix := DefaultAPITokenPrefix
|
||||
if app != nil && app.Config != nil {
|
||||
if configured := strings.TrimSpace(app.Config.String("golem15.user.api_tokens.prefix")); configured != "" {
|
||||
prefix = configured
|
||||
}
|
||||
}
|
||||
if len(prefix) < 2 || len(prefix) > 16 {
|
||||
return "", fmt.Errorf("golem15.user: api_tokens.prefix must contain 2 to 16 safe characters")
|
||||
}
|
||||
for _, r := range prefix {
|
||||
if !(r == '_' || r == '-' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9') {
|
||||
return "", fmt.Errorf("golem15.user: api_tokens.prefix contains an unsafe character")
|
||||
}
|
||||
}
|
||||
return prefix, nil
|
||||
}
|
||||
|
||||
// MintAPIToken builds a token record and returns its one-time clear-text
|
||||
// secret. A nil scopes slice receives DefaultAPITokenScopes.
|
||||
func MintAPIToken(prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint) (string, *models.APIToken, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if userID == 0 || name == "" || len(name) > 255 {
|
||||
return "", nil, fmt.Errorf("a user and token name of 1 to 255 characters are required")
|
||||
}
|
||||
if prefix == "" {
|
||||
prefix = DefaultAPITokenPrefix
|
||||
}
|
||||
if scopes == nil {
|
||||
scopes = slices.Clone(DefaultAPITokenScopes)
|
||||
} else {
|
||||
scopes = slices.Clone(scopes)
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
if !slices.Contains(AllowedAPITokenScopes, scope) {
|
||||
return "", nil, fmt.Errorf("scope %q is not allowed", scope)
|
||||
}
|
||||
}
|
||||
seenScopes := make(map[string]bool, len(scopes))
|
||||
uniqueScopes := make([]string, 0, len(scopes))
|
||||
for _, scope := range scopes {
|
||||
if !seenScopes[scope] {
|
||||
seenScopes[scope] = true
|
||||
uniqueScopes = append(uniqueScopes, scope)
|
||||
}
|
||||
}
|
||||
scopes = uniqueScopes
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
secret := prefix + base64.RawURLEncoding.EncodeToString(raw)
|
||||
token := &models.APIToken{
|
||||
UserID: userID,
|
||||
Name: &name,
|
||||
TokenHash: HashAPIToken(secret),
|
||||
Scopes: lagoon.Jsonable[[]string]{Data: scopes, Valid: true},
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
if len(collectionIDs) > 0 {
|
||||
collectionIDs = slices.Compact(slices.Sorted(slices.Values(collectionIDs)))
|
||||
token.CollectionIDs = lagoon.Jsonable[[]uint]{Data: collectionIDs, Valid: true}
|
||||
}
|
||||
return secret, token, nil
|
||||
}
|
||||
|
||||
// HashAPIToken returns the only representation of a token secret stored in
|
||||
// the database.
|
||||
func HashAPIToken(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// RevokeAPIToken invalidates token immediately.
|
||||
func RevokeAPIToken(db *gorm.DB, token *models.APIToken) error {
|
||||
if db == nil || token == nil {
|
||||
return fmt.Errorf("golem15.user: token is missing")
|
||||
}
|
||||
now := time.Now()
|
||||
if err := db.Model(token).Update("revoked_at", now).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
token.RevokedAt = &now
|
||||
return nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -27,6 +28,14 @@ func (g GormUsers) FindByID(ctx context.Context, id uint) (*bouncer.Principal, e
|
||||
if !ok || gdb == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
return PrincipalByID(ctx, gdb, id)
|
||||
}
|
||||
|
||||
// PrincipalByID loads one front-end user and their current group permissions.
|
||||
func PrincipalByID(ctx context.Context, gdb *gorm.DB, id uint) (*bouncer.Principal, error) {
|
||||
if gdb == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
var row models.User
|
||||
err := gdb.WithContext(ctx).Where("id = ?", id).Take(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -42,9 +51,66 @@ func (g GormUsers) FindByID(ctx context.Context, id uint) (*bouncer.Principal, e
|
||||
if row.TokensValidAfter != nil {
|
||||
principal.TokensValidAfter = *row.TokensValidAfter
|
||||
}
|
||||
grants, err := UserPermissionGrants(ctx, gdb, row.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
principal.PermissionGrants = grants
|
||||
return principal, nil
|
||||
}
|
||||
|
||||
// UserPermissionGrants returns the enabled permissions of all groups to which
|
||||
// userID belongs. A false/zero value is not a grant; another group may still
|
||||
// grant the same code.
|
||||
func UserPermissionGrants(ctx context.Context, db *gorm.DB, userID uint) (map[string]bool, error) {
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
var rows []struct{ Permissions *string }
|
||||
err := db.WithContext(ctx).
|
||||
Table("user_groups").
|
||||
Select("user_groups.permissions").
|
||||
Joins("JOIN users_groups ON users_groups.user_group_id = user_groups.id").
|
||||
Where("users_groups.user_id = ? AND user_groups.permissions IS NOT NULL", userID).
|
||||
Order("user_groups.id").
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
grants := map[string]bool{}
|
||||
for _, row := range rows {
|
||||
if row.Permissions == nil || strings.TrimSpace(*row.Permissions) == "" {
|
||||
continue
|
||||
}
|
||||
var decoded map[string]any
|
||||
if json.Unmarshal([]byte(*row.Permissions), &decoded) != nil {
|
||||
continue
|
||||
}
|
||||
for code, value := range decoded {
|
||||
if permissionEnabled(value) {
|
||||
grants[code] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(grants) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return grants, nil
|
||||
}
|
||||
|
||||
func permissionEnabled(value any) bool {
|
||||
switch v := value.(type) {
|
||||
case bool:
|
||||
return v
|
||||
case float64:
|
||||
return v == 1
|
||||
case string:
|
||||
return v == "1" || strings.EqualFold(v, "true")
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// LookupByEmail returns the user row, including a soft-deleted one.
|
||||
// A missing email is (nil, nil).
|
||||
func LookupByEmail(ctx context.Context, db *gorm.DB, email string) (*models.User, error) {
|
||||
|
||||
Reference in New Issue
Block a user