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
- func BearerTokenFromHeader(authHeader string) 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(email string, password string, options UserAuthOptions) (response LoginUsernameAndPasswordResponse)
- func (a Auth) RegisterWithUsernameAndPassword(email string, password string, firstName string, lastName 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 AuthenticatedUserID
- type ConfigPasswordless
- type ConfigUsernameAndPassword
- type InMemoryRateLimiter
- type LoginUsernameAndPasswordResponse
- type RateLimitResult
- 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" )
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)
func AuthTokenRetrieve ¶
authTokenRetrieve retrieves the auth token from the request Several attempts are made:
- From cookie
- Authorization header (aka Bearer token)
- Request param "api_key"
- Request param "token"
func BearerTokenFromHeader ¶
BearerTokenFromHeader extracts the bearer token from the passed authorization header value. If a bearer token is not found, an empty string is returned.
Parameters:
- authHeader: a string representing the authorization header
Returns:
- a string representing the extracted bearer token
Example:
authHeader := r.Header.Get("Authorization")
authTokenFromBearerToken := BearerTokenFromHeader(authHeader)
or simplified
authTokenFromBearerToken := BearerTokenFromHeader(r.Header.Get("Authorization"))
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(email string, password string, options UserAuthOptions) (response LoginUsernameAndPasswordResponse)
func (Auth) RegisterWithUsernameAndPassword ¶
func (a Auth) RegisterWithUsernameAndPassword(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 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(sessionID string, options UserAuthOptions) (userID string, err error)
FuncUserLogout func(userID string, options UserAuthOptions) (err error)
FuncUserStoreAuthToken func(sessionID string, userID string, options UserAuthOptions) error
UrlRedirectOnSuccess string
UseCookies bool
UseLocalStorage bool
// 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
// ===== START: passwordless options
FuncUserFindByEmail func(email string, options UserAuthOptions) (userID string, err error)
FuncEmailTemplateLoginCode func(email string, logingLink string, options UserAuthOptions) string // optional
FuncEmailTemplateRegisterCode func(email string, registerLink string, options UserAuthOptions) string // optional
FuncEmailSend func(email string, emailSubject string, emailBody string) (err error)
FuncUserRegister func(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(sessionID string, userID string, options UserAuthOptions) error
FuncUserFindByAuthToken func(sessionID string, options UserAuthOptions) (userID string, err error)
UrlRedirectOnSuccess string
UseCookies bool
UseLocalStorage bool
// 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
// ===== START: username(email) and password options
EnableVerification bool
FuncEmailTemplatePasswordRestore func(userID string, passwordRestoreLink string, options UserAuthOptions) string // optional
FuncEmailTemplateRegisterCode func(userID string, passwordRestoreLink string, options UserAuthOptions) string // optional
FuncEmailSend func(userID string, emailSubject string, emailBody string) (err error)
FuncUserFindByUsername func(username string, firstName string, lastName string, options UserAuthOptions) (userID string, err error)
FuncUserLogin func(username string, password string, options UserAuthOptions) (userID string, err error)
FuncUserLogout func(userID string, options UserAuthOptions) (err error)
FuncUserPasswordChange func(username string, newPassword string, options UserAuthOptions) (err error)
FuncUserRegister func(username string, password string, first_name string, last_name string, options UserAuthOptions) (err error)
LabelUsername string
}
Config defines the available configuration options for authentication
type InMemoryRateLimiter ¶ added in v0.28.0
type InMemoryRateLimiter struct {
// contains filtered or unexported fields
}
InMemoryRateLimiter provides thread-safe in-memory rate limiting
func GetDefaultRateLimiter ¶ added in v0.28.0
func GetDefaultRateLimiter() *InMemoryRateLimiter
GetDefaultRateLimiter returns the singleton default rate limiter
func NewInMemoryRateLimiter ¶ added in v0.28.0
func NewInMemoryRateLimiter(maxAttempts int, windowDuration time.Duration, lockoutDuration time.Duration) *InMemoryRateLimiter
NewInMemoryRateLimiter creates a new in-memory rate limiter with default settings
func (*InMemoryRateLimiter) Check ¶ added in v0.28.0
func (r *InMemoryRateLimiter) Check(ip string, endpoint string) RateLimitResult
Check verifies if a request from the given IP to the given endpoint should be allowed
func (*InMemoryRateLimiter) Stop ¶ added in v0.28.0
func (r *InMemoryRateLimiter) Stop()
Stop gracefully stops the rate limiter's background cleanup
type RateLimitResult ¶ added in v0.28.0
RateLimitResult represents the result of a rate limit check
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_middleware.go
- auth_token_retrieve.go
- bearer_token_from_header.go
- config_passwordless.go
- config_username_and_password.go
- consts.go
- email_login_code_template.go
- email_register_code_template.go
- email_template_password_change.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
- rate_limiter.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