auth

package
v0.9.16 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
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

View Source
var (
	ErrUnauthorized    = errors.New("unauthorized action")
	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

func (u *AuthUser) GetAuthPassword() string

GetAuthPassword returns user password hash

func (*AuthUser) GetRememberToken added in v0.2.4

func (u *AuthUser) GetRememberToken() string

GetRememberToken returns remember token

func (*AuthUser) SetRememberToken added in v0.2.4

func (u *AuthUser) SetRememberToken(token string)

SetRememberToken sets remember token

func (*AuthUser) String added in v0.2.4

func (u *AuthUser) String() string

String returns string representation

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 NewSession

func NewSession(id string) *BaseSession

NewSession creates a new session

func (*BaseSession) Clear

func (s *BaseSession) Clear()

Clear clears all session data

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) Has

func (s *BaseSession) Has(key string) bool

Has checks if key exists

func (*BaseSession) ID

func (s *BaseSession) ID() string

ID returns session ID

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

func (*BcryptHasher) Verify

func (h *BcryptHasher) Verify(password string, hash string) bool

Verify verifies a password against a hash

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

func ConfigFromEnv() (Config, bool)

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 NewGate added in v0.8.0

func NewGate() *Gate

NewGate creates a new Gate instance

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

func (g *Gate) RegisterPolicy(resourceType string, policy Policy)

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

type GuardConfig struct {
	Driver   string
	Provider string
	Options  map[string]interface{}
}

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 FromContext added in v0.9.13

func FromContext(ctx *router.Context) *Manager

FromContext extracts the *Manager from a router.Context. Returns nil if auth is not configured.

func NewManager

func NewManager() *Manager

NewManager creates a new auth manager

func NewManagerFromConfig added in v0.9.5

func NewManagerFromConfig(config Config) (*Manager, error)

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

func (m *Manager) Check(r *http.Request) bool

Check returns true if the request is authenticated using the default guard.

func (*Manager) DefaultGuard

func (m *Manager) DefaultGuard() (Guard, error)

DefaultGuard returns the default guard

func (*Manager) GetHasher added in v0.9.5

func (m *Manager) GetHasher() Hasher

GetHasher returns the manager's hasher, falling back to a default bcrypt hasher.

func (*Manager) Guard

func (m *Manager) Guard(name string) (Guard, error)

Guard returns a guard by name

func (*Manager) Hash added in v0.9.5

func (m *Manager) Hash(password string) (string, error)

Hash hashes a password using the manager's hasher.

func (*Manager) ID added in v0.9.5

func (m *Manager) ID(r *http.Request) interface{}

ID returns the authenticated user ID using the default guard.

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) Logout added in v0.9.5

func (m *Manager) Logout(w http.ResponseWriter, r *http.Request) error

Logout logs out the 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

func (m *Manager) RegisterGuard(name string, guard Guard)

RegisterGuard registers an authentication guard

func (*Manager) RegisterProvider

func (m *Manager) RegisterProvider(name string, provider UserProvider)

RegisterProvider registers a user provider

func (*Manager) SetDefaultGuard

func (m *Manager) SetDefaultGuard(name string)

SetDefaultGuard sets the default guard

func (*Manager) SetHasher added in v0.9.5

func (m *Manager) SetHasher(h Hasher)

SetHasher sets the hasher on the manager.

func (*Manager) User added in v0.9.5

func (m *Manager) User(r *http.Request) Authenticatable

User returns the authenticated user using the default guard.

func (*Manager) Verify added in v0.9.5

func (m *Manager) Verify(password string, hash string) bool

Verify verifies a password against a hash using the manager's hasher.

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

type ProviderConfig struct {
	Driver  string
	Model   string
	Options map[string]interface{}
}

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

func GetSessionFromRequest(r *http.Request, store SessionStore, name string) (Session, error)

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

func (ug *UserGate) Allows(ability string, args ...interface{}) bool

Allows checks if the user is allowed to perform an ability

func (*UserGate) Authorize added in v0.8.0

func (ug *UserGate) Authorize(ability string, args ...interface{}) error

Authorize checks authorization and returns an error if denied

func (*UserGate) Can added in v0.8.0

func (ug *UserGate) Can(ability string, args ...interface{}) bool

Can is an alias for Allows

func (*UserGate) Cannot added in v0.8.0

func (ug *UserGate) Cannot(ability string, args ...interface{}) bool

Cannot is an alias for Denies

func (*UserGate) Denies added in v0.8.0

func (ug *UserGate) Denies(ability string, args ...interface{}) bool

Denies checks if the user is denied from performing an ability

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

Directories

Path Synopsis
drivers

Jump to

Keyboard shortcuts

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