Documentation
¶
Index ¶
- Constants
- Variables
- func GenerateToken() (string, error)
- func HashToken(token string) string
- func IsEmailIdentifier(identifier string) bool
- func ValidateUsername(username string) error
- type AuthService
- type ConsentPolicy
- type CreateTokenResult
- type CredentialPolicy
- type FailedLoginAttempt
- type FailedLoginAttemptRepo
- type FirstLoginService
- type LoginRequest
- type LoginResult
- type LoginService
- type MFAChallenge
- type MFAChallengeCode
- type MFAChallengeRepo
- type MFAService
- func (s *MFAService) ChallengeUserID(ctx context.Context, token string) (int, error)
- func (s *MFAService) CreateChallenge(ctx context.Context, userID int) (*MFAChallengeCode, error)
- func (s *MFAService) ResendChallenge(ctx context.Context, token string) (*MFAChallengeCode, error)
- func (s *MFAService) VerifyChallenge(ctx context.Context, token, code string) (int, error)
- type PasswordResetResult
- type PasswordResetService
- type PasswordResetToken
- type PasswordResetTokenRepo
- type RegisterRequest
- type RegisterResult
- type RegistrationOption
- type RegistrationService
- type RequestPasswordResetResult
- type UserInfo
- type VerificationOption
- type VerificationResult
- type VerificationService
- type VerificationToken
- type VerificationTokenRepo
Constants ¶
const ( // MFACodeTTL is how long an emailed login code stays valid. MFACodeTTL time.Duration = 5 * time.Minute // MFAResendCooldown is the minimum wait between code re-issues. MFAResendCooldown time.Duration = 60 * time.Second // MFAMaxAttempts is the wrong-code budget per challenge. The final // mismatch discards the challenge. MFAMaxAttempts = 5 )
const DefaultAdminID = "default-admin-001"
DefaultAdminID is the stable identifier reported for the bootstrap admin.
const DefaultPassword = "admin"
DefaultPassword is the bootstrap admin password compared (via hash verification, never string equality) during first-login setup detection.
const DefaultRole = "Admin"
DefaultRole is the bootstrap admin role.
const DefaultUsername = "admin"
DefaultUsername is the bootstrap admin login. It mirrors internal/constants.DefaultUsername (the frozen bootstrap vocabulary); the module owns its first-login comparisons.
const RoleCommentator = "Commentator"
RoleCommentator is the default role assigned to self-service registrants. It mirrors internal/constants.RoleCommentator (the frozen role vocabulary); the module owns its registration default.
Variables ¶
var ( ErrAccountLocked = errors.New("account locked due to too many failed login attempts") ErrEmailNotVerified = errors.New("email address not verified") ErrAccountSuspended = errors.New("account has been suspended") ErrAccountDeleted = errors.New("account has been deleted") ErrInvalidCredentials = errors.New("invalid username or password") MaxFailedLoginAttempts = 3 AccountLockoutDuration = 15 * time.Minute )
var ( // ErrMFAChallengeInvalid is returned when a login challenge cannot be // found (unknown token, consumed token, or cleared by a newer login). ErrMFAChallengeInvalid = errors.New("login verification challenge is invalid") // ErrMFAChallengeExpired is returned when a login challenge passed its // expiration. The challenge is discarded so the user must sign in again. ErrMFAChallengeExpired = errors.New("login verification challenge has expired") // ErrMFACodeInvalid is returned when the submitted code does not match. ErrMFACodeInvalid = errors.New("invalid login verification code") // ErrMFACodeMaxAttempts is returned when the challenge burned through its // wrong-code budget. The challenge is discarded, forcing a fresh sign-in. ErrMFACodeMaxAttempts = errors.New("too many invalid login verification attempts") // ErrMFAResendTooSoon is returned when a resend arrives inside the // cooldown window. ErrMFAResendTooSoon = errors.New("login verification code was requested too recently") )
var ( // ErrResetTokenInvalid is returned when password reset token is invalid ErrResetTokenInvalid = errors.New("invalid password reset token") // ErrResetTokenExpired is returned when password reset token has expired ErrResetTokenExpired = errors.New("password reset token has expired") // ErrResetFailed is returned when password reset fails ErrResetFailed = errors.New("password reset failed") )
var ( // ErrUsernameInvalid is returned when username format is invalid ErrUsernameInvalid = errors.New("username must be 1-50 characters and contain only letters, numbers, underscores, and hyphens") // ErrUsernameExists is returned when username already exists ErrUsernameExists = errors.New("username already exists") // ErrEmailExists is returned when email already exists ErrEmailExists = errors.New("email address already registered") // ErrRegistrationFailed is returned when registration fails ErrRegistrationFailed = errors.New("registration failed") // ErrRegistrationDisabled is returned when self-registration is disabled via // the [registration] config block (or, by legacy default, when the comment // system is off). ErrRegistrationDisabled = errors.New("self-registration is disabled") // ErrConsentRequired is returned when registration demands an affirmative // consent act and the request does not carry one. ErrConsentRequired = errors.New("consent is required to register") )
var ( // ErrInvalidEmail is returned when an email address fails validation. // Its message mirrors internal/auth.ErrEmailInvalid byte-for-byte: the // first-login handler surfaces policy errors on the wire, so the text // is part of the frozen contract. The adapter test pins the equality. ErrInvalidEmail = errors.New("please enter a valid email address") // ErrInvalidPassword is returned when a password fails validation. // Its message mirrors internal/auth.ErrPasswordInvalid byte-for-byte // for the same wire-text reason. ErrInvalidPassword = errors.New("password must be at least 12 characters with mixed case, numbers, and special characters") )
var ( // ErrTokenInvalid is returned when verification token is invalid ErrTokenInvalid = errors.New("invalid verification token") // ErrTokenExpired is returned when verification token has expired ErrTokenExpired = errors.New("verification token has expired") // ErrVerificationFailed is returned when email verification fails ErrVerificationFailed = errors.New("email verification failed") )
var ( // ErrFailedLoginAttemptNotFound is returned when no failed login attempt // record exists for a user. ErrFailedLoginAttemptNotFound = errors.New("failed login attempt record not found") )
Functions ¶
func GenerateToken ¶
GenerateToken returns a cryptographically random 32-byte token in hex.
func IsEmailIdentifier ¶
IsEmailIdentifier reports whether a login identifier is an email address rather than a username. Usernames are validated as [a-zA-Z0-9_-]{1,50}, so an "@" unambiguously marks an email identifier.
func ValidateUsername ¶
ValidateUsername checks if a username has a valid format
Types ¶
type AuthService ¶
type AuthService struct {
// contains filtered or unexported fields
}
AuthService handles authentication business logic
func NewAuthService ¶
func NewAuthService(passwordHash string, policy CredentialPolicy) *AuthService
NewAuthService creates a new auth service with default admin credentials
type ConsentPolicy ¶
ConsentPolicy is the registration consent contract resolved once at boot: whether an affirmative act is required and which document revisions that act refers to. A zero policy leaves registration unchanged.
type CreateTokenResult ¶
CreateTokenResult contains the result of token creation
type CredentialPolicy ¶
type CredentialPolicy interface {
ValidateEmail(email string) error
ValidateUsername(username string) error
ValidatePassword(password string) error
GeneratePassword(length int) (string, error)
HashPassword(password string) (string, error)
VerifyPassword(hash, password string) error
NeedsRehash(hash string) bool
}
CredentialPolicy validates credentials, hashes passwords, and reports hash staleness. The platform owns the policy (internal/auth rules plus the registration username rule); the module declares only the methods its services call.
type FailedLoginAttempt ¶
type FailedLoginAttempt struct {
ID int
UserID int
Attempts int
LastAttemptAt time.Time
LockedUntil *time.Time
LastEmailSentAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
FailedLoginAttempt represents a failed login attempt record
type FailedLoginAttemptRepo ¶
type FailedLoginAttemptRepo interface {
GetByUserID(ctx context.Context, userID int) (*FailedLoginAttempt, error)
Create(ctx context.Context, attempt *FailedLoginAttempt) error
IncrementAttempts(ctx context.Context, userID int) error
LockAccount(ctx context.Context, userID int, lockoutDuration time.Duration) error
ResetAttempts(ctx context.Context, userID int) error
Delete(ctx context.Context, userID int) error
IsLocked(ctx context.Context, userID int) (bool, *time.Time, error)
UpdateLastEmailSent(ctx context.Context, userID int) error
ShouldSendLockoutEmail(ctx context.Context, userID int, minInterval time.Duration) (bool, error)
}
FailedLoginAttemptRepo defines the interface for failed login attempt repository operations
type FirstLoginService ¶
type FirstLoginService struct {
// contains filtered or unexported fields
}
FirstLoginService manages first-login setup state by deriving it from the database. Setup is considered complete when the admin password differs from the default.
func NewFirstLoginService ¶
func NewFirstLoginService(policy CredentialPolicy) *FirstLoginService
NewFirstLoginService creates a new first-login service.
func (*FirstLoginService) IsSetupComplete ¶
func (f *FirstLoginService) IsSetupComplete(currentAdminHash string) bool
IsSetupComplete returns whether first-login setup is complete by verifying the current admin password hash against the default password. Unlike a naive string comparison, this correctly handles salted hashes (Argon2id, bcrypt) where two hashes of the same password are never string-equal.
type LoginRequest ¶
type LoginRequest struct {
// Username is the login identifier: a username or an email address.
Username string
Password string
}
LoginRequest represents a login request
type LoginResult ¶
LoginResult represents the result of a successful login
type LoginService ¶
type LoginService struct {
// contains filtered or unexported fields
}
LoginService handles login business logic with account lockout
func NewLoginService ¶
func NewLoginService( userRepo userStore, failedLoginRepo FailedLoginAttemptRepo, policy CredentialPolicy, logger kernel.Logger, ) *LoginService
NewLoginService creates a new login service
func (*LoginService) GetFailedLoginAttempts ¶
GetFailedLoginAttempts returns the number of failed login attempts for a user
func (*LoginService) IsAccountLocked ¶
func (s *LoginService) IsAccountLocked(ctx context.Context, identifier string) (bool, *time.Time, error)
IsAccountLocked checks if an account is currently locked
func (*LoginService) Login ¶
func (s *LoginService) Login(ctx context.Context, req LoginRequest) (*LoginResult, error)
Login performs login with account lockout mechanism
type MFAChallenge ¶
type MFAChallenge struct {
ID int
UserID int
TokenHash string
CodeHash string
Attempts int
ExpiresAt time.Time
CreatedAt time.Time
}
MFAChallenge is a pending second-factor challenge: the hashed proof token issued after a correct password, the hashed emailed code, and its budget.
type MFAChallengeCode ¶
MFAChallengeCode carries the plaintext challenge token and code returned by the service for delivery. Neither value is ever stored in plaintext.
type MFAChallengeRepo ¶
type MFAChallengeRepo interface {
Create(ctx context.Context, challenge *MFAChallenge) error
FindByTokenHash(ctx context.Context, tokenHash string) (*MFAChallenge, error)
// IncrementAttempts spends one attempt only while the challenge is below
// maxAttempts. It reports whether the attempt was spent.
IncrementAttempts(ctx context.Context, id, maxAttempts int) (bool, error)
// Consume deletes the challenge and reports whether this caller removed
// it. A concurrent verify that loses the race gets false.
Consume(ctx context.Context, id int) (bool, error)
Delete(ctx context.Context, id int) error
DeleteUserChallenges(ctx context.Context, userID int) error
DeleteExpired(ctx context.Context) error
}
MFAChallengeRepo defines the interface for login MFA challenge repository operations. Challenges hold only hashed tokens and codes; successful verification deletes the row so a challenge is single-use.
type MFAService ¶
type MFAService struct {
// contains filtered or unexported fields
}
MFAService issues and verifies the emailed one-time codes that complete a login after the password step.
func NewMFAService ¶
func NewMFAService( repo MFAChallengeRepo, ttl time.Duration, resendCooldown time.Duration, maxAttempts int, ) *MFAService
NewMFAService creates the login MFA service. ttl bounds a challenge's life, resendCooldown throttles re-issues, and maxAttempts caps wrong codes before the challenge is discarded.
func (*MFAService) ChallengeUserID ¶
ChallengeUserID resolves the user behind a pending challenge without consuming or rotating it. The resend path uses it to re-check the account before spending the cooldown and clearing the challenge.
func (*MFAService) CreateChallenge ¶
func (s *MFAService) CreateChallenge(ctx context.Context, userID int) (*MFAChallengeCode, error)
CreateChallenge discards any pending challenge for the user and issues a fresh token/code pair.
func (*MFAService) ResendChallenge ¶
func (s *MFAService) ResendChallenge(ctx context.Context, token string) (*MFAChallengeCode, error)
ResendChallenge replaces a pending challenge with a fresh one, enforcing the resend cooldown against the original issue time.
func (*MFAService) VerifyChallenge ¶
VerifyChallenge consumes a challenge when the code matches and returns the challenged user ID. Each verify spends one attempt atomically; the final mismatch discards the challenge, and a concurrent verifier can consume the row only once.
type PasswordResetResult ¶
PasswordResetResult contains the result of a successful password reset
type PasswordResetService ¶
type PasswordResetService struct {
// contains filtered or unexported fields
}
PasswordResetService handles password reset business logic
func NewPasswordResetService ¶
func NewPasswordResetService( userRepo userStore, tokenRepo PasswordResetTokenRepo, policy CredentialPolicy, expirationHours int, ) *PasswordResetService
NewPasswordResetService creates a new password reset service
func (*PasswordResetService) RequestPasswordReset ¶
func (s *PasswordResetService) RequestPasswordReset(ctx context.Context, email string) (*RequestPasswordResetResult, error)
RequestPasswordReset creates a password reset token for a user
func (*PasswordResetService) ResetPassword ¶
func (s *PasswordResetService) ResetPassword(ctx context.Context, token, newPassword string) (*PasswordResetResult, error)
ResetPassword verifies the token and updates the user's password
type PasswordResetToken ¶
type PasswordResetToken struct {
ID int
UserID int
TokenHash string
ExpiresAt time.Time
CreatedAt time.Time
}
PasswordResetToken represents a password reset token in the system
type PasswordResetTokenRepo ¶
type PasswordResetTokenRepo interface {
CreateToken(ctx context.Context, token *PasswordResetToken) error
FindValidToken(ctx context.Context, tokenHash string) (*PasswordResetToken, error)
DeleteUserTokens(ctx context.Context, userID int) error
}
PasswordResetTokenRepo defines the interface for password reset token repository operations
type RegisterRequest ¶
type RegisterRequest struct {
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
ConsentAccepted bool `json:"consentAccepted,omitempty"`
}
RegisterRequest represents a user registration request
type RegisterResult ¶
RegisterResult contains the result of a successful registration
type RegistrationOption ¶
type RegistrationOption func(*registrationOptions)
RegistrationOption configures a RegistrationService. The zero options reproduce the legacy behavior exactly: registration enabled iff the comment system is enabled, default role Commentator, pending status.
func WithDefaultRole ¶
func WithDefaultRole(roleName string) RegistrationOption
WithDefaultRole sets the role assigned to new registrants. When unset, it defaults to the Commentator role.
func WithEnabled ¶
func WithEnabled(enabled bool) RegistrationOption
WithEnabled overrides the registration gate. When unset, registration is enabled iff comments are enabled (the legacy coupling).
type RegistrationService ¶
type RegistrationService struct {
// contains filtered or unexported fields
}
RegistrationService handles user registration business logic
func NewRegistrationService ¶
func NewRegistrationService(userRepo userStore, policy CredentialPolicy, commentsEnabled bool, opts ...RegistrationOption) *RegistrationService
NewRegistrationService creates a new registration service. Legacy behavior — registration enabled iff comments enabled, default role Commentator, pending status — is preserved unless overridden via RegistrationOptions.
func (*RegistrationService) RegisterUser ¶
func (s *RegistrationService) RegisterUser(ctx context.Context, req RegisterRequest) (*RegisterResult, error)
RegisterUser registers a new user with validation. The registered user gets the configured default role (Commentator unless overridden) and is always created in "pending" status: email verification is mandatory, so the account only becomes usable after the registrant proves their email address (and, in admin-approval mode, after an administrator approves the account).
func (*RegistrationService) RegistrationEnabled ¶
func (s *RegistrationService) RegistrationEnabled() bool
RegistrationEnabled reports whether self-registration is currently allowed. Handlers call this BEFORE any repository lookup (e.g. the blocked-email check) so a disabled instance short-circuits without a DB query and without leaking whether a submitted email is blocked.
func (*RegistrationService) SetConsentPolicy ¶
func (s *RegistrationService) SetConsentPolicy(policy ConsentPolicy)
SetConsentPolicy adopts the boot-time registration consent contract. The composition root resolves the conventional legal documents after the auth module is built, so this seam lands before any request is served: enabling consent here also gates the API, not just the rendered checkbox.
type RequestPasswordResetResult ¶
RequestPasswordResetResult contains the result of a password reset request
type VerificationOption ¶
type VerificationOption func(*verificationOptions)
VerificationOption configures a VerificationService. The zero options reproduce the legacy behavior exactly: a successful verification activates the account immediately.
func WithAdminApprovalRequired ¶
func WithAdminApprovalRequired() VerificationOption
WithAdminApprovalRequired makes email verification a proof-of-ownership step only: the email address is recorded as verified, but the account stays "pending" until an administrator approves it. Without it, verification activates the account (legacy behavior).
type VerificationResult ¶
type VerificationResult struct {
Success bool
Message string
UserID int
// AwaitingApproval reports that the email address was proven but the
// account stays pending until an administrator approves it.
AwaitingApproval bool
}
VerificationResult contains the result of a successful verification
type VerificationService ¶
type VerificationService struct {
// contains filtered or unexported fields
}
VerificationService handles email verification business logic
func NewVerificationService ¶
func NewVerificationService( userRepo userStore, tokenRepo VerificationTokenRepo, expirationHours int, opts ...VerificationOption, ) *VerificationService
NewVerificationService creates a new verification service. Legacy behavior — verification activates the account — is preserved unless overridden via VerificationOptions.
func (*VerificationService) CleanupExpiredTokens ¶
func (s *VerificationService) CleanupExpiredTokens(ctx context.Context) error
CleanupExpiredTokens removes expired tokens from the database
func (*VerificationService) CreateVerificationToken ¶
func (s *VerificationService) CreateVerificationToken(ctx context.Context, userID int) (*CreateTokenResult, error)
CreateVerificationToken creates a new verification token for a user
func (*VerificationService) VerifyEmail ¶
func (s *VerificationService) VerifyEmail(ctx context.Context, token string) (*VerificationResult, error)
VerifyEmail verifies a user's email using a token
type VerificationToken ¶
type VerificationToken struct {
ID int
UserID int
TokenHash string
ExpiresAt time.Time
CreatedAt time.Time
}
VerificationToken represents a verification token in the system
type VerificationTokenRepo ¶
type VerificationTokenRepo interface {
CreateToken(ctx context.Context, token *VerificationToken) error
FindValidToken(ctx context.Context, tokenHash string) (*VerificationToken, error)
DeleteUserTokens(ctx context.Context, userID int) error
DeleteExpiredTokens(ctx context.Context) error
}
VerificationTokenRepo defines the interface for verification token repository operations