auth

package
v0.0.46 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PermContactsRead      = "contacts:read"
	PermContactsWrite     = "contacts:write"
	PermTasksRead         = "tasks:read"
	PermTasksWrite        = "tasks:write"
	PermChatWrite         = "chat:write"
	PermSessionsRead      = "sessions:read"
	PermDashboardRead     = "dashboard:read"
	PermEnvRead           = "env:read"
	PermEnvWrite          = "env:write"
	PermSystemConfigRead  = "system_config:read"
	PermSystemConfigWrite = "system_config:write"
	PermUsersManage       = "users:manage"
	PermRolesManage       = "roles:manage"
)

Permission keys ("resource:action"). Single source of truth.

View Source
const (
	ScopeReadWorkers     = "read:workers"
	ScopeReadDepartments = "read:departments"
	ScopeReadTasks       = "read:tasks"
	ScopeReadMessages    = "read:messages"
)
View Source
const (
	TokenTypeBee    = "bee"
	TokenTypeWorker = "worker"
)
View Source
const PermWildcard = "*"

PermWildcard grants every permission (super-admin).

Variables

Functions

func AllPermissions added in v0.0.42

func AllPermissions() []string

AllPermissions flattens the catalog into a single slice.

func AuthMiddleware added in v0.0.42

func AuthMiddleware(jwtSvc *JWTService, users UserAuthStateLoader) gin.HandlerFunc

AuthMiddleware validates the access token, loads the user id, and rejects missing/disabled accounts as well as tokens minted before the user's last password change (which forces a re-login after any password change/reset).

func CheckPassword added in v0.0.42

func CheckPassword(hash, plain string) bool

CheckPassword reports whether plain matches the bcrypt hash.

func GenerateBeeToken

func GenerateBeeToken(secret string, ttl time.Duration) (string, error)

func GenerateWorkerToken

func GenerateWorkerToken(secret, workerID string, scopes []string, ttl time.Duration) (string, error)

func HashPassword added in v0.0.42

func HashPassword(plain string) (string, error)

HashPassword returns a bcrypt hash of the plaintext password.

func IsAssignablePermission added in v0.0.42

func IsAssignablePermission(p string) bool

IsAssignablePermission reports whether p is a known, assignable permission.

func RequirePermission added in v0.0.42

func RequirePermission(resolver *PermissionResolver, perms ...string) gin.HandlerFunc

RequirePermission aborts with 403 unless the current user holds at least one of perms. Multiple perms are OR-ed (any one grants access); pass a single perm for the common case.

func ScopeForTool added in v0.0.22

func ScopeForTool(name string) (string, bool)

ScopeForTool returns the permission scope required to call the named tool, and whether the tool has a scope requirement at all.

func SetUserID added in v0.0.42

func SetUserID(c *gin.Context, uid string)

SetUserID stores the authenticated user id on the request context.

func TokenPredatesPasswordChange added in v0.0.42

func TokenPredatesPasswordChange(issuedAt, passwordChangedAt int64) bool

TokenPredatesPasswordChange reports whether a token issued at issuedAt was minted before the user's last password change (passwordChangedAt), in which case it must be rejected to force a re-login. Both the access-token middleware and the refresh path apply this check, since the refresh endpoint bypasses the middleware.

func UserID added in v0.0.42

func UserID(c *gin.Context) string

UserID returns the authenticated user id, or "" if unauthenticated.

func ValidatePermissionScopes added in v0.0.22

func ValidatePermissionScopes(scopes string) error

ValidatePermissionScopes checks that every scope in the comma-separated string is a recognised value. Returns an error listing any invalid scopes found.

Types

type AuthHandler

type AuthHandler struct {
	// contains filtered or unexported fields
}

func NewAuthHandler

func NewAuthHandler(users UserAuthenticator, jwtSvc *JWTService, rateLimiter *LoginRateLimiter, resolver *PermissionResolver) *AuthHandler

func (*AuthHandler) ChangePassword added in v0.0.42

func (h *AuthHandler) ChangePassword(c *gin.Context)

ChangePassword updates the current user's password after verifying the old one.

func (*AuthHandler) Login

func (h *AuthHandler) Login(c *gin.Context)

func (*AuthHandler) Me added in v0.0.42

func (h *AuthHandler) Me(c *gin.Context)

Me returns the current user with resolved permissions.

func (*AuthHandler) Refresh

func (h *AuthHandler) Refresh(c *gin.Context)

type Claims

type Claims struct {
	Type string `json:"type"`
	UID  string `json:"uid,omitempty"`
	jwt.RegisteredClaims
}

type JWTService

type JWTService struct {
	// contains filtered or unexported fields
}

func NewJWTService

func NewJWTService(secret string, accessTTL, refreshTTL time.Duration) *JWTService

func (*JWTService) GenerateUserAccessToken added in v0.0.42

func (s *JWTService) GenerateUserAccessToken(userID string) (string, int64, error)

GenerateUserAccessToken issues a fresh access token for a user id.

func (*JWTService) GenerateUserTokenPair added in v0.0.42

func (s *JWTService) GenerateUserTokenPair(userID string) (*TokenPair, error)

GenerateUserTokenPair issues an access+refresh pair bound to a user id.

func (*JWTService) ParseAccessToken added in v0.0.42

func (s *JWTService) ParseAccessToken(tokenStr string) (uid string, issuedAt int64, err error)

ParseAccessToken validates an access token and returns its uid and the issued-at time in milliseconds (floored to the second, matching the JWT `iat` claim). Callers compare issuedAt against the user's password_changed_at to reject tokens minted before a password change.

func (*JWTService) ParseRefreshToken added in v0.0.42

func (s *JWTService) ParseRefreshToken(tokenStr string) (uid string, issuedAt int64, err error)

ParseRefreshToken validates a refresh token and returns its uid and issued-at time in milliseconds. See ParseAccessToken for the issuedAt semantics.

type LoginRateLimiter

type LoginRateLimiter struct {
	// contains filtered or unexported fields
}

LoginRateLimiter throttles login attempts per client key (typically an IP). It wraps a token-bucket limiter per key: up to maxAttempts in a burst, then one slot recovers every window/maxAttempts. Callers consume a token on each attempt via Allow and clear a key's budget with Reset on success, so only failed attempts leave a lasting cost.

func NewLoginRateLimiter

func NewLoginRateLimiter(maxAttempts int, window time.Duration) *LoginRateLimiter

func (*LoginRateLimiter) Allow

func (l *LoginRateLimiter) Allow(key string) bool

Allow consumes one token for the key and reports whether the attempt is permitted. Call it at the request entry point.

func (*LoginRateLimiter) Reset added in v0.0.42

func (l *LoginRateLimiter) Reset(key string)

Reset clears a key's budget so its next attempt starts from a full bucket. Call it after a successful login so legitimate users never accumulate a cost.

type PermissionGroup added in v0.0.42

type PermissionGroup struct {
	Resource    string   `json:"resource"`
	Permissions []string `json:"permissions"`
}

PermissionGroup groups permissions by resource for the catalog endpoint.

func PermissionCatalog added in v0.0.42

func PermissionCatalog() []PermissionGroup

PermissionCatalog returns the grouped permission catalog for the UI.

type PermissionLoader added in v0.0.42

type PermissionLoader func(userID string) ([]string, error)

PermissionLoader loads the raw permission keys for a user (union across roles).

type PermissionResolver added in v0.0.42

type PermissionResolver struct {
	// contains filtered or unexported fields
}

PermissionResolver caches per-user permission sets and answers HasPermission.

func NewPermissionResolver added in v0.0.42

func NewPermissionResolver(loader PermissionLoader) *PermissionResolver

func (*PermissionResolver) HasAnyPermission added in v0.0.42

func (r *PermissionResolver) HasAnyPermission(userID string, perms ...string) (bool, error)

HasAnyPermission reports whether the user holds at least one of perms (or the wildcard). With no perms it returns false.

func (*PermissionResolver) HasPermission added in v0.0.42

func (r *PermissionResolver) HasPermission(userID, perm string) (bool, error)

HasPermission reports whether the user holds perm (or the wildcard).

func (*PermissionResolver) Invalidate added in v0.0.42

func (r *PermissionResolver) Invalidate(userID string)

Invalidate drops the cached set for one user.

func (*PermissionResolver) InvalidateAll added in v0.0.42

func (r *PermissionResolver) InvalidateAll()

InvalidateAll clears the entire cache (use when role permissions change).

func (*PermissionResolver) PermissionsFor added in v0.0.42

func (r *PermissionResolver) PermissionsFor(userID string) ([]string, error)

PermissionsFor returns the user's resolved permission keys (for /api/me).

type RPCClaims added in v0.0.35

type RPCClaims struct {
	Type     string   `json:"type"`
	WorkerID string   `json:"worker_id,omitempty"`
	Scopes   []string `json:"scopes,omitempty"`
	jwt.RegisteredClaims
}

RPCClaims are the JWT claims embedded in every RPC token.

func ValidateToken

func ValidateToken(tokenStr, secret string) (*RPCClaims, error)

type TokenPair

type TokenPair struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"` // seconds until access_token expires
}

type UserAuthStateLoader added in v0.0.42

type UserAuthStateLoader interface {
	UserAuthState(userID string) (status string, passwordChangedAt int64, err error)
}

UserAuthStateLoader returns the account status and last password-change time for a user id, in a single query.

type UserAuthenticator added in v0.0.42

type UserAuthenticator interface {
	Authenticate(username, password string) (model.UserWithRoles, error)
	GetByID(id string) (model.UserWithRoles, error)
	SetPassword(id, plainPassword string) error
	UserAuthState(userID string) (status string, passwordChangedAt int64, err error)
}

UserAuthenticator authenticates credentials and loads user data.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL