core

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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

func ValidateEmail(email string) error

ValidateEmail checks if email is valid

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

func (*BcryptHasher) Hash

func (h *BcryptHasher) Hash(password string) (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

func DefautConfig

func DefautConfig() Config

DefautConfig returns sensible defaults

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

func (e *Engine) Authenticate(tokenString string) (string, error)

Authenticate extracts user ID from token

func (*Engine) ChangeEmail

func (e *Engine) ChangeEmail(ctx context.Context, userID, newEmail string) error

ChangeEmail updates user's email

func (*Engine) ChangePassword

func (e *Engine) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string) error

ChangePassword updates user's password and logs out all devices

func (*Engine) DeleteAccount

func (e *Engine) DeleteAccount(ctx context.Context, userID string) error

DeleteAccount removes user and all sessions

func (*Engine) GetSessionStore

func (e *Engine) GetSessionStore() SessionStore

GetSessionStore returns the session store (for testing)

func (*Engine) GetUser

func (e *Engine) GetUser(ctx context.Context, userID string) (*User, error)

GetUser retrieves a user by ID

func (*Engine) GetUserByEmail

func (e *Engine) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail retrieves a user by email

func (*Engine) GetUserStore

func (e *Engine) GetUserStore() UserStore

GetUserStore returns the user store (for testing)

func (*Engine) ListSessions

func (e *Engine) ListSessions(ctx context.Context, userID string) ([]Session, error)

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

func (e *Engine) Logout(ctx context.Context, refreshToken string) error

Logout revokes the current session

func (*Engine) LogoutAll

func (e *Engine) LogoutAll(ctx context.Context, userID string) error

LogoutAll revokes ALL sessions for a user

func (*Engine) RefreshToken

func (e *Engine) RefreshToken(ctx context.Context, refreshToken string) (*TokenPair, error)

func (*Engine) RevokeSession

func (e *Engine) RevokeSession(ctx context.Context, sessionID string) error

RevokeSession manually revokes a specific session

func (*Engine) SignUp

func (e *Engine) SignUp(ctx context.Context, email, password string) (*User, error)

SignUp creates a new user account

func (*Engine) VerifyToken

func (e *Engine) VerifyToken(tokenString string) (*Claims, error)

VerifyToken validates a JWT access token

func (*Engine) WithAuditLogger

func (e *Engine) WithAuditLogger(logger AuditLogger) *Engine

func (*Engine) WithHasher

func (e *Engine) WithHasher(hasher Hasher) *Engine

func (*Engine) WithJWTSecret

func (e *Engine) WithJWTSecret(secret string) *Engine

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

type LimitResult struct {
	Allowed   bool
	Limit     int
	Remaining int
	Reset     time.Duration
}

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

func (*MemoryRateLimiter) Reset

func (r *MemoryRateLimiter) Reset(ctx context.Context, key string) error

Reset clears rate limit for a key

type MockHasher

type MockHasher struct{}

MockHasher for fast tests

func (*MockHasher) Compare

func (h *MockHasher) Compare(password, hash string) error

func (*MockHasher) Hash

func (h *MockHasher) Hash(password string) (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)

func (*NoopRateLimiter) Reset

func (r *NoopRateLimiter) Reset(ctx context.Context, key string) 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

type ValidationError struct {
	Field   string
	Message string
	Err     error
}

validation error provides field level error details

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Jump to

Keyboard shortcuts

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