auth

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 14 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

Functions

func Attempt

func Attempt(w http.ResponseWriter, r *http.Request, credentials map[string]interface{}, remember ...bool) (bool, error)

Attempt login with credentials using default guard

func Check

func Check(r *http.Request) bool

Check if user is authenticated using default guard

func Guest

func Guest(redirectTo string) func(http.Handler) http.Handler

Guest middleware - redirects authenticated users

func Hash

func Hash(password string) (string, error)

Hash hashes a password using the global hasher

func ID

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

ID returns authenticated user ID using default guard

func Init

func Init(config Config) error

Init initializes the global auth manager

func InitHasher

func InitHasher(hasher Hasher)

InitHasher initializes the global hasher

func Login

func Login(w http.ResponseWriter, r *http.Request, user Authenticatable, remember ...bool) error

Login logs in a user using default guard

func LoginByID

func LoginByID(w http.ResponseWriter, r *http.Request, id interface{}, remember ...bool) error

LoginByID logs in a user by ID using default guard

func Logout

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

Logout logs out user using default guard

func Middleware

func Middleware(redirectTo string) func(http.Handler) http.Handler

Middleware that requires authentication

func NeedsRehash

func NeedsRehash(hash string) bool

NeedsRehash checks if a hash needs rehashing using the global hasher

func RedirectIfAuthenticated

func RedirectIfAuthenticated(redirectTo string) func(http.Handler) http.Handler

RedirectIfAuthenticated middleware - same as Guest but with clearer name

func RequireAuth

func RequireAuth(redirectTo string) func(http.Handler) http.Handler

RequireAuth is an alias for Middleware

func Verify

func Verify(password string, hash string) bool

Verify verifies a password against a hash using the global hasher

Types

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

func User

func User(r *http.Request) Authenticatable

User returns authenticated user using default guard

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

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 Claims

type Claims struct {
	jwt.RegisteredClaims
	UserID interface{} `json:"uid,omitempty"`
	Email  string      `json:"email,omitempty"`
	Role   string      `json:"role,omitempty"`
}

Claims represents JWT claims

type Config

type Config struct {
	DefaultGuard string
	Guards       map[string]GuardConfig
	Providers    map[string]ProviderConfig
}

Config holds authentication configuration

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

func GetGuard

func GetGuard(name string) (Guard, error)

GetGuard returns a guard by name from global manager

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

func GetHasher

func GetHasher() Hasher

GetHasher returns the global hasher

type JWTConfig

type JWTConfig struct {
	Secret           string
	Algorithm        string
	TTL              int // Minutes
	RefreshTTL       int // Minutes
	BlacklistEnabled bool
}

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

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 token without validating signature Useful for extracting claims from expired tokens

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)

RevokeToken adds token to blacklist

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 GetManager

func GetManager() (*Manager, error)

GetManager returns the global auth manager

func NewManager

func NewManager() *Manager

NewManager creates a new auth manager

func (*Manager) DefaultGuard

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

DefaultGuard returns the default guard

func (*Manager) Guard

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

Guard returns a guard by name

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

type ORMUserProvider

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

ORMUserProvider provides users from ORM models

func NewORMUserProvider

func NewORMUserProvider(modelType string) *ORMUserProvider

NewORMUserProvider creates a new ORM user provider

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

func (*ORMUserProvider) ValidateCredentials

func (p *ORMUserProvider) ValidateCredentials(user Authenticatable, credentials map[string]interface{}) bool

ValidateCredentials validates user credentials

type ProviderConfig

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

ProviderConfig holds provider configuration

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