Documentation
¶
Index ¶
- Variables
- func ValidateEmail(email string) error
- func ValidatePassword(password string, policy PasswordPolicy) error
- type AuditAction
- type AuditEntry
- type AuditLogger
- type BcryptHasher
- type Claims
- type Config
- type ConsoleAuditLogger
- type Engine
- func (e *Engine) Authenticate(tokenString string) (string, error)
- func (e *Engine) ChangeEmail(ctx context.Context, userID, newEmail string) error
- func (e *Engine) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string) error
- func (e *Engine) DeleteAccount(ctx context.Context, userID string) error
- func (e *Engine) GetSessionStore() SessionStore
- func (e *Engine) GetUser(ctx context.Context, userID string) (*User, error)
- func (e *Engine) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (e *Engine) GetUserStore() UserStore
- func (e *Engine) ListSessions(ctx context.Context, userID string) ([]Session, error)
- func (e *Engine) Login(ctx context.Context, email, password string) (*TokenPair, *LimitResult, error)
- func (e *Engine) Logout(ctx context.Context, refreshToken string) error
- func (e *Engine) LogoutAll(ctx context.Context, userID string) error
- func (e *Engine) RefreshToken(ctx context.Context, refreshToken string) (*TokenPair, error)
- func (e *Engine) RevokeSession(ctx context.Context, sessionID string) error
- func (e *Engine) SignUp(ctx context.Context, email, password string) (*User, error)
- func (e *Engine) VerifyToken(tokenString string) (*Claims, error)
- func (e *Engine) WithAuditLogger(logger AuditLogger) *Engine
- func (e *Engine) WithHasher(hasher Hasher) *Engine
- func (e *Engine) WithJWTSecret(secret string) *Engine
- func (e *Engine) WithRateLimiter(limiter RateLimiter) *Engine
- type FileAuditLogger
- type Hasher
- type LimitResult
- type MemoryRateLimiter
- type MockHasher
- type NoopAuditLogger
- type NoopRateLimiter
- type PasswordPolicy
- type RateLimiter
- type Session
- type SessionStore
- type TokenPair
- type User
- type UserStore
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( // user errors ErrUserNotFound = errors.New("user not found") ErrUserExists = errors.New("user alredy exists") ErrInvalidEmail = errors.New("incorrect email format") // password errors ErrPasswordTooShort = errors.New("password must be at least 8 characters") ErrPasswordTooLong = errors.New("password execceds maximum lenght") ErrPasswordNoUpper = errors.New("password must contain an uppercase letter") ErrPasswordNoLower = errors.New("password must contain a lowercase letter") ErrPasswordNoNumber = errors.New("password must contain a number") // Rate limit errors ErrTooManyAttempts = errors.New("too many attempts, please try again later") // auth errors ErrInvalidCredentials = errors.New("invalid email or password") ErrInvalidToken = errors.New("invalid or expired token") // token errors ErrInvalidSession = errors.New("invalid or expired token") ErrSessionNotFound = errors.New("session not found") // Audit errors ErrAuditLogFailed = errors.New("Failed to write audit logs") )
Functions ¶
func ValidatePassword ¶
func ValidatePassword(password string, policy PasswordPolicy) error
ValidatePassword checks password against policy
Types ¶
type AuditAction ¶
type AuditAction string
AuditAction Represent what happened
const ( ActionSignUp AuditAction = "SIGN_UP" ActionSignInSuccess AuditAction = "SIGN_IN_SUCCESS" ActionSignInFailed AuditAction = "SIGN_IN_FAILED" ActionSignOut AuditAction = "SIGN_OUT" ActionSignOutAll AuditAction = "SIGN_OUT_ALL" ActionPasswordChange AuditAction = "PASSWORD_CHANGE" ActionEmailChange AuditAction = "EMAIL_CHANGE" ActionAccountDelete AuditAction = "ACCOUNT_DELETE" ActionTokenRefresh AuditAction = "TOKEN_REFRESH" ActionRateLimited AuditAction = "RATE_LIMITED" )
type AuditEntry ¶
type AuditEntry struct {
Timestamp time.Time
UserID string
Action AuditAction
Status string
Error string
IPAddress string
UserAgent string
Metadata map[string]interface{}
}
AuditEntry represents a single audit log entry
type AuditLogger ¶
type AuditLogger interface {
Log(ctx context.Context, entry AuditEntry) error
Close() error
}
AuditLogger defines how to log events
type BcryptHasher ¶
type BcryptHasher struct {
Cost int
}
BcryptHasher implement Hasher using bcrypt
func NewBcryptHasher ¶
func NewBcryptHasher(cost int) *BcryptHasher
func (*BcryptHasher) Compare ¶
func (h *BcryptHasher) Compare(password, hash string) error
type Claims ¶
type Claims struct {
UserID string `json: "user_id"`
jwt.RegisteredClaims
}
Claims represents JWT claims
type Config ¶
type Config struct {
PasswordPolicy PasswordPolicy
JWTSecret string
AccessTokenTTL time.Duration
RefreshTokenTTL time.Duration
Issuer string
TokenExpiry time.Duration
}
Config holds engine configuration
type ConsoleAuditLogger ¶
type ConsoleAuditLogger struct{}
ConsoleAuditLogger prints to the console
func NewConsoleAuditLogger ¶
func NewConsoleAuditLogger() *ConsoleAuditLogger
func (*ConsoleAuditLogger) Close ¶
func (l *ConsoleAuditLogger) Close() error
func (*ConsoleAuditLogger) Log ¶
func (l *ConsoleAuditLogger) Log(ctx context.Context, entry AuditEntry) error
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the main authentication engine
func New ¶
func New(users UserStore, sessions SessionStore) *Engine
New creates a new authentication engine
func (*Engine) Authenticate ¶
Authenticate extracts user ID from token
func (*Engine) ChangeEmail ¶
ChangeEmail updates user's email
func (*Engine) ChangePassword ¶
ChangePassword updates user's password and logs out all devices
func (*Engine) DeleteAccount ¶
DeleteAccount removes user and all sessions
func (*Engine) GetSessionStore ¶
func (e *Engine) GetSessionStore() SessionStore
GetSessionStore returns the session store (for testing)
func (*Engine) GetUserByEmail ¶
GetUserByEmail retrieves a user by email
func (*Engine) GetUserStore ¶
GetUserStore returns the user store (for testing)
func (*Engine) ListSessions ¶
ListSessions returns all active sessions for a user
func (*Engine) Login ¶
func (e *Engine) Login(ctx context.Context, email, password string) (*TokenPair, *LimitResult, error)
Login authenticates a user and returns tokens
func (*Engine) RefreshToken ¶
func (*Engine) RevokeSession ¶
RevokeSession manually revokes a specific session
func (*Engine) VerifyToken ¶
VerifyToken validates a JWT access token
func (*Engine) WithAuditLogger ¶
func (e *Engine) WithAuditLogger(logger AuditLogger) *Engine
func (*Engine) WithHasher ¶
func (*Engine) WithJWTSecret ¶
func (*Engine) WithRateLimiter ¶
func (e *Engine) WithRateLimiter(limiter RateLimiter) *Engine
type FileAuditLogger ¶
type FileAuditLogger struct {
// contains filtered or unexported fields
}
FileAuditLogger writes to a file
func NewFileAuditLogger ¶
func NewFileAuditLogger(filePath string) *FileAuditLogger
func (*FileAuditLogger) Close ¶
func (l *FileAuditLogger) Close() error
func (*FileAuditLogger) Log ¶
func (l *FileAuditLogger) Log(ctx context.Context, entry AuditEntry) error
type Hasher ¶
type Hasher interface {
Hash(password string) (string, error)
Compare(password, hash string) error
}
Hasher defines password opperation
type LimitResult ¶
LimitResult contains rate limit info for response headers
type MemoryRateLimiter ¶
type MemoryRateLimiter struct {
// contains filtered or unexported fields
}
MemoryRateLimiter implements RateLimiter in memory
func NewMemoryRateLimiter ¶
func NewMemoryRateLimiter(limit int, window time.Duration) *MemoryRateLimiter
NewMemoryRateLimiter creates new memory rate limiter
func (*MemoryRateLimiter) Allow ¶
func (r *MemoryRateLimiter) Allow(ctx context.Context, key string) (LimitResult, error)
Allow checks if a is whithin rate limit
type MockHasher ¶
type MockHasher struct{}
MockHasher for fast tests
func (*MockHasher) Compare ¶
func (h *MockHasher) Compare(password, hash string) error
type NoopAuditLogger ¶
type NoopAuditLogger struct{}
NoopAuditLogger dose nothing just for testing
func NewNoopAuditLogger ¶
func NewNoopAuditLogger() *NoopAuditLogger
func (*NoopAuditLogger) Close ¶
func (l *NoopAuditLogger) Close() error
func (*NoopAuditLogger) Log ¶
func (l *NoopAuditLogger) Log(ctx context.Context, entry AuditEntry) error
type NoopRateLimiter ¶
type NoopRateLimiter struct{}
NoopRateLimiter for testing - allows everything
func (*NoopRateLimiter) Allow ¶
func (r *NoopRateLimiter) Allow(ctx context.Context, key string) (LimitResult, error)
type PasswordPolicy ¶
type PasswordPolicy struct {
MinLenght int
MaxLenght int
RequireUpper bool
RequireLower bool
RequireNumber bool
RequireSpecial bool
}
PasswordPolicy defines rules for passwords
func DefaultPasswordPolicy ¶
func DefaultPasswordPolicy() PasswordPolicy
DefaultPasswordPolicy returns sensible defauls
type RateLimiter ¶
type RateLimiter interface {
// Allow checks if requst is parmitted
Allow(ctx context.Context, key string) (LimitResult, error)
// Reset clears limit for a key
Reset(ctx context.Context, key string) error
}
RateLimiter defines how rate limiting works
type Session ¶
type Session struct {
ID string
UserID string
RefreshToken string
CreatedAt time.Time
UpdatedAt time.Time
ExpiresAt time.Time
}
Session represents a user Session
type SessionStore ¶
type SessionStore interface {
Create(ctx context.Context, userID string) (*Session, error)
GetByRefreshToken(ctx context.Context, refreshToken string) (*Session, error)
Revoke(ctx context.Context, sessionID string) error
RevokeAllForUser(ctx context.Context, userID string) error
ListForUser(ctx context.Context, userID string) ([]Session, error)
}
SessionStore defines how we store retrieve sessions
type TokenPair ¶
type TokenPair struct {
AccessToken string `json: "access_token"`
RefreshToken string `json: "refresh_token"`
TokenType string `json: "token_type"`
ExpiresIn int64 `json: "expires_in"`
}
contains access and refresh tokens for a user
type User ¶
type User struct {
ID string
Email string
PasswordHash string
CreatedAt time.Time
UpdatedAt time.Time
}
User represents a user in the system
type UserStore ¶
type UserStore interface {
Create(ctx context.Context, email, passwordHash string) (*User, error)
GetByEmail(ctx context.Context, email string) (*User, error)
GetByID(ctx context.Context, id string) (*User, error)
UpdateEmail(ctx context.Context, id, newEmail string) error
UpdatePassword(ctx context.Context, id, newPasswordHash string) error
Delete(ctx context.Context, id string) error
}
UserStore defines how we store and retrieve users ANY database can implement this interface
type ValidationError ¶
validation error provides field level error details
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error