Files
Michilis 41f6ae916f first commit
Made-with: Cursor
2026-02-28 02:17:55 +00:00

65 lines
1.2 KiB
Go

package middleware
import (
"context"
"github.com/google/uuid"
)
type contextKey string
const (
userIDKey contextKey = "user_id"
authMethodKey contextKey = "auth_method"
scopesKey contextKey = "scopes"
)
type Scopes map[string][]string
func SetUserID(ctx context.Context, id uuid.UUID) context.Context {
return context.WithValue(ctx, userIDKey, id)
}
func GetUserID(ctx context.Context) (uuid.UUID, bool) {
id, ok := ctx.Value(userIDKey).(uuid.UUID)
return id, ok
}
func SetAuthMethod(ctx context.Context, method string) context.Context {
return context.WithValue(ctx, authMethodKey, method)
}
func GetAuthMethod(ctx context.Context) string {
m, _ := ctx.Value(authMethodKey).(string)
return m
}
func SetScopes(ctx context.Context, scopes Scopes) context.Context {
return context.WithValue(ctx, scopesKey, scopes)
}
func GetScopes(ctx context.Context) Scopes {
s, _ := ctx.Value(scopesKey).(Scopes)
return s
}
func HasScope(ctx context.Context, resource, action string) bool {
if GetAuthMethod(ctx) == "jwt" {
return true
}
scopes := GetScopes(ctx)
if scopes == nil {
return false
}
actions, ok := scopes[resource]
if !ok {
return false
}
for _, a := range actions {
if a == action {
return true
}
}
return false
}