Documentation
¶
Index ¶
- Constants
- Variables
- func CheckBackupCode(code, hash string) bool
- func CheckPassword(password, hash string) bool
- func GenerateBackupCodes(count int) ([]string, error)
- func HashBackupCode(code string) (string, error)
- func HashPassword(password string) (string, error)
- func TokenHasPermission(token *APIToken, perm Permission) bool
- func ValidateTOTPCode(code, secret string) bool
- type APIToken
- type BackupCode
- type DashboardPreferences
- type NotificationPreferences
- type Permission
- type Role
- type Session
- type TOTPSetup
- type TOTPStore
- func (s *TOTPStore) DisableTOTP(userID int64) error
- func (s *TOTPStore) EnableTOTP(userID int64) error
- func (s *TOTPStore) GetBackupCodeCount(userID int64) (int, error)
- func (s *TOTPStore) GetTOTPStatus(userID int64) (enabled bool, secret string, verifiedAt *time.Time, err error)
- func (s *TOTPStore) HasBackupCodes(userID int64) (bool, error)
- func (s *TOTPStore) SaveBackupCodes(userID int64, codes []string) error
- func (s *TOTPStore) SetTOTPSecret(userID int64, secret string) error
- func (s *TOTPStore) ValidateBackupCode(userID int64, code string) error
- type TokenScope
- type TokenStore
- func (s *TokenStore) CleanExpiredTokens() (int64, error)
- func (s *TokenStore) CountByUser(userID int64) (int, error)
- func (s *TokenStore) Create(userID int64, name string, scopes []TokenScope, expiresAt *time.Time) (string, *APIToken, error)
- func (s *TokenStore) Delete(id int64) error
- func (s *TokenStore) GetByID(id int64) (*APIToken, error)
- func (s *TokenStore) ListActiveByUser(userID int64) ([]*APIToken, error)
- func (s *TokenStore) ListByUser(userID int64) ([]*APIToken, error)
- func (s *TokenStore) Revoke(id int64) error
- func (s *TokenStore) RevokeAllForUser(userID int64) (int64, error)
- func (s *TokenStore) ValidateToken(rawToken string) (*APIToken, *User, error)
- type User
- type UserStore
- func (s *UserStore) Authenticate(username, password string) (*User, error)
- func (s *UserStore) CleanExpiredSessions() (int64, error)
- func (s *UserStore) Count() (int, error)
- func (s *UserStore) Create(username, email, password string, role Role) (*User, error)
- func (s *UserStore) CreateSession(userID int64) (*Session, error)
- func (s *UserStore) DB() *sql.DB
- func (s *UserStore) Delete(id int64) error
- func (s *UserStore) DeleteSession(token string) error
- func (s *UserStore) DeleteUserSessions(userID int64) error
- func (s *UserStore) GetByID(id int64) (*User, error)
- func (s *UserStore) GetByUsername(username string) (*User, error)
- func (s *UserStore) GetDashboardPreferences(userID int64) (*DashboardPreferences, error)
- func (s *UserStore) GetNotificationPreferences(userID int64) (*NotificationPreferences, error)
- func (s *UserStore) GetSessionByToken(token string) (*Session, error)
- func (s *UserStore) List() ([]*User, error)
- func (s *UserStore) ListUserSessions(userID int64) ([]*Session, error)
- func (s *UserStore) SaveDashboardPreferences(prefs *DashboardPreferences) error
- func (s *UserStore) SaveNotificationPreferences(prefs *NotificationPreferences) error
- func (s *UserStore) Update(id int64, username, email string, role Role) error
- func (s *UserStore) UpdateLastLogin(id int64) error
- func (s *UserStore) UpdatePassword(id int64, password string) error
- func (s *UserStore) ValidateSession(token string) (*User, error)
Constants ¶
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 )
const SessionDuration = 24 * time.Hour
SessionDuration is how long a session is valid.
const TokenLength = 32
TokenLength is the number of random bytes in a token (before encoding).
const TokenPrefix = "csk_"
TokenPrefix is the prefix for API tokens for easy identification.
Variables ¶
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") )
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") )
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") )
var DefaultWidgetOrder = []string{"sites", "snippets", "containers", "certificates", "status"}
DefaultWidgetOrder is the default order of dashboard widgets.
var ValidRoles = []Role{RoleAdmin, RoleEditor, RoleViewer}
ValidRoles is a list of all valid roles.
var ValidScopes = []TokenScope{ScopeRead, ScopeWrite, ScopeAdmin}
ValidScopes is a list of all valid token scopes.
Functions ¶
func CheckBackupCode ¶
CheckBackupCode compares a backup code with its hash.
func CheckPassword ¶
CheckPassword compares a password with its hash.
func GenerateBackupCodes ¶
GenerateBackupCodes generates a set of backup codes.
func HashBackupCode ¶
HashBackupCode hashes a backup code for storage.
func HashPassword ¶
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 ¶
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 ¶
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 ¶
HasWriteAccess returns true if the token has write or admin scope.
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.
func (Role) CanEditGlobal ¶
CanEditGlobal returns true if the role can edit global settings.
func (Role) CanManageUsers ¶
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.
type TOTPSetup ¶
TOTPSetup holds the information needed to set up 2FA.
func GenerateTOTPSecret ¶
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 (*TOTPStore) DisableTOTP ¶
DisableTOTP disables 2FA for a user and clears their backup codes.
func (*TOTPStore) EnableTOTP ¶
EnableTOTP enables 2FA for a user after they've verified the code.
func (*TOTPStore) GetBackupCodeCount ¶
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 ¶
HasBackupCodes returns true if the user has any unused backup codes.
func (*TOTPStore) SaveBackupCodes ¶
SaveBackupCodes saves a set of backup codes for a user. It first deletes any existing backup codes.
func (*TOTPStore) SetTOTPSecret ¶
SetTOTPSecret sets the TOTP secret for a user (before verification).
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 (*UserStore) Authenticate ¶
Authenticate validates credentials and returns the user if valid.
func (*UserStore) CleanExpiredSessions ¶
CleanExpiredSessions removes all expired sessions.
func (*UserStore) CreateSession ¶
CreateSession creates a new session for a user.
func (*UserStore) DeleteSession ¶
DeleteSession removes a session by token.
func (*UserStore) DeleteUserSessions ¶
DeleteUserSessions removes all sessions for a user.
func (*UserStore) GetByUsername ¶
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 ¶
GetSessionByToken retrieves a session by its token.
func (*UserStore) ListUserSessions ¶
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) UpdateLastLogin ¶
UpdateLastLogin updates the last login timestamp for a user.
func (*UserStore) UpdatePassword ¶
UpdatePassword updates a user's password.