auth

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package auth provides authentication services for LacyLights.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAuthDisabled       = errors.New("authentication is not enabled")
	ErrUserNotFound       = errors.New("user not found")
	ErrUserExists         = errors.New("user already exists")
	ErrInvalidCredentials = errors.New("invalid email or password")
	ErrInvalidEmail       = errors.New("invalid email format")
	ErrAccountLocked      = errors.New("account is locked")
	ErrAccountInactive    = errors.New("account is inactive")
	ErrPasswordTooShort   = errors.New("password is too short")
	ErrSessionNotFound    = errors.New("session not found")
	ErrSessionExpired     = errors.New("session has expired")
)

Errors

View Source
var (
	ErrInvalidToken     = errors.New("invalid token")
	ErrExpiredToken     = errors.New("token has expired")
	ErrInvalidTokenType = errors.New("invalid token type")
)

JWTError represents errors from JWT operations.

View Source
var ErrHashMismatch = errors.New("password does not match hash")

ErrHashMismatch is returned when the password doesn't match the hash.

View Source
var ErrInvalidHash = errors.New("invalid password hash format")

ErrInvalidHash is returned when the hash format is invalid.

Functions

func GenerateSecureToken

func GenerateSecureToken(length int) (string, error)

GenerateSecureToken generates a cryptographically secure random token. Used for verification tokens, password reset tokens, etc.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes a password using Argon2id. Returns the hash in the format: $argon2id$v=19$m=65536,t=1,p=4$<salt>$<hash>

func HashToken

func HashToken(token string) string

HashToken creates a hash of a token for storage. Uses SHA-256 to create a deterministic hash that can be looked up. This is appropriate for high-entropy tokens (like session IDs) where we need consistent hashing for lookups.

func VerifyPassword

func VerifyPassword(password, encodedHash string) error

VerifyPassword verifies a password against an Argon2id hash. Returns nil if the password matches, ErrHashMismatch if it doesn't.

Types

type AuthResult

type AuthResult struct {
	User         *models.User
	AccessToken  string
	RefreshToken string
	ExpiresAt    time.Time
	SessionID    string
}

AuthResult holds the result of a successful authentication.

type Claims

type Claims struct {
	jwt.RegisteredClaims
	UserID    string    `json:"uid"`
	Email     string    `json:"email"`
	Role      string    `json:"role"`
	SessionID string    `json:"sid"`
	TokenType TokenType `json:"type"`
}

Claims represents the JWT claims for LacyLights tokens.

type Config

type Config struct {
	// Database connection
	DB *gorm.DB

	// JWT configuration
	JWTSecret          string
	JWTIssuer          string
	JWTAccessTokenTTL  time.Duration
	JWTRefreshTokenTTL time.Duration

	// Session configuration
	SessionDurationHours int
	CacheMaxSize         int
	CacheTTL             time.Duration

	// Password configuration
	PasswordMinLength int

	// Feature flags
	Enabled           bool
	DeviceAuthEnabled bool
}

Config holds configuration for the auth service.

type JWTConfig

type JWTConfig struct {
	Secret          string
	Issuer          string
	AccessTokenTTL  time.Duration
	RefreshTokenTTL time.Duration
}

JWTConfig holds configuration for the JWT service.

type JWTService

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

JWTService handles JWT token generation and validation.

func NewJWTService

func NewJWTService(cfg JWTConfig) (*JWTService, error)

NewJWTService creates a new JWT service with the given configuration. If the secret is empty, a new random secret is generated.

func (*JWTService) AccessTokenTTL

func (s *JWTService) AccessTokenTTL() time.Duration

AccessTokenTTL returns the access token TTL.

func (*JWTService) GenerateAccessToken

func (s *JWTService) GenerateAccessToken(userID, email, role, sessionID string) (string, time.Time, error)

GenerateAccessToken generates a new access token for a user.

func (*JWTService) GenerateTokenPair

func (s *JWTService) GenerateTokenPair(userID, email, role, sessionID string) (*TokenPair, error)

GenerateTokenPair generates a new access/refresh token pair for a user.

func (*JWTService) GetSecret

func (s *JWTService) GetSecret() string

GetSecret returns the JWT secret (for testing or backup purposes).

func (*JWTService) RefreshTokenTTL

func (s *JWTService) RefreshTokenTTL() time.Duration

RefreshTokenTTL returns the refresh token TTL.

func (*JWTService) ValidateAccessToken

func (s *JWTService) ValidateAccessToken(tokenString string) (*Claims, error)

ValidateAccessToken validates an access token specifically.

func (*JWTService) ValidateRefreshToken

func (s *JWTService) ValidateRefreshToken(tokenString string) (*Claims, error)

ValidateRefreshToken validates a refresh token specifically.

func (*JWTService) ValidateToken

func (s *JWTService) ValidateToken(tokenString string) (*Claims, error)

ValidateToken validates a JWT token and returns the claims.

type RegisterInput

type RegisterInput struct {
	Email    string
	Password string
	Name     *string
}

RegisterInput holds input for registering a new user.

type Service

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

Service provides authentication functionality.

func NewService

func NewService(cfg Config) (*Service, error)

NewService creates a new authentication service.

func (*Service) ChangePassword

func (s *Service) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string) error

ChangePassword changes a user's password.

func (*Service) EnsureDefaultAdmin

func (s *Service) EnsureDefaultAdmin(ctx context.Context, email, password string) error

EnsureDefaultAdmin creates the default admin user if no users exist. This is called on startup when auth is enabled to ensure there's at least one admin user to manage the system.

func (*Service) GetUserByEmail

func (s *Service) GetUserByEmail(ctx context.Context, email string) (*models.User, error)

GetUserByEmail retrieves a user by their email.

func (*Service) GetUserByID

func (s *Service) GetUserByID(ctx context.Context, userID string) (*models.User, error)

GetUserByID retrieves a user by their ID.

func (*Service) GetUserSessions

func (s *Service) GetUserSessions(ctx context.Context, userID string) ([]models.Session, error)

GetUserSessions retrieves all active sessions for a user.

func (*Service) IsDeviceAuthEnabled

func (s *Service) IsDeviceAuthEnabled() bool

IsDeviceAuthEnabled returns whether device authentication is enabled.

func (*Service) IsEnabled

func (s *Service) IsEnabled() bool

IsEnabled returns whether authentication is enabled.

func (*Service) JWTService

func (s *Service) JWTService() *JWTService

JWTService returns the JWT service for middleware use.

func (*Service) Login

func (s *Service) Login(ctx context.Context, email, password string, ipAddress, userAgent *string) (*AuthResult, error)

Login authenticates a user with email and password.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, sessionID string) error

Logout invalidates a session.

func (*Service) LogoutAll

func (s *Service) LogoutAll(ctx context.Context, userID string) error

LogoutAll invalidates all sessions for a user.

func (*Service) RefreshToken

func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (*AuthResult, error)

RefreshToken generates new tokens using a refresh token.

func (*Service) Register

func (s *Service) Register(ctx context.Context, input RegisterInput, ipAddress, userAgent *string) (*AuthResult, error)

Register creates a new user account with email/password.

func (*Service) SessionManager

func (s *Service) SessionManager() *session.Manager

SessionManager returns the session manager.

func (*Service) ValidateSession

func (s *Service) ValidateSession(ctx context.Context, accessToken string) (*session.CachedSession, error)

ValidateSession validates an access token and returns the session info.

type TokenPair

type TokenPair struct {
	AccessToken  string    `json:"accessToken"`
	RefreshToken string    `json:"refreshToken"`
	ExpiresAt    time.Time `json:"expiresAt"`
}

TokenPair represents an access/refresh token pair.

type TokenType

type TokenType string

TokenType represents the type of JWT token.

const (
	// TokenTypeAccess is a short-lived token for API access.
	TokenTypeAccess TokenType = "access"
	// TokenTypeRefresh is a long-lived token for obtaining new access tokens.
	TokenTypeRefresh TokenType = "refresh"
)

Directories

Path Synopsis
Package session provides session management for authentication.
Package session provides session management for authentication.

Jump to

Keyboard shortcuts

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