auth

package
v0.0.0-...-73dc379 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// TOTPIssuer is the issuer name shown in authenticator apps.
	TOTPIssuer = "Caddyshack"

	// BackupCodeCount is the number of backup codes to generate.
	BackupCodeCount = 10

	// BackupCodeLength is the length of each backup code (in characters).
	BackupCodeLength = 8
)
View Source
const SessionDuration = 24 * time.Hour

SessionDuration is how long a session is valid.

View Source
const TokenLength = 32

TokenLength is the number of random bytes in a token (before encoding).

View Source
const TokenPrefix = "csk_"

TokenPrefix is the prefix for API tokens for easy identification.

Variables

View Source
var (
	// ErrTokenNotFound is returned when a token is not found.
	ErrTokenNotFound = errors.New("token not found")

	// ErrTokenExpired is returned when a token has expired.
	ErrTokenExpired = errors.New("token expired")

	// ErrTokenRevoked is returned when a token has been revoked.
	ErrTokenRevoked = errors.New("token revoked")

	// ErrInvalidToken is returned when a token is invalid.
	ErrInvalidToken = errors.New("invalid token")

	// ErrTokenNameExists is returned when a token name already exists for a user.
	ErrTokenNameExists = errors.New("token name already exists")
)
View Source
var (
	// ErrTOTPAlreadyEnabled is returned when trying to enable 2FA when it's already enabled.
	ErrTOTPAlreadyEnabled = errors.New("two-factor authentication is already enabled")

	// ErrTOTPNotEnabled is returned when trying to use 2FA when it's not enabled.
	ErrTOTPNotEnabled = errors.New("two-factor authentication is not enabled")

	// ErrInvalidTOTPCode is returned when a TOTP code is invalid.
	ErrInvalidTOTPCode = errors.New("invalid verification code")

	// ErrInvalidBackupCode is returned when a backup code is invalid.
	ErrInvalidBackupCode = errors.New("invalid backup code")

	// ErrNoBackupCodes is returned when there are no unused backup codes.
	ErrNoBackupCodes = errors.New("no backup codes available")
)
View Source
var (
	// ErrUserNotFound is returned when a user is not found.
	ErrUserNotFound = errors.New("user not found")

	// ErrInvalidCredentials is returned when credentials are invalid.
	ErrInvalidCredentials = errors.New("invalid credentials")

	// ErrUsernameExists is returned when a username already exists.
	ErrUsernameExists = errors.New("username already exists")

	// ErrInvalidRole is returned when an invalid role is specified.
	ErrInvalidRole = errors.New("invalid role")

	// ErrSessionNotFound is returned when a session is not found.
	ErrSessionNotFound = errors.New("session not found")

	// ErrSessionExpired is returned when a session has expired.
	ErrSessionExpired = errors.New("session expired")
)
View Source
var DefaultWidgetOrder = []string{"sites", "snippets", "containers", "certificates", "status"}

DefaultWidgetOrder is the default order of dashboard widgets.

ValidRoles is a list of all valid roles.

ValidScopes is a list of all valid token scopes.

Functions

func CheckBackupCode

func CheckBackupCode(code, hash string) bool

CheckBackupCode compares a backup code with its hash.

func CheckPassword

func CheckPassword(password, hash string) bool

CheckPassword compares a password with its hash.

func GenerateBackupCodes

func GenerateBackupCodes(count int) ([]string, error)

GenerateBackupCodes generates a set of backup codes.

func HashBackupCode

func HashBackupCode(code string) (string, error)

HashBackupCode hashes a backup code for storage.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes a password using bcrypt.

func TokenHasPermission

func TokenHasPermission(token *APIToken, perm Permission) bool

TokenHasPermission checks if a token has the specified permission.

func ValidateTOTPCode

func ValidateTOTPCode(code, secret string) bool

ValidateTOTPCode validates a TOTP code against a secret.

Types

type APIToken

type APIToken struct {
	ID         int64
	UserID     int64
	TokenHash  string
	Name       string
	Scopes     []TokenScope
	CreatedAt  time.Time
	ExpiresAt  *time.Time
	LastUsedAt *time.Time
	RevokedAt  *time.Time
}

APIToken represents an API token in the database.

func (*APIToken) HasAdminAccess

func (t *APIToken) HasAdminAccess() bool

HasAdminAccess returns true if the token has admin scope.

func (*APIToken) HasScope

func (t *APIToken) HasScope(scope TokenScope) bool

HasScope checks if the token has the specified scope.

func (*APIToken) HasWriteAccess

func (t *APIToken) HasWriteAccess() bool

HasWriteAccess returns true if the token has write or admin scope.

func (*APIToken) IsExpired

func (t *APIToken) IsExpired() bool

IsExpired returns true if the token has expired.

func (*APIToken) IsRevoked

func (t *APIToken) IsRevoked() bool

IsRevoked returns true if the token has been revoked.

func (*APIToken) IsValid

func (t *APIToken) IsValid() bool

IsValid returns true if the token is not expired and not revoked.

type BackupCode

type BackupCode struct {
	ID        int64
	UserID    int64
	CodeHash  string
	UsedAt    *time.Time
	CreatedAt time.Time
}

BackupCode represents a backup code for account recovery.

type DashboardPreferences

type DashboardPreferences struct {
	UserID           int64
	WidgetOrder      []string
	HiddenWidgets    []string
	CollapsedWidgets []string
}

DashboardPreferences represents a user's dashboard layout preferences.

func DefaultDashboardPreferences

func DefaultDashboardPreferences(userID int64) *DashboardPreferences

DefaultDashboardPreferences returns the default dashboard preferences.

func (*DashboardPreferences) IsWidgetCollapsed

func (p *DashboardPreferences) IsWidgetCollapsed(widgetID string) bool

IsWidgetCollapsed checks if a widget is collapsed.

func (*DashboardPreferences) IsWidgetHidden

func (p *DashboardPreferences) IsWidgetHidden(widgetID string) bool

IsWidgetHidden checks if a widget is hidden.

type NotificationPreferences

type NotificationPreferences struct {
	UserID              int64
	NotifyCertExpiry    bool
	NotifyDomainExpiry  bool
	NotifyConfigChange  bool
	NotifyCaddyReload   bool
	NotifyContainerDown bool
	NotifySystem        bool
}

NotificationPreferences represents a user's notification preferences.

func DefaultNotificationPreferences

func DefaultNotificationPreferences(userID int64) *NotificationPreferences

DefaultNotificationPreferences returns the default notification preferences.

type Permission

type Permission string

Permission represents an action that can be performed.

const (
	// PermViewDashboard allows viewing the dashboard.
	PermViewDashboard Permission = "view:dashboard"

	// PermViewSites allows viewing sites.
	PermViewSites Permission = "view:sites"

	// PermEditSites allows creating, editing, and deleting sites.
	PermEditSites Permission = "edit:sites"

	// PermViewSnippets allows viewing snippets.
	PermViewSnippets Permission = "view:snippets"

	// PermEditSnippets allows creating, editing, and deleting snippets.
	PermEditSnippets Permission = "edit:snippets"

	// PermViewGlobal allows viewing global options.
	PermViewGlobal Permission = "view:global"

	// PermEditGlobal allows editing global options.
	PermEditGlobal Permission = "edit:global"

	// PermViewHistory allows viewing config history.
	PermViewHistory Permission = "view:history"

	// PermRestoreHistory allows restoring config from history.
	PermRestoreHistory Permission = "restore:history"

	// PermViewLogs allows viewing logs.
	PermViewLogs Permission = "view:logs"

	// PermViewCerts allows viewing certificates.
	PermViewCerts Permission = "view:certs"

	// PermViewContainers allows viewing containers.
	PermViewContainers Permission = "view:containers"

	// PermManageContainers allows managing containers (start/stop/restart).
	PermManageContainers Permission = "manage:containers"

	// PermViewDomains allows viewing domains.
	PermViewDomains Permission = "view:domains"

	// PermEditDomains allows editing domains.
	PermEditDomains Permission = "edit:domains"

	// PermImportExport allows importing and exporting configuration.
	PermImportExport Permission = "import:export"

	// PermViewNotifications allows viewing notifications.
	PermViewNotifications Permission = "view:notifications"

	// PermManageNotifications allows acknowledging notifications.
	PermManageNotifications Permission = "manage:notifications"

	// PermViewUsers allows viewing users.
	PermViewUsers Permission = "view:users"

	// PermManageUsers allows creating, editing, and deleting users.
	PermManageUsers Permission = "manage:users"

	// PermViewAuditLog allows viewing the audit log.
	PermViewAuditLog Permission = "view:audit"
)

func ScopeToPermissions

func ScopeToPermissions(scope TokenScope) []Permission

ScopeToPermissions maps a token scope to the permissions it grants.

type Role

type Role string

Role represents a user's role in the system.

const (
	// RoleAdmin has full access to all features.
	RoleAdmin Role = "admin"

	// RoleEditor can manage sites and snippets but not users or global settings.
	RoleEditor Role = "editor"

	// RoleViewer has read-only access.
	RoleViewer Role = "viewer"
)

func (Role) CanEdit

func (r Role) CanEdit() bool

CanEdit returns true if the role can edit content (sites, snippets, etc.)

func (Role) CanEditGlobal

func (r Role) CanEditGlobal() bool

CanEditGlobal returns true if the role can edit global settings.

func (Role) CanManageUsers

func (r Role) CanManageUsers() bool

CanManageUsers returns true if the role can manage users.

func (Role) GetPermissions

func (r Role) GetPermissions() []Permission

GetPermissions returns all permissions for a role.

func (Role) HasPermission

func (r Role) HasPermission(perm Permission) bool

HasPermission checks if a role has a specific permission.

func (Role) IsValid

func (r Role) IsValid() bool

IsValid checks if the role is a valid role.

func (Role) String

func (r Role) String() string

String returns the string representation of the role.

type Session

type Session struct {
	ID        int64
	UserID    int64
	Token     string
	CreatedAt time.Time
	ExpiresAt time.Time
}

Session represents an authenticated user session.

type TOTPSetup

type TOTPSetup struct {
	Secret     string
	QRCodeData string // Base64 encoded PNG
	URL        string
}

TOTPSetup holds the information needed to set up 2FA.

func GenerateTOTPSecret

func GenerateTOTPSecret(username string) (*TOTPSetup, error)

GenerateTOTPSecret generates a new TOTP secret for a user.

type TOTPStore

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

TOTPStore provides database operations for TOTP and backup codes.

func NewTOTPStore

func NewTOTPStore(db *sql.DB) *TOTPStore

NewTOTPStore creates a new TOTPStore.

func (*TOTPStore) DisableTOTP

func (s *TOTPStore) DisableTOTP(userID int64) error

DisableTOTP disables 2FA for a user and clears their backup codes.

func (*TOTPStore) EnableTOTP

func (s *TOTPStore) EnableTOTP(userID int64) error

EnableTOTP enables 2FA for a user after they've verified the code.

func (*TOTPStore) GetBackupCodeCount

func (s *TOTPStore) GetBackupCodeCount(userID int64) (int, error)

GetBackupCodeCount returns the number of unused backup codes for a user.

func (*TOTPStore) GetTOTPStatus

func (s *TOTPStore) GetTOTPStatus(userID int64) (enabled bool, secret string, verifiedAt *time.Time, err error)

GetTOTPStatus returns whether 2FA is enabled for a user and when it was enabled.

func (*TOTPStore) HasBackupCodes

func (s *TOTPStore) HasBackupCodes(userID int64) (bool, error)

HasBackupCodes returns true if the user has any unused backup codes.

func (*TOTPStore) SaveBackupCodes

func (s *TOTPStore) SaveBackupCodes(userID int64, codes []string) error

SaveBackupCodes saves a set of backup codes for a user. It first deletes any existing backup codes.

func (*TOTPStore) SetTOTPSecret

func (s *TOTPStore) SetTOTPSecret(userID int64, secret string) error

SetTOTPSecret sets the TOTP secret for a user (before verification).

func (*TOTPStore) ValidateBackupCode

func (s *TOTPStore) ValidateBackupCode(userID int64, code string) error

ValidateBackupCode validates and marks a backup code as used.

type TokenScope

type TokenScope string

TokenScope represents an API token scope/permission.

const (
	// ScopeRead allows read access to sites, snippets, and configuration.
	ScopeRead TokenScope = "read"

	// ScopeWrite allows create, update, and delete of sites and snippets.
	ScopeWrite TokenScope = "write"

	// ScopeAdmin allows full administrative access including user management.
	ScopeAdmin TokenScope = "admin"
)

func (TokenScope) IsValid

func (s TokenScope) IsValid() bool

IsValid checks if the scope is valid.

func (TokenScope) String

func (s TokenScope) String() string

String returns the string representation of the scope.

type TokenStore

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

TokenStore provides database operations for API tokens.

func NewTokenStore

func NewTokenStore(db *sql.DB) *TokenStore

NewTokenStore creates a new TokenStore.

func (*TokenStore) CleanExpiredTokens

func (s *TokenStore) CleanExpiredTokens() (int64, error)

CleanExpiredTokens removes all expired tokens.

func (*TokenStore) CountByUser

func (s *TokenStore) CountByUser(userID int64) (int, error)

CountByUser returns the count of active tokens for a user.

func (*TokenStore) Create

func (s *TokenStore) Create(userID int64, name string, scopes []TokenScope, expiresAt *time.Time) (string, *APIToken, error)

Create creates a new API token for a user. Returns the raw token (which should be shown to the user once) and the token record.

func (*TokenStore) Delete

func (s *TokenStore) Delete(id int64) error

Delete permanently deletes a token by ID.

func (*TokenStore) GetByID

func (s *TokenStore) GetByID(id int64) (*APIToken, error)

GetByID retrieves a token by ID.

func (*TokenStore) ListActiveByUser

func (s *TokenStore) ListActiveByUser(userID int64) ([]*APIToken, error)

ListActiveByUser lists all active (non-revoked, non-expired) tokens for a user.

func (*TokenStore) ListByUser

func (s *TokenStore) ListByUser(userID int64) ([]*APIToken, error)

ListByUser lists all tokens for a user.

func (*TokenStore) Revoke

func (s *TokenStore) Revoke(id int64) error

Revoke revokes a token by ID.

func (*TokenStore) RevokeAllForUser

func (s *TokenStore) RevokeAllForUser(userID int64) (int64, error)

RevokeAllForUser revokes all tokens for a user.

func (*TokenStore) ValidateToken

func (s *TokenStore) ValidateToken(rawToken string) (*APIToken, *User, error)

ValidateToken validates a raw token and returns the token record and associated user. It also updates the last_used_at timestamp.

type User

type User struct {
	ID           int64
	Username     string
	Email        string
	PasswordHash string
	Role         Role
	CreatedAt    time.Time
	LastLogin    *time.Time
}

User represents a user in the system.

type UserStore

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

UserStore provides database operations for users and sessions.

func NewUserStore

func NewUserStore(db *sql.DB) *UserStore

NewUserStore creates a new UserStore.

func (*UserStore) Authenticate

func (s *UserStore) Authenticate(username, password string) (*User, error)

Authenticate validates credentials and returns the user if valid.

func (*UserStore) CleanExpiredSessions

func (s *UserStore) CleanExpiredSessions() (int64, error)

CleanExpiredSessions removes all expired sessions.

func (*UserStore) Count

func (s *UserStore) Count() (int, error)

Count returns the number of users in the system.

func (*UserStore) Create

func (s *UserStore) Create(username, email, password string, role Role) (*User, error)

Create creates a new user.

func (*UserStore) CreateSession

func (s *UserStore) CreateSession(userID int64) (*Session, error)

CreateSession creates a new session for a user.

func (*UserStore) DB

func (s *UserStore) DB() *sql.DB

DB returns the underlying database connection.

func (*UserStore) Delete

func (s *UserStore) Delete(id int64) error

Delete deletes a user.

func (*UserStore) DeleteSession

func (s *UserStore) DeleteSession(token string) error

DeleteSession removes a session by token.

func (*UserStore) DeleteUserSessions

func (s *UserStore) DeleteUserSessions(userID int64) error

DeleteUserSessions removes all sessions for a user.

func (*UserStore) GetByID

func (s *UserStore) GetByID(id int64) (*User, error)

GetByID retrieves a user by ID.

func (*UserStore) GetByUsername

func (s *UserStore) GetByUsername(username string) (*User, error)

GetByUsername retrieves a user by username.

func (*UserStore) GetDashboardPreferences

func (s *UserStore) GetDashboardPreferences(userID int64) (*DashboardPreferences, error)

GetDashboardPreferences retrieves dashboard preferences for a user. If no preferences exist, returns defaults.

func (*UserStore) GetNotificationPreferences

func (s *UserStore) GetNotificationPreferences(userID int64) (*NotificationPreferences, error)

GetNotificationPreferences retrieves notification preferences for a user. If no preferences exist, returns defaults with all notifications enabled.

func (*UserStore) GetSessionByToken

func (s *UserStore) GetSessionByToken(token string) (*Session, error)

GetSessionByToken retrieves a session by its token.

func (*UserStore) List

func (s *UserStore) List() ([]*User, error)

List retrieves all users.

func (*UserStore) ListUserSessions

func (s *UserStore) ListUserSessions(userID int64) ([]*Session, error)

ListUserSessions lists all active sessions for a user.

func (*UserStore) SaveDashboardPreferences

func (s *UserStore) SaveDashboardPreferences(prefs *DashboardPreferences) error

SaveDashboardPreferences saves or updates dashboard preferences for a user.

func (*UserStore) SaveNotificationPreferences

func (s *UserStore) SaveNotificationPreferences(prefs *NotificationPreferences) error

SaveNotificationPreferences saves or updates notification preferences for a user.

func (*UserStore) Update

func (s *UserStore) Update(id int64, username, email string, role Role) error

Update updates a user's information (excluding password).

func (*UserStore) UpdateLastLogin

func (s *UserStore) UpdateLastLogin(id int64) error

UpdateLastLogin updates the last login timestamp for a user.

func (*UserStore) UpdatePassword

func (s *UserStore) UpdatePassword(id int64, password string) error

UpdatePassword updates a user's password.

func (*UserStore) ValidateSession

func (s *UserStore) ValidateSession(token string) (*User, error)

ValidateSession checks if a session token is valid and returns the user.

Jump to

Keyboard shortcuts

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