Documentation
¶
Index ¶
- Variables
- func AuthMiddleware(manager *Manager) router.MiddlewareFunc
- type AfterCallback
- type AuthUser
- type Authenticatable
- type BaseSession
- func (s *BaseSession) Clear()
- func (s *BaseSession) Flash(key string, value interface{})
- func (s *BaseSession) Get(key string) interface{}
- func (s *BaseSession) GetData() map[string]interface{}
- func (s *BaseSession) GetFlash(key string) interface{}
- func (s *BaseSession) GetFlashData() map[string]interface{}
- func (s *BaseSession) Has(key string) bool
- func (s *BaseSession) ID() string
- func (s *BaseSession) Invalidate() error
- func (s *BaseSession) IsDestroyed() bool
- func (s *BaseSession) IsModified() bool
- func (s *BaseSession) Put(key string, value interface{})
- func (s *BaseSession) Regenerate() error
- func (s *BaseSession) Remove(key string)
- func (s *BaseSession) Save(w http.ResponseWriter) error
- func (s *BaseSession) SetData(data map[string]interface{})
- func (s *BaseSession) SetFlashData(flash map[string]interface{})
- type BcryptHasher
- type BeforeCallback
- type BlacklistStore
- type Claims
- type Config
- type Gate
- func (g *Gate) After(callback AfterCallback)
- func (g *Gate) Allows(user Authenticatable, ability string, args ...interface{}) bool
- func (g *Gate) Any(user Authenticatable, abilities []string, args ...interface{}) bool
- func (g *Gate) AuthorizePolicy(user Authenticatable, resourceType, action string, resource interface{}) bool
- func (g *Gate) Before(callback BeforeCallback)
- func (g *Gate) Check(user Authenticatable, abilities []string, args ...interface{}) bool
- func (g *Gate) Define(ability string, callback GateCallback)
- func (g *Gate) Denies(user Authenticatable, ability string, args ...interface{}) bool
- func (g *Gate) ForUser(user Authenticatable) *UserGate
- func (g *Gate) HasAllRoles(user Authenticatable, roles ...string) bool
- func (g *Gate) HasAnyRole(user Authenticatable, roles ...string) bool
- func (g *Gate) HasRole(user Authenticatable, role string) bool
- func (g *Gate) RegisterPolicy(resourceType string, policy Policy)
- func (g *Gate) SetRoleChecker(checker RoleChecker)
- type GateCallback
- type Guard
- type GuardConfig
- type Hasher
- type InMemoryBlacklistStore
- type JWTConfig
- type JWTManager
- func (j *JWTManager) CleanupBlacklist()
- func (j *JWTManager) GenerateRefreshToken(user Authenticatable) (string, error)
- func (j *JWTManager) GenerateToken(user Authenticatable, customClaims ...map[string]interface{}) (string, error)
- func (j *JWTManager) IsBlacklisted(jti string) bool
- func (j *JWTManager) ParseTokenWithoutValidation(tokenString string) (*Claims, error)
- func (j *JWTManager) RefreshToken(refreshTokenString string, provider UserProvider) (string, error)
- func (j *JWTManager) RevokeToken(jti string, expiresAt ...time.Time)
- func (j *JWTManager) SetBlacklistStore(store BlacklistStore)
- func (j *JWTManager) ValidateToken(tokenString string) (*Claims, error)
- type Manager
- func (m *Manager) Attempt(w http.ResponseWriter, r *http.Request, credentials map[string]interface{}, ...) (bool, error)
- func (m *Manager) Check(r *http.Request) bool
- func (m *Manager) DefaultGuard() (Guard, error)
- func (m *Manager) GetHasher() Hasher
- func (m *Manager) Guard(name string) (Guard, error)
- func (m *Manager) Hash(password string) (string, error)
- func (m *Manager) ID(r *http.Request) interface{}
- func (m *Manager) Login(w http.ResponseWriter, r *http.Request, user Authenticatable, remember ...bool) error
- func (m *Manager) Logout(w http.ResponseWriter, r *http.Request) error
- func (m *Manager) Provider(name string) (UserProvider, error)
- func (m *Manager) RegisterGuard(name string, guard Guard)
- func (m *Manager) RegisterProvider(name string, provider UserProvider)
- func (m *Manager) SetDefaultGuard(name string)
- func (m *Manager) SetHasher(h Hasher)
- func (m *Manager) User(r *http.Request) Authenticatable
- func (m *Manager) Verify(password string, hash string) bool
- type ORMUserProvider
- func (p *ORMUserProvider) FindByCredentials(credentials map[string]interface{}) (Authenticatable, error)
- func (p *ORMUserProvider) FindByID(id interface{}) (Authenticatable, error)
- func (p *ORMUserProvider) UpdateRememberToken(user Authenticatable, token string) error
- func (p *ORMUserProvider) ValidateCredentials(user Authenticatable, credentials map[string]interface{}) bool
- type Policy
- type PolicyFunc
- type ProviderConfig
- type RoleChecker
- type Session
- type SessionConfig
- type SessionStore
- type UserGate
- func (ug *UserGate) Allows(ability string, args ...interface{}) bool
- func (ug *UserGate) Authorize(ability string, args ...interface{}) error
- func (ug *UserGate) Can(ability string, args ...interface{}) bool
- func (ug *UserGate) Cannot(ability string, args ...interface{}) bool
- func (ug *UserGate) Denies(ability string, args ...interface{}) bool
- type UserProvider
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotAuthenticated = errors.New("not authenticated") ErrInvalidCredentials = errors.New("invalid credentials") ErrUserNotFound = errors.New("user not found") ErrGuardNotFound = errors.New("guard not found") ErrNotInitialized = errors.New("auth manager not initialized") ErrInvalidSession = errors.New("invalid session") )
Errors
var ( ErrPolicyNotFound = errors.New("policy not found") ErrGateNotFound = errors.New("gate not found") ErrNoUserInContext = errors.New("no authenticated user in context") ErrInvalidResource = errors.New("invalid resource type") )
Authorization errors
Functions ¶
func AuthMiddleware ¶ added in v0.9.5
func AuthMiddleware(manager *Manager) router.MiddlewareFunc
AuthMiddleware returns a router.MiddlewareFunc that requires authentication using the provided Manager instance.
Types ¶
type AfterCallback ¶ added in v0.8.0
type AfterCallback func(user Authenticatable, ability string, result bool, args ...interface{}) bool
AfterCallback is called after any gate/policy check
type AuthUser ¶ added in v0.2.4
type AuthUser struct {
ID interface{}
Name string
Email string
Password string
RememberToken string
}
AuthUser represents an authenticated user
func (*AuthUser) GetAuthIdentifier ¶ added in v0.2.4
func (u *AuthUser) GetAuthIdentifier() interface{}
GetAuthIdentifier returns user ID
func (*AuthUser) GetAuthPassword ¶ added in v0.2.4
GetAuthPassword returns user password hash
func (*AuthUser) GetRememberToken ¶ added in v0.2.4
GetRememberToken returns remember token
func (*AuthUser) SetRememberToken ¶ added in v0.2.4
SetRememberToken sets remember token
type Authenticatable ¶
type Authenticatable interface {
GetAuthIdentifier() interface{}
GetAuthPassword() string
GetRememberToken() string
SetRememberToken(token string)
}
Authenticatable represents a user that can be authenticated
type BaseSession ¶
type BaseSession struct {
// contains filtered or unexported fields
}
BaseSession provides common session functionality
func (*BaseSession) Flash ¶
func (s *BaseSession) Flash(key string, value interface{})
Flash sets flash message
func (*BaseSession) Get ¶
func (s *BaseSession) Get(key string) interface{}
Get gets value from session
func (*BaseSession) GetData ¶
func (s *BaseSession) GetData() map[string]interface{}
GetData returns session data (for serialization)
func (*BaseSession) GetFlash ¶
func (s *BaseSession) GetFlash(key string) interface{}
GetFlash gets and removes flash message
func (*BaseSession) GetFlashData ¶
func (s *BaseSession) GetFlashData() map[string]interface{}
GetFlashData returns flash data (for serialization)
func (*BaseSession) Invalidate ¶
func (s *BaseSession) Invalidate() error
Invalidate invalidates session
func (*BaseSession) IsDestroyed ¶
func (s *BaseSession) IsDestroyed() bool
IsDestroyed checks if session was destroyed
func (*BaseSession) IsModified ¶
func (s *BaseSession) IsModified() bool
IsModified checks if session was modified
func (*BaseSession) Put ¶
func (s *BaseSession) Put(key string, value interface{})
Put puts value in session
func (*BaseSession) Regenerate ¶
func (s *BaseSession) Regenerate() error
Regenerate regenerates session ID
func (*BaseSession) Remove ¶
func (s *BaseSession) Remove(key string)
Remove removes value from session
func (*BaseSession) Save ¶
func (s *BaseSession) Save(w http.ResponseWriter) error
Save saves session (implemented by stores)
func (*BaseSession) SetData ¶
func (s *BaseSession) SetData(data map[string]interface{})
SetData sets session data (for deserialization)
func (*BaseSession) SetFlashData ¶
func (s *BaseSession) SetFlashData(flash map[string]interface{})
SetFlashData sets flash data (for deserialization)
type BcryptHasher ¶
type BcryptHasher struct {
// contains filtered or unexported fields
}
BcryptHasher implements Hasher using bcrypt
func NewBcryptHasher ¶
func NewBcryptHasher(cost int) *BcryptHasher
NewBcryptHasher creates a new bcrypt hasher. Minimum cost is 10 for security; lower values are overridden with a warning.
func (*BcryptHasher) Hash ¶
func (h *BcryptHasher) Hash(password string) (string, error)
Hash hashes a password using bcrypt
func (*BcryptHasher) NeedsRehash ¶
func (h *BcryptHasher) NeedsRehash(hash string) bool
NeedsRehash checks if a hash needs rehashing
func (*BcryptHasher) SetCost ¶
func (h *BcryptHasher) SetCost(cost int)
SetCost updates the bcrypt cost factor
type BeforeCallback ¶ added in v0.8.0
type BeforeCallback func(user Authenticatable, ability string, args ...interface{}) *bool
BeforeCallback is called before any gate/policy check Return true to allow, false to deny, nil to continue to the actual check
type BlacklistStore ¶ added in v0.9.2
type BlacklistStore interface {
// Add adds a token JTI to the blacklist with an expiration time.
Add(jti string, expiresAt time.Time)
// IsBlacklisted checks whether a token JTI has been blacklisted.
IsBlacklisted(jti string) bool
// Cleanup removes expired entries.
Cleanup()
}
BlacklistStore defines the interface for JWT token blacklist storage. Implement with Redis or another persistent store for production use.
type Claims ¶
type Claims struct {
jwt.RegisteredClaims
UserID interface{} `json:"uid,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
TokenType string `json:"type,omitempty"` // "access" or "refresh"
}
Claims represents JWT claims
type Config ¶
type Config struct {
DefaultGuard string
Guards map[string]GuardConfig
Providers map[string]ProviderConfig
BcryptCost int // Bcrypt cost for password hashing. 0 uses the default.
}
Config holds authentication configuration
func ConfigFromEnv ¶ added in v0.9.5
ConfigFromEnv builds a Config from environment variables. Returns the config and true if AUTH_GUARD is set, or a zero Config and false otherwise.
type Gate ¶ added in v0.8.0
type Gate struct {
// contains filtered or unexported fields
}
Gate manages authorization gates and policies
func (*Gate) After ¶ added in v0.8.0
func (g *Gate) After(callback AfterCallback)
After registers a callback to run after authorization checks
func (*Gate) Allows ¶ added in v0.8.0
func (g *Gate) Allows(user Authenticatable, ability string, args ...interface{}) bool
Allows checks if a user is allowed to perform an ability
func (*Gate) Any ¶ added in v0.8.0
func (g *Gate) Any(user Authenticatable, abilities []string, args ...interface{}) bool
Any checks if any of the abilities pass
func (*Gate) AuthorizePolicy ¶ added in v0.8.0
func (g *Gate) AuthorizePolicy(user Authenticatable, resourceType, action string, resource interface{}) bool
AuthorizePolicy checks authorization using a registered policy
func (*Gate) Before ¶ added in v0.8.0
func (g *Gate) Before(callback BeforeCallback)
Before registers a callback to run before authorization checks
func (*Gate) Check ¶ added in v0.8.0
func (g *Gate) Check(user Authenticatable, abilities []string, args ...interface{}) bool
Check checks multiple abilities (all must pass)
func (*Gate) Define ¶ added in v0.8.0
func (g *Gate) Define(ability string, callback GateCallback)
Define registers a gate callback for an ability
func (*Gate) Denies ¶ added in v0.8.0
func (g *Gate) Denies(user Authenticatable, ability string, args ...interface{}) bool
Denies checks if a user is denied from performing an ability
func (*Gate) ForUser ¶ added in v0.8.0
func (g *Gate) ForUser(user Authenticatable) *UserGate
ForUser creates a user-scoped authorization checker
func (*Gate) HasAllRoles ¶ added in v0.8.0
func (g *Gate) HasAllRoles(user Authenticatable, roles ...string) bool
HasAllRoles checks if a user has all the given roles
func (*Gate) HasAnyRole ¶ added in v0.8.0
func (g *Gate) HasAnyRole(user Authenticatable, roles ...string) bool
HasAnyRole checks if a user has any of the given roles
func (*Gate) HasRole ¶ added in v0.8.0
func (g *Gate) HasRole(user Authenticatable, role string) bool
HasRole checks if a user has a specific role
func (*Gate) RegisterPolicy ¶ added in v0.8.0
Policy registers a policy for a resource type
func (*Gate) SetRoleChecker ¶ added in v0.8.0
func (g *Gate) SetRoleChecker(checker RoleChecker)
SetRoleChecker sets the function used to check user roles
type GateCallback ¶ added in v0.8.0
type GateCallback func(user Authenticatable, args ...interface{}) bool
GateCallback is a function that determines if a user can perform an action
type Guard ¶
type Guard interface {
// Check if user is authenticated
Check(r *http.Request) bool
// Get authenticated user
User(r *http.Request) Authenticatable
// Get user ID
ID(r *http.Request) interface{}
// Login user
Login(w http.ResponseWriter, r *http.Request, user Authenticatable, remember ...bool) error
// Login by user ID
LoginByID(w http.ResponseWriter, r *http.Request, id interface{}, remember ...bool) error
// Attempt login with credentials
Attempt(w http.ResponseWriter, r *http.Request, credentials map[string]interface{}, remember ...bool) (bool, error)
// Logout user
Logout(w http.ResponseWriter, r *http.Request) error
// Set user provider
SetProvider(provider UserProvider)
}
Guard defines authentication guard interface
type GuardConfig ¶
GuardConfig holds guard configuration
type Hasher ¶
type Hasher interface {
// Hash a password
Hash(password string) (string, error)
// Verify a password against a hash
Verify(password string, hash string) bool
// Check if hash needs rehashing
NeedsRehash(hash string) bool
}
Hasher handles password hashing and verification
type InMemoryBlacklistStore ¶ added in v0.9.2
type InMemoryBlacklistStore struct {
// contains filtered or unexported fields
}
InMemoryBlacklistStore is the default in-memory blacklist (not suitable for multi-instance deployments).
func NewInMemoryBlacklistStore ¶ added in v0.9.2
func NewInMemoryBlacklistStore() *InMemoryBlacklistStore
NewInMemoryBlacklistStore creates a new in-memory blacklist store.
func (*InMemoryBlacklistStore) Add ¶ added in v0.9.2
func (s *InMemoryBlacklistStore) Add(jti string, expiresAt time.Time)
func (*InMemoryBlacklistStore) Cleanup ¶ added in v0.9.2
func (s *InMemoryBlacklistStore) Cleanup()
func (*InMemoryBlacklistStore) IsBlacklisted ¶ added in v0.9.2
func (s *InMemoryBlacklistStore) IsBlacklisted(jti string) bool
type JWTConfig ¶
type JWTConfig struct {
Secret string
Algorithm string
TTL int // Minutes
RefreshTTL int // Minutes
Issuer string // Optional JWT issuer (iss claim)
Audience string // Optional JWT audience (aud claim)
BlacklistEnabled bool
BlacklistStore BlacklistStore // Optional persistent store; defaults to in-memory
}
JWTConfig holds JWT configuration
type JWTManager ¶
type JWTManager struct {
// contains filtered or unexported fields
}
JWTManager handles JWT operations
func NewJWTManager ¶
func NewJWTManager(config JWTConfig) *JWTManager
NewJWTManager creates a new JWT manager. Panics if Secret is empty or shorter than 32 bytes.
func (*JWTManager) CleanupBlacklist ¶
func (j *JWTManager) CleanupBlacklist()
CleanupBlacklist removes expired entries from blacklist
func (*JWTManager) GenerateRefreshToken ¶
func (j *JWTManager) GenerateRefreshToken(user Authenticatable) (string, error)
GenerateRefreshToken generates a refresh token
func (*JWTManager) GenerateToken ¶
func (j *JWTManager) GenerateToken(user Authenticatable, customClaims ...map[string]interface{}) (string, error)
GenerateToken generates a JWT token for a user
func (*JWTManager) IsBlacklisted ¶
func (j *JWTManager) IsBlacklisted(jti string) bool
IsBlacklisted checks if token is blacklisted
func (*JWTManager) ParseTokenWithoutValidation ¶
func (j *JWTManager) ParseTokenWithoutValidation(tokenString string) (*Claims, error)
ParseTokenWithoutValidation parses a token WITHOUT verifying its signature.
WARNING: This method is UNSAFE for authentication or authorization decisions. Claims returned by this method have NOT been verified and may have been tampered with. Only use this for non-security-sensitive operations such as extracting claims from expired tokens for logging or token rotation. Never trust the returned claims for granting access or making security decisions.
func (*JWTManager) RefreshToken ¶
func (j *JWTManager) RefreshToken(refreshTokenString string, provider UserProvider) (string, error)
RefreshToken creates a new token from a refresh token
func (*JWTManager) RevokeToken ¶
func (j *JWTManager) RevokeToken(jti string, expiresAt ...time.Time)
RevokeToken adds token to blacklist. If expiresAt is provided, use it as the blacklist expiry; otherwise falls back to the access token TTL.
func (*JWTManager) SetBlacklistStore ¶ added in v0.9.2
func (j *JWTManager) SetBlacklistStore(store BlacklistStore)
SetBlacklistStore replaces the blacklist store (e.g., swap in a Redis-backed store).
func (*JWTManager) ValidateToken ¶
func (j *JWTManager) ValidateToken(tokenString string) (*Claims, error)
ValidateToken validates a JWT token
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages multiple authentication guards
func NewManagerFromConfig ¶ added in v0.9.5
NewManagerFromConfig creates a new Manager configured from the provided Config.
func (*Manager) Attempt ¶ added in v0.9.5
func (m *Manager) Attempt(w http.ResponseWriter, r *http.Request, credentials map[string]interface{}, remember ...bool) (bool, error)
Attempt attempts login with credentials using the default guard.
func (*Manager) Check ¶ added in v0.9.5
Check returns true if the request is authenticated using the default guard.
func (*Manager) DefaultGuard ¶
DefaultGuard returns the default guard
func (*Manager) GetHasher ¶ added in v0.9.5
GetHasher returns the manager's hasher, falling back to a default bcrypt hasher.
func (*Manager) Login ¶ added in v0.9.5
func (m *Manager) Login(w http.ResponseWriter, r *http.Request, user Authenticatable, remember ...bool) error
Login logs in a user using the default guard.
func (*Manager) Provider ¶
func (m *Manager) Provider(name string) (UserProvider, error)
Provider returns a provider by name
func (*Manager) RegisterGuard ¶
RegisterGuard registers an authentication guard
func (*Manager) RegisterProvider ¶
func (m *Manager) RegisterProvider(name string, provider UserProvider)
RegisterProvider registers a user provider
func (*Manager) SetDefaultGuard ¶
SetDefaultGuard sets the default guard
type ORMUserProvider ¶
type ORMUserProvider struct {
// contains filtered or unexported fields
}
ORMUserProvider provides users from ORM models
func NewORMUserProvider ¶
func NewORMUserProvider(db *sql.DB, modelType string, hasher Hasher) *ORMUserProvider
NewORMUserProvider creates a new ORM user provider. If hasher is nil, a default bcrypt hasher is used.
func (*ORMUserProvider) FindByCredentials ¶
func (p *ORMUserProvider) FindByCredentials(credentials map[string]interface{}) (Authenticatable, error)
FindByCredentials finds user by credentials (email/username)
func (*ORMUserProvider) FindByID ¶
func (p *ORMUserProvider) FindByID(id interface{}) (Authenticatable, error)
FindByID finds user by ID
func (*ORMUserProvider) UpdateRememberToken ¶
func (p *ORMUserProvider) UpdateRememberToken(user Authenticatable, token string) error
UpdateRememberToken updates user's remember token and persists it to the database.
func (*ORMUserProvider) ValidateCredentials ¶
func (p *ORMUserProvider) ValidateCredentials(user Authenticatable, credentials map[string]interface{}) bool
ValidateCredentials validates user credentials
type Policy ¶ added in v0.8.0
type Policy interface {
// Authorize checks if user can perform action on the resource
Authorize(user Authenticatable, action string, resource interface{}) bool
}
Policy defines authorization logic for a specific resource type
type PolicyFunc ¶ added in v0.8.0
type PolicyFunc func(user Authenticatable, action string, resource interface{}) bool
PolicyFunc is a function adapter for simple policies
func (PolicyFunc) Authorize ¶ added in v0.8.0
func (f PolicyFunc) Authorize(user Authenticatable, action string, resource interface{}) bool
Authorize implements Policy interface
type ProviderConfig ¶
ProviderConfig holds provider configuration
type RoleChecker ¶ added in v0.8.0
type RoleChecker func(user Authenticatable, role string) bool
RoleChecker is a function that checks if a user has a role
type Session ¶
type Session interface {
// Get session ID
ID() string
// Get value from session
Get(key string) interface{}
// Put value in session
Put(key string, value interface{})
// Has checks if key exists
Has(key string) bool
// Remove value from session
Remove(key string)
// Clear all session data
Clear()
// Regenerate session ID
Regenerate() error
// Invalidate session
Invalidate() error
// Flash messages
Flash(key string, value interface{})
GetFlash(key string) interface{}
// Save session
Save(w http.ResponseWriter) error
}
Session represents a user session
func GetSessionFromRequest ¶
GetSessionFromRequest gets session from request
type SessionConfig ¶
type SessionConfig struct {
Driver string
Name string
Lifetime int // Minutes
Path string
Domain string
Secure bool
HttpOnly bool
SameSite http.SameSite
}
SessionConfig holds session configuration
func NewSessionConfigFromEnv ¶
func NewSessionConfigFromEnv() SessionConfig
NewSessionConfigFromEnv creates a SessionConfig from environment variables
type SessionStore ¶
type SessionStore interface {
// Create a new session
Create(id string) (Session, error)
// Get session by ID
Get(r *http.Request, id string) (Session, error)
// Save session
Save(w http.ResponseWriter, session Session) error
// Destroy session
Destroy(id string) error
// Garbage collection
GarbageCollect(maxLifetime time.Duration) error
}
SessionStore handles session storage
type UserGate ¶ added in v0.8.0
type UserGate struct {
// contains filtered or unexported fields
}
UserGate provides authorization methods for a specific user
func (*UserGate) Allows ¶ added in v0.8.0
Allows checks if the user is allowed to perform an ability
func (*UserGate) Authorize ¶ added in v0.8.0
Authorize checks authorization and returns an error if denied
type UserProvider ¶
type UserProvider interface {
// Retrieve user by ID
FindByID(id interface{}) (Authenticatable, error)
// Retrieve user by credentials
FindByCredentials(credentials map[string]interface{}) (Authenticatable, error)
// Validate user credentials
ValidateCredentials(user Authenticatable, credentials map[string]interface{}) bool
// Update remember token
UpdateRememberToken(user Authenticatable, token string) error
}
UserProvider handles user retrieval and validation