Documentation
¶
Index ¶
- Constants
- func AuthCookieGet(r *http.Request) string
- func AuthCookieRemove(w http.ResponseWriter, r *http.Request)
- func AuthCookieSet(w http.ResponseWriter, r *http.Request, token string)
- func AuthTokenRetrieve(r *http.Request, useCookies bool) string
- type Auth
- func (a Auth) ApiAuthOrErrorMiddleware(next http.Handler) http.Handler
- func (a Auth) AuthHandler(w http.ResponseWriter, r *http.Request)
- func (a Auth) GetCurrentUserID(r *http.Request) string
- func (a Auth) Handler() http.Handler
- func (a Auth) LinkApiLogin() string
- func (a Auth) LinkApiLoginCodeVerify() string
- func (a Auth) LinkApiLogout() string
- func (a Auth) LinkApiPasswordReset() string
- func (a Auth) LinkApiPasswordRestore() string
- func (a Auth) LinkApiRegister() string
- func (a Auth) LinkApiRegisterCodeVerify() string
- func (a Auth) LinkLogin() string
- func (a Auth) LinkLoginCodeVerify() string
- func (a Auth) LinkLogout() string
- func (a Auth) LinkPasswordReset(token string) string
- func (a Auth) LinkPasswordRestore() string
- func (a Auth) LinkRedirectOnSuccess() string
- func (a Auth) LinkRegister() string
- func (a Auth) LinkRegisterCodeVerify() string
- func (a Auth) LoginWithUsernameAndPassword(ctx context.Context, email string, password string, options UserAuthOptions) (response LoginUsernameAndPasswordResponse)
- func (a Auth) RegisterWithUsernameAndPassword(ctx context.Context, email string, password string, firstName string, ...) (response RegisterUsernameAndPasswordResponse)
- func (a *Auth) RegistrationDisable()
- func (a *Auth) RegistrationEnable()
- func (a Auth) Router() *http.ServeMux
- func (a Auth) WebAppendUserIdIfExistsMiddleware(next http.Handler) http.Handler
- func (a Auth) WebAuthOrRedirectMiddleware(next http.Handler) http.Handler
- type AuthError
- func NewAuthenticationError(err error) AuthError
- func NewCodeGenerationError(err error) AuthError
- func NewEmailSendError(err error) AuthError
- func NewInternalError(err error) AuthError
- func NewLogoutError(err error) AuthError
- func NewPasswordResetError(err error) AuthError
- func NewRegistrationError(err error) AuthError
- func NewSerializationError(err error) AuthError
- func NewTokenStoreError(err error) AuthError
- type AuthenticatedUserID
- type ConfigPasswordless
- type ConfigUsernameAndPassword
- type CookieConfig
- type LoginUsernameAndPasswordResponse
- type RegisterUsernameAndPasswordResponse
- type UserAuthOptions
Constants ¶
const ( CookieName = "authtoken" // PathApiLogin contains the path to api login endpoint PathApiLogin string = "api/login" // PathApiLoginCodeVerify contains the path to api login code verification endpoint PathApiLoginCodeVerify string = "api/login-code-verify" // PathApiLogout contains the path to api logout endpoint PathApiLogout string = "api/logout" // PathApiRegister contains the path to api register endpoint PathApiRegister string = "api/register" // PathApiRegisterCodeVerify contains the path to api register code verification endpoint PathApiRegisterCodeVerify string = "api/register-code-verify" // PathApiRestorePassword contains the path to api restore password endpoint PathApiRestorePassword string = "api/restore-password" // PathApiResetPassword contains the path to api reset password endpoint PathApiResetPassword string = "api/reset-password" // PathLogin contains the path to login page PathLogin string = "login" // PathLoginCodeVerify contains the path to login code verification page PathLoginCodeVerify string = "login-code-verify" // PathLogout contains the path to logout page PathLogout string = "logout" // PathRegister contains the path to logout page PathRegister string = "register" // PathRegisterCodeVerify contains the path to registration code verification page PathRegisterCodeVerify string = "register-code-verify" // PathRestore contains the path to password restore page PathPasswordRestore string = "password-restore" // PathReset contains the path to password reset page PathPasswordReset string = "password-reset" // LoginCodeLength specified the length of the login code LoginCodeLength int = 8 // LoginCodeGamma specifies the characters to be used for building the login code LoginCodeGamma string = "BCDFGHJKLMNPQRSTVXYZ" DefaultVerificationCodeExpiration = 1 * time.Hour DefaultPasswordResetExpiration = 1 * time.Hour DefaultAuthTokenExpiration = 2 * time.Hour DefaultMaxLoginAttempts = 5 DefaultLockoutDuration = 15 * time.Minute )
const ( ErrCodeEmailSendFailed = "EMAIL_SEND_FAILED" ErrCodeTokenStoreFailed = "TOKEN_STORE_FAILED" ErrCodeValidationFailed = "VALIDATION_FAILED" ErrCodeAuthenticationFailed = "AUTHENTICATION_FAILED" ErrCodeRegistrationFailed = "REGISTRATION_FAILED" ErrCodeLogoutFailed = "LOGOUT_FAILED" ErrCodeInternalError = "INTERNAL_ERROR" ErrCodeCodeGenerationFailed = "CODE_GENERATION_FAILED" ErrCodeSerializationFailed = "SERIALIZATION_FAILED" ErrCodePasswordResetFailed = "PASSWORD_RESET_FAILED" )
Error codes for consistent error handling
Variables ¶
This section is empty.
Functions ¶
func AuthCookieGet ¶
func AuthCookieRemove ¶
func AuthCookieRemove(w http.ResponseWriter, r *http.Request)
func AuthCookieSet ¶
func AuthCookieSet(w http.ResponseWriter, r *http.Request, token string)
Types ¶
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth defines the structure for the authentication
func NewPasswordlessAuth ¶
func NewPasswordlessAuth(config ConfigPasswordless) (*Auth, error)
func NewUsernameAndPasswordAuth ¶
func NewUsernameAndPasswordAuth(config ConfigUsernameAndPassword) (*Auth, error)
func (Auth) ApiAuthOrErrorMiddleware ¶
ApiAuthOrErrorMiddleware checks that an authentication token exists, and then finds the userID based on it. On success appends the user ID to the context. On failure it will return an unauthenticated JSON response.
func (Auth) AuthHandler ¶
func (a Auth) AuthHandler(w http.ResponseWriter, r *http.Request)
Router routes the requests
func (Auth) LinkApiLogin ¶
func (Auth) LinkApiLoginCodeVerify ¶
func (Auth) LinkApiLogout ¶
func (Auth) LinkApiPasswordReset ¶
func (Auth) LinkApiPasswordRestore ¶
func (Auth) LinkApiRegister ¶
func (Auth) LinkApiRegisterCodeVerify ¶
func (Auth) LinkLoginCodeVerify ¶
func (Auth) LinkLogout ¶
func (Auth) LinkPasswordReset ¶
LinkPasswordReset - returns the password reset URL
func (Auth) LinkPasswordRestore ¶
func (Auth) LinkRedirectOnSuccess ¶
LinkRedirectOnSuccess - returns the URL to where the user will be redirected after successful registration
func (Auth) LinkRegister ¶
LinkRegister - returns the registration URL
func (Auth) LinkRegisterCodeVerify ¶
LinkRegisterCodeVerify - returns the registration code verification URL
func (Auth) LoginWithUsernameAndPassword ¶
func (a Auth) LoginWithUsernameAndPassword(ctx context.Context, email string, password string, options UserAuthOptions) (response LoginUsernameAndPasswordResponse)
func (Auth) RegisterWithUsernameAndPassword ¶
func (a Auth) RegisterWithUsernameAndPassword(ctx context.Context, email string, password string, firstName string, lastName string, options UserAuthOptions) (response RegisterUsernameAndPasswordResponse)
func (*Auth) RegistrationDisable ¶
func (a *Auth) RegistrationDisable()
RegistrationDisable - disables registration
func (*Auth) RegistrationEnable ¶
func (a *Auth) RegistrationEnable()
RegistrationEnable - enables registration
func (Auth) WebAppendUserIdIfExistsMiddleware ¶
WebAppendUserIdIfExistsMiddleware appends the user ID to the context if an authentication token exists in the requests. This middleware does not have a side effect like for instance redirecting to the login endpoint. This is why it is important to be added to places which can be used by both guests and users (i.e. website pages), where authenticated users may have some extra privileges
If you need to redirect the user if authentication token not found, or the user does not exist, take a look at the WebAuthOrRedirectMiddleware middleware, which does exactly that
func (Auth) WebAuthOrRedirectMiddleware ¶
WebAuthOrRedirectMiddleware checks that an authentication token exists, and then finds the userID based on it. On success appends the user ID to the context. On failure it will redirect the user to the login endpoint to reauthenticate.
If you need to only find if the authentication token is successful without redirection please use the WebAppendUserIdIfExistsMiddleware which does exactly that without side effects
type AuthError ¶ added in v0.29.0
type AuthError struct {
Code string
Message string // User-facing message
InternalErr error // For logging only, never exposed to users
}
AuthError represents a structured authentication error with a code, user-facing message, and internal error details for logging.
func NewAuthenticationError ¶ added in v0.29.0
NewAuthenticationError creates an AuthError for authentication failures.
func NewCodeGenerationError ¶ added in v0.29.0
NewCodeGenerationError creates an AuthError for code generation failures.
func NewEmailSendError ¶ added in v0.29.0
NewEmailSendError creates an AuthError for email send failures.
func NewInternalError ¶ added in v0.29.0
NewInternalError creates an AuthError for generic internal errors.
func NewLogoutError ¶ added in v0.29.0
NewLogoutError creates an AuthError for logout failures.
func NewPasswordResetError ¶ added in v0.29.0
NewPasswordResetError creates an AuthError for password reset failures.
func NewRegistrationError ¶ added in v0.29.0
NewRegistrationError creates an AuthError for registration failures.
func NewSerializationError ¶ added in v0.29.0
NewSerializationError creates an AuthError for data serialization failures.
func NewTokenStoreError ¶ added in v0.29.0
NewTokenStoreError creates an AuthError for token store failures.
type AuthenticatedUserID ¶
type AuthenticatedUserID struct{}
type ConfigPasswordless ¶
type ConfigPasswordless struct {
// ===== START: shared by all implementations
EnableRegistration bool
Endpoint string
FuncLayout func(content string) string
FuncTemporaryKeyGet func(key string) (value string, err error)
FuncTemporaryKeySet func(key string, value string, expiresSeconds int) (err error)
FuncUserFindByAuthToken func(ctx context.Context, sessionID string, options UserAuthOptions) (userID string, err error)
FuncUserLogout func(ctx context.Context, userID string, options UserAuthOptions) (err error)
FuncUserStoreAuthToken func(ctx context.Context, sessionID string, userID string, options UserAuthOptions) error
UrlRedirectOnSuccess string
UseCookies bool
UseLocalStorage bool
CookieConfig *CookieConfig
// Rate limiting options
DisableRateLimit bool // Set to true to disable rate limiting (not recommended for production)
FuncCheckRateLimit func(ip string, endpoint string) (allowed bool, retryAfter time.Duration, err error) // Optional: override default rate limiter
MaxLoginAttempts int // Maximum attempts before lockout (default: 5)
LockoutDuration time.Duration // Duration to lock after max attempts (default: 15 minutes)
// CSRF Protection
EnableCSRFProtection bool
CSRFSecret string
Logger *slog.Logger
// ===== START: passwordless options
FuncUserFindByEmail func(ctx context.Context, email string, options UserAuthOptions) (userID string, err error)
FuncEmailTemplateLoginCode func(ctx context.Context, email string, logingLink string, options UserAuthOptions) string // optional
FuncEmailTemplateRegisterCode func(ctx context.Context, email string, registerLink string, options UserAuthOptions) string // optional
FuncEmailSend func(ctx context.Context, email string, emailSubject string, emailBody string) (err error)
FuncUserRegister func(ctx context.Context, email string, firstName string, lastName string, options UserAuthOptions) (err error)
}
type ConfigUsernameAndPassword ¶
type ConfigUsernameAndPassword struct {
// ===== START: shared by all implementations
EnableRegistration bool
Endpoint string
FuncLayout func(content string) string
FuncTemporaryKeyGet func(key string) (value string, err error)
FuncTemporaryKeySet func(key string, value string, expiresSeconds int) (err error)
FuncUserStoreAuthToken func(ctx context.Context, sessionID string, userID string, options UserAuthOptions) error
FuncUserFindByAuthToken func(ctx context.Context, sessionID string, options UserAuthOptions) (userID string, err error)
UrlRedirectOnSuccess string
UseCookies bool
UseLocalStorage bool
CookieConfig *CookieConfig
// Rate limiting options
DisableRateLimit bool // Set to true to disable rate limiting (not recommended for production)
FuncCheckRateLimit func(ip string, endpoint string) (allowed bool, retryAfter time.Duration, err error) // Optional: override default rate limiter
MaxLoginAttempts int // Maximum attempts before lockout (default: 5)
LockoutDuration time.Duration // Duration to lock after max attempts (default: 15 minutes)
// CSRF Protection
EnableCSRFProtection bool
CSRFSecret string
Logger *slog.Logger
// ===== START: username(email) and password options
EnableVerification bool
FuncEmailTemplatePasswordRestore func(ctx context.Context, userID string, passwordRestoreLink string, options UserAuthOptions) string // optional
FuncEmailTemplateRegisterCode func(ctx context.Context, userID string, passwordRestoreLink string, options UserAuthOptions) string // optional
FuncEmailSend func(ctx context.Context, userID string, emailSubject string, emailBody string) (err error)
FuncUserFindByUsername func(ctx context.Context, username string, firstName string, lastName string, options UserAuthOptions) (userID string, err error)
FuncUserLogin func(ctx context.Context, username string, password string, options UserAuthOptions) (userID string, err error)
FuncUserLogout func(ctx context.Context, userID string, options UserAuthOptions) (err error)
FuncUserPasswordChange func(ctx context.Context, username string, newPassword string, options UserAuthOptions) (err error)
FuncUserRegister func(ctx context.Context, username string, password string, first_name string, last_name string, options UserAuthOptions) (err error)
PasswordStrength *authtypes.PasswordStrengthConfig
LabelUsername string
}
Config defines the available configuration options for authentication
type CookieConfig ¶ added in v0.29.0
type UserAuthOptions ¶
Source Files
¶
- api_auth_or_error_middleware.go
- api_login.go
- api_login_code_verify.go
- api_logout.go
- api_password_reset.go
- api_password_restore.go
- api_register.go
- api_register_code_verify.go
- auth.go
- auth_cookie_get.go
- auth_cookie_remove.go
- auth_cookie_set.go
- auth_token_retrieve.go
- config_passwordless.go
- config_username_and_password.go
- constants.go
- cookie_config.go
- email_login_code_template.go
- email_register_code_template.go
- email_template_password_change.go
- errors.go
- layout.go
- login_with_username_and_password.go
- new_passwordless_auth.go
- new_username_and_password_auth.go
- page_login.go
- page_login_code_verify.go
- page_logout.go
- page_password_reset.go
- page_password_restore.go
- page_register.go
- page_register_code_verify.go
- rate_limit_helpers.go
- register_with_username_and_password.go
- router.go
- testutils.go
- utilities.go
- web_append_user_id_if_exists_middleware.go
- web_auth_or_redirect_middleware.go