Documentation
¶
Overview ¶
Package auth implements local authentication (ADR-0005): argon2id passwords, server-side sessions stored in SQLite, CSRF protection, the first-run setup token and login rate limiting.
Index ¶
- Constants
- Variables
- func CSRF(next http.Handler) http.Handler
- func HashPassword(password string, p Argon2Params) (string, error)
- func PasswordChanged(next http.Handler) http.Handler
- func ResetMFAOffline(ctx context.Context, st *store.Store, username string, now time.Time) error
- func ResetPassword(ctx context.Context, st *store.Store, username, password string, now time.Time) error
- func SameOrigin(r *http.Request) bool
- func SubjectFromRequest(r *http.Request) (authz.Subject, bool)
- func ValidatePassword(p string) error
- func VerifyPassword(password, encoded string, want Argon2Params) (ok, needsRehash bool, err error)
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type APIKey
- type Argon2Params
- type Auditor
- type Client
- type CreatedAPIKey
- type Issued
- type KeyOptions
- type KeyRef
- type Limiter
- type MFAChallengeError
- type MFAChallengeResponse
- type MFAEnrollment
- type MFAStatus
- type OIDCIdentity
- type OIDCSettings
- type OIDCSettingsResponse
- type OIDCStatus
- type Options
- type Passkey
- type PasskeyAdded
- type PasskeyOptions
- type Preferences
- type Principal
- type RateLimitedError
- type SecuritySettings
- type Service
- func (s *Service) Authenticate(ctx context.Context, token string) (Principal, error)
- func (s *Service) AuthenticateKey(ctx context.Context, token string) (Principal, error)
- func (s *Service) BeginPasskeyLogin(rp relyingParty, c Client) (string, *protocol.CredentialAssertion, error)
- func (s *Service) BeginPasskeyMFA(ctx context.Context, mfaToken string, rp relyingParty) (*protocol.CredentialAssertion, error)
- func (s *Service) BeginPasskeyRegistration(ctx context.Context, userID int64, password string, rp relyingParty) (string, *protocol.CredentialCreation, error)
- func (s *Service) ChangePassword(ctx context.Context, p Principal, current, next string) error
- func (s *Service) CleanupLoop(ctx context.Context)
- func (s *Service) CreateAPIKey(ctx context.Context, userID int64, name string, o KeyOptions) (APIKey, string, error)
- func (s *Service) CreateUser(ctx context.Context, username, password string) (UserDetail, string, error)
- func (s *Service) DeleteAPIKey(ctx context.Context, userID, id int64) error
- func (s *Service) DeletePasskey(ctx context.Context, userID, id int64, password string) error
- func (s *Service) DeleteUser(ctx context.Context, actor, id int64) error
- func (s *Service) DisableMFA(ctx context.Context, userID int64, password string) error
- func (s *Service) EnableMFA(ctx context.Context, userID int64, code string) ([]string, error)
- func (s *Service) FinishPasskeyLogin(ctx context.Context, token string, response []byte, c Client) (User, Issued, error)
- func (s *Service) FinishPasskeyRegistration(ctx context.Context, userID int64, token, name string, response []byte) (Passkey, []string, error)
- func (s *Service) GetPreferences(ctx context.Context, userID int64) (Preferences, error)
- func (s *Service) GetUser(ctx context.Context, id int64) (UserDetail, error)
- func (s *Service) ListAPIKeys(ctx context.Context, userID int64) ([]APIKey, error)
- func (s *Service) ListUsers(ctx context.Context) ([]UserDetail, error)
- func (s *Service) Login(ctx context.Context, username, password string, c Client) (User, Issued, error)
- func (s *Service) LoginMFA(ctx context.Context, token, code string, passkey []byte, c Client) (User, Issued, error)
- func (s *Service) Logout(ctx context.Context, p Principal) error
- func (s *Service) MFAEnrolled(next http.Handler) http.Handler
- func (s *Service) MFAStatusOf(ctx context.Context, userID int64) (MFAStatus, error)
- func (s *Service) NewBackupCodes(ctx context.Context, userID int64, password string) ([]string, error)
- func (s *Service) OIDCFinish(ctx context.Context, cookieState, state, code string, c Client) (User, Issued, string, OIDCIdentity, error)
- func (s *Service) OIDCSettings(ctx context.Context) (OIDCSettings, error)
- func (s *Service) OIDCStart(ctx context.Context, redirect, callback string) (authURL, state string, err error)
- func (s *Service) OptionalSession(next http.Handler) http.Handler
- func (s *Service) Passkeys(ctx context.Context, userID int64) ([]Passkey, error)
- func (s *Service) RequireMFA(ctx context.Context) bool
- func (s *Service) RequireSession(next http.Handler) http.Handler
- func (s *Service) ResetMFA(ctx context.Context, actorID, userID int64) error
- func (s *Service) Routes(r chi.Router, g *authz.Guard)
- func (s *Service) SecureCookie() bool
- func (s *Service) SetDisabled(ctx context.Context, actor, id int64, disabled bool) (UserDetail, error)
- func (s *Service) SetOIDCSettings(ctx context.Context, c OIDCSettings) (OIDCSettings, error)
- func (s *Service) SetPreferences(ctx context.Context, userID int64, p Preferences) (Preferences, error)
- func (s *Service) SetRequireMFA(ctx context.Context, on bool) error
- func (s *Service) SetTemporaryPassword(ctx context.Context, actor, id int64, password string) (string, error)
- func (s *Service) Setup(ctx context.Context, token, username, password string, c Client) (User, Issued, error)
- func (s *Service) SetupRequired() bool
- func (s *Service) StartMFA(ctx context.Context, userID int64, password string) (MFAEnrollment, error)
- func (s *Service) UnlinkOIDC(ctx context.Context, id int64) (UserDetail, error)
- type SessionResponse
- type User
- type UserDetail
- type UserPasswordResponse
Constants ¶
const ( MethodPassword = "password" MethodOIDC = "oidc" )
Session methods.
const ( MinPasswordLen = 12 // characters MaxPasswordLen = 1024 // bytes; bounds hashing cost )
Password policy.
const ( DefaultIdleTimeout = 24 * time.Hour DefaultAbsoluteTimeout = 30 * 24 * time.Hour // RoleAdmin is the only role in MVP (ADR-0009). RoleAdmin = authz.RoleAdmin )
Defaults (ADR-0005).
const APIKeyPrefix = "nerdui_"
APIKeyPrefix starts every key, so it is recognizable (secret scanners, logs).
const CSRFHeader = "X-CSRF-Token"
CSRFHeader carries the per-session CSRF token on unsafe requests.
const CodeMFASetupRequired = "mfa_setup_required"
CodeMFASetupRequired: the administrator requires two-factor authentication and the user has not set it up; only the session and two-factor endpoints are available.
const CookieName = "nerdui_session"
CookieName is the session cookie (ADR-0005).
const (
// MethodPasskey: the session signed in with a passkey alone (with user verification).
MethodPasskey = "passkey"
)
Variables ¶
var ( ErrAPIKeyNotFound = errors.New("API key not found") ErrInvalidAPIKey = errors.New("invalid API key settings") ErrTooManyAPIKeys = fmt.Errorf("%w: at most %d keys per user", ErrInvalidAPIKey, maxAPIKeysPerUser) ErrNotWithAPIKey = errors.New("not allowed with an API key: sign in with a password") )
Errors of API key management.
var ( ErrMFAInvalidCode = errors.New("invalid or already used code") ErrMFANotStarted = errors.New("start two-factor setup first") ErrMFANotEnabled = errors.New("two-factor authentication is not enabled") ErrMFAChallenge = errors.New("the sign-in attempt expired; enter your password again") ErrMFASetupRequired = errors.New("set up two-factor authentication first") ErrMFAAlreadyEnabled = errors.New("two-factor authentication is already enabled; disable it first") )
var ( ErrOIDCDisabled = errors.New("single sign-on is not enabled") ErrOIDCState = errors.New("the sign-in attempt expired or did not start here; try again") ErrOIDCNoAccount = errors.New("there is no nerdui account for you; ask an administrator to create one") ErrOIDCNotInGroup = errors.New("your account at the provider is not allowed to sign in to nerdui") ErrOIDCLinked = errors.New("this nerdui account is linked to another account at the provider") ErrInvalidOIDC = errors.New("invalid single sign-on settings") )
var ( ErrPasskeyHost = errors.New("passkeys need nerdui opened by a host name over HTTPS (or localhost); browsers refuse them on IP addresses") ErrPasskeyFailed = errors.New("the passkey was not accepted") ErrPasskeyCeremony = errors.New("the passkey request expired; try again") ErrPasskeyNotFound = errors.New("passkey not found") ErrPasskeyLimit = fmt.Errorf("a user can have at most %d passkeys", maxPasskeys) ErrPasskeyName = errors.New("passkey name must be at most 64 characters") )
var ( ErrInvalidCredentials = errors.New("invalid username or password") ErrUnauthenticated = errors.New("not authenticated") ErrSetupCompleted = errors.New("setup has already been completed") ErrInvalidSetupToken = errors.New("invalid setup token") ErrInvalidUsername = errors.New("username must be 1-64 characters: letters, digits, '.', '_' or '-'") ErrUserNotFound = errors.New("user not found") ErrUserDisabled = errors.New("account is disabled") )
Errors returned by the service.
var ( ErrUsernameTaken = errors.New("username is already taken") ErrOwnAccount = errors.New("use your account settings to change your own account") ErrLastAdmin = errors.New("at least one active administrator is required") ErrWrongPassword = errors.New("current password is incorrect") ErrSamePassword = errors.New("the new password must differ from the current one") ErrPasswordChange = errors.New("change your temporary password first") )
User management errors (#74, ADR-0016).
var DefaultArgon2 = Argon2Params{Memory: 19 * 1024, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}
DefaultArgon2 follows the OWASP recommendation (19 MiB, 2 iterations, 1 thread), which is affordable on small ARM boards.
var ( // ErrInvalidPreferences is returned for values outside the allowed ones. ErrInvalidPreferences = errors.New("invalid preferences") )
var ErrWeakPassword = fmt.Errorf("password must be %d to %d characters long", MinPasswordLen, MaxPasswordLen)
ErrWeakPassword is returned for passwords that violate the policy.
Functions ¶
func CSRF ¶
CSRF protects unsafe methods of authenticated routes: the X-CSRF-Token header must match the session's token, and a present Origin header must match the request host. Must run after RequireSession.
func HashPassword ¶
func HashPassword(password string, p Argon2Params) (string, error)
HashPassword returns a PHC-formatted argon2id hash: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<key>.
func PasswordChanged ¶
PasswordChanged rejects requests of sessions that still have to replace a temporary password (#74) with 403 password_change_required. Must run after RequireSession; only the caller's own session endpoints (me, logout, password) are exempt.
func ResetMFAOffline ¶ added in v0.2.0
ResetMFAOffline turns off a user's two-factor authentication and revokes their sessions. It is used by `nerdui admin reset-mfa` and works without a running server, e.g. when the only administrator lost both the phone and the backup codes.
func ResetPassword ¶
func ResetPassword(ctx context.Context, st *store.Store, username, password string, now time.Time) error
ResetPassword sets a new password for username, enables the account and revokes all of its sessions. It is used by `nerdui admin reset-password` and works without a running server; the operator chose the password, so it does not have to be changed.
func SameOrigin ¶
SameOrigin reports whether the request's Origin header (if present) matches its Host. Browsers always send Origin on cross-origin and unsafe requests.
func SubjectFromRequest ¶
SubjectFromRequest adapts the request's principal for the authorizer (authz.SubjectFunc).
func ValidatePassword ¶
ValidatePassword checks the password policy.
func VerifyPassword ¶
func VerifyPassword(password, encoded string, want Argon2Params) (ok, needsRehash bool, err error)
VerifyPassword reports whether password matches the encoded hash, and whether the hash uses weaker parameters than want (so callers can transparently rehash).
Types ¶
type APIKey ¶
type APIKey struct {
ID int64 `json:"id"`
Name string `json:"name"`
Prefix string `json:"prefix"`
ReadOnly bool `json:"readOnly"`
// Permissions limits the key to these actions (#80); absent, the key may do everything
// its user may.
Permissions []string `json:"permissions,omitempty"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
}
APIKey describes a key without its secret. Keep in sync with api/openapi.yaml.
type Argon2Params ¶
type Argon2Params struct {
Memory uint32 // KiB
Time uint32
Threads uint8
SaltLen uint32
KeyLen uint32
}
Argon2Params are the argon2id cost parameters; they are stored in every hash so they can be raised later without breaking existing passwords.
type Auditor ¶ added in v0.2.0
Auditor records authentication attempts; *audit.Recorder implements it.
type CreatedAPIKey ¶
CreatedAPIKey is the response to creating a key: the key itself is shown only here.
type KeyOptions ¶ added in v0.2.0
type KeyOptions struct {
ReadOnly bool
ExpiresAt *time.Time
// Permissions limits the key to these actions; nil: no limit beyond the user's.
Permissions []string
}
KeyOptions are the limits of a new API key.
type KeyRef ¶
type KeyRef struct {
ID int64
Name string
Prefix string
ReadOnly bool
// Permissions is nil for a key without limits.
Permissions []authz.Action
}
KeyRef identifies the API key a principal authenticated with.
type Limiter ¶
type Limiter struct {
MaxFailures int
Window time.Duration
BaseBlock time.Duration
MaxBlock time.Duration
// contains filtered or unexported fields
}
Limiter throttles failed authentication attempts per key (client IP, username). After MaxFailures failures within Window the key is blocked; every further block doubles, from BaseBlock up to MaxBlock (ADR-0005).
func NewLimiter ¶
NewLimiter returns a limiter with the defaults: 5 failures per minute, blocks from 1 to 15 minutes.
type MFAChallengeError ¶ added in v0.2.0
MFAChallengeError is returned by Login when the password was right and a second factor is needed: the client sends Token with a code or a passkey to LoginMFA. TOTP and Passkey tell which factors the user has; backup codes always work.
func (*MFAChallengeError) Error ¶ added in v0.2.0
func (e *MFAChallengeError) Error() string
type MFAChallengeResponse ¶ added in v0.2.0
type MFAChallengeResponse struct {
MFARequired bool `json:"mfaRequired"`
MFAToken string `json:"mfaToken"`
// TOTP and Passkey tell which factors the user has; backup codes always work.
TOTP bool `json:"totp"`
Passkey bool `json:"passkey"`
}
MFAChallengeResponse is returned by login when a second factor is needed. Keep in sync with api/openapi.yaml.
type MFAEnrollment ¶ added in v0.2.0
MFAEnrollment is a new secret to add to an authenticator app.
type MFAStatus ¶ added in v0.2.0
type MFAStatus struct {
// Enabled: the user has a second factor, an authenticator app or a passkey.
Enabled bool `json:"enabled"`
// TOTP: the authenticator app is set up.
TOTP bool `json:"totp"`
Passkeys int `json:"passkeys"`
BackupCodesLeft int `json:"backupCodesLeft"`
// Required: the administrator requires it from every user.
Required bool `json:"required"`
}
MFAStatus describes a user's two-factor authentication. Keep in sync with api/openapi.yaml.
type OIDCIdentity ¶ added in v0.2.0
type OIDCIdentity struct {
// ID is "<issuer> <subject>", unique per account at the provider.
ID string
Username string
Groups []string
}
OIDCIdentity is what the provider says about the user.
type OIDCSettings ¶ added in v0.2.0
type OIDCSettings struct {
Enabled bool `json:"enabled"`
Issuer string `json:"issuer"`
ClientID string `json:"clientId"`
// ClientSecret replaces the stored secret when set; "" removes it (public clients).
ClientSecret *string `json:"clientSecret,omitempty"`
HasClientSecret bool `json:"hasClientSecret"`
// Scopes besides openid; default profile and email, and groups when Group is set.
Scopes []string `json:"scopes"`
// UsernameClaim names the nerdui account; default preferred_username.
UsernameClaim string `json:"usernameClaim"`
// GroupsClaim lists the user's groups; default groups.
GroupsClaim string `json:"groupsClaim"`
// Group, when set, is required to sign in, and its members without an account get one.
// Without it only existing accounts can sign in.
Group string `json:"group"`
// ButtonLabel is the text of the sign-in button; default "Sign in with SSO".
ButtonLabel string `json:"buttonLabel"`
// RedirectURL overrides the callback URL nerdui derives from the request.
RedirectURL string `json:"redirectUrl"`
}
OIDCSettings configure the provider. The client secret is write-only: ClientSecret is never returned, HasClientSecret tells whether one is stored. Keep in sync with api/openapi.yaml.
type OIDCSettingsResponse ¶ added in v0.2.0
type OIDCSettingsResponse struct {
OIDCSettings
CallbackURL string `json:"callbackUrl"`
}
OIDCSettingsResponse is the settings with the callback URL to register at the provider. Keep in sync with api/openapi.yaml.
type OIDCStatus ¶ added in v0.2.0
OIDCStatus tells the sign-in page whether to show the single sign-on button. Keep in sync with api/openapi.yaml.
type Options ¶
type Options struct {
// Audit, when set, records setups and logins, also failed ones (#79).
Audit Auditor
SecureCookie bool
// CookiePath limits the session cookie to nerdui's base path (#222); "" means "/".
CookiePath string
IdleTimeout time.Duration
AbsoluteTimeout time.Duration
Argon2 Argon2Params
Now func() time.Time
Logger *slog.Logger
// Box encrypts the client secret of the single sign-on provider (#76).
Box *secretbox.Box
// HTTPClient talks to the single sign-on provider; nil: http.DefaultClient.
HTTPClient *http.Client
}
Options configures the service.
type Passkey ¶ added in v0.2.0
type Passkey struct {
ID int64 `json:"id"`
Name string `json:"name"`
Host string `json:"host"`
CreatedAt time.Time `json:"createdAt"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
}
Passkey is the public view of a passkey. Keep in sync with api/openapi.yaml.
type PasskeyAdded ¶ added in v0.2.0
type PasskeyAdded struct {
Passkey Passkey `json:"passkey"`
BackupCodes []string `json:"backupCodes,omitempty"`
}
PasskeyAdded is the new passkey, with backup codes when it is the user's first second factor. Keep in sync with api/openapi.yaml.
type PasskeyOptions ¶ added in v0.2.0
PasskeyOptions are the options for navigator.credentials.create() or .get() (their JSON form, with a "publicKey" member) and the token of the request. Keep in sync with api/openapi.yaml.
type Preferences ¶
type Preferences struct {
// Theme is auto (the system's), light or dark.
Theme string `json:"theme"`
// DateFormat is relative ("5 min ago"), local (the browser's locale) or iso.
DateFormat string `json:"dateFormat"`
// RefreshSeconds polls lists in addition to live events; 0 turns it off.
RefreshSeconds int `json:"refreshSeconds"`
// HiddenColumns lists hidden columns per table.
HiddenColumns map[string][]string `json:"hiddenColumns"`
}
Preferences are a user's interface settings (#90), kept on the server so they follow the user across browsers. Keep in sync with api/openapi.yaml.
func DefaultPreferences ¶
func DefaultPreferences() Preferences
DefaultPreferences apply until a user saves their own.
func (*Preferences) Validate ¶
func (p *Preferences) Validate() error
Validate checks every field against the allowed values.
type Principal ¶
type Principal struct {
User User
CSRFToken string
ExpiresAt time.Time
// APIKey is set when the request authenticated with an API key instead of a session.
APIKey *KeyRef
// Method is how the session signed in: MethodPassword, MethodPasskey or MethodOIDC.
Method string
// contains filtered or unexported fields
}
Principal is the authenticated caller attached to a request context.
type RateLimitedError ¶
RateLimitedError carries the time until the next attempt is allowed.
func (*RateLimitedError) Error ¶
func (e *RateLimitedError) Error() string
type SecuritySettings ¶ added in v0.2.0
type SecuritySettings struct {
RequireMFA bool `json:"requireMfa"`
}
SecuritySettings are the server-wide sign-in rules. Keep in sync with api/openapi.yaml.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the authentication service.
func New ¶
New creates the service. When the database has no users, it generates a one-time setup token and logs it (ADR-0005): whoever creates the first admin must have access to the logs.
func (*Service) Authenticate ¶
Authenticate resolves a session token (from the cookie) to a principal.
func (*Service) AuthenticateKey ¶
AuthenticateKey resolves an API key to its principal. Unknown, expired keys and keys of disabled users are ErrUnauthenticated.
func (*Service) BeginPasskeyLogin ¶ added in v0.2.0
func (s *Service) BeginPasskeyLogin(rp relyingParty, c Client) (string, *protocol.CredentialAssertion, error)
BeginPasskeyLogin returns the options for signing in without a password: the browser offers the passkeys it has for this host.
func (*Service) BeginPasskeyMFA ¶ added in v0.2.0
func (s *Service) BeginPasskeyMFA(ctx context.Context, mfaToken string, rp relyingParty) (*protocol.CredentialAssertion, error)
BeginPasskeyMFA returns the options for the second step of a login with a password.
func (*Service) BeginPasskeyRegistration ¶ added in v0.2.0
func (s *Service) BeginPasskeyRegistration(ctx context.Context, userID int64, password string, rp relyingParty) (string, *protocol.CredentialCreation, error)
BeginPasskeyRegistration checks the password and returns the options for the browser.
func (*Service) ChangePassword ¶
ChangePassword changes the caller's own password after verifying the current one. It clears the temporary-password flag and revokes the caller's other sessions.
func (*Service) CleanupLoop ¶
CleanupLoop deletes expired sessions periodically until ctx is done.
func (*Service) CreateAPIKey ¶
func (s *Service) CreateAPIKey(ctx context.Context, userID int64, name string, o KeyOptions) (APIKey, string, error)
CreateAPIKey creates a key for a user and returns it with its secret, which is not stored. The caller checks that the user has every permission of the key.
func (*Service) CreateUser ¶
func (s *Service) CreateUser(ctx context.Context, username, password string) (UserDetail, string, error)
CreateUser adds an administrator with a temporary password that must be changed at the first sign-in. An empty password is generated and returned; a given one is returned empty.
func (*Service) DeleteAPIKey ¶
DeleteAPIKey revokes a key of a user; requests with it are rejected at once.
func (*Service) DeletePasskey ¶ added in v0.2.0
DeletePasskey removes one of the user's passkeys after checking the password. Without another second factor left, the backup codes go too.
func (*Service) DeleteUser ¶
DeleteUser removes another user and their sessions.
func (*Service) DisableMFA ¶ added in v0.2.0
DisableMFA turns the authenticator app off after checking the password. The backup codes stay while the user has passkeys.
func (*Service) EnableMFA ¶ added in v0.2.0
EnableMFA confirms the pending secret with a code and returns new backup codes.
func (*Service) FinishPasskeyLogin ¶ added in v0.2.0
func (s *Service) FinishPasskeyLogin(ctx context.Context, token string, response []byte, c Client) (User, Issued, error)
FinishPasskeyLogin signs in with a passkey alone: it is both factors, as the authenticator verified the user (PIN, biometrics).
func (*Service) FinishPasskeyRegistration ¶ added in v0.2.0
func (s *Service) FinishPasskeyRegistration(ctx context.Context, userID int64, token, name string, response []byte) (Passkey, []string, error)
FinishPasskeyRegistration stores the new passkey. The first second factor of a user also gets backup codes.
func (*Service) GetPreferences ¶
GetPreferences returns a user's preferences, or the defaults.
func (*Service) ListAPIKeys ¶
ListAPIKeys returns a user's keys, newest first.
func (*Service) ListUsers ¶
func (s *Service) ListUsers(ctx context.Context) ([]UserDetail, error)
ListUsers returns all users sorted by username.
func (*Service) Login ¶
func (s *Service) Login(ctx context.Context, username, password string, c Client) (User, Issued, error)
Login verifies credentials and creates a session.
func (*Service) LoginMFA ¶ added in v0.2.0
func (s *Service) LoginMFA(ctx context.Context, token, code string, passkey []byte, c Client) (User, Issued, error)
LoginMFA completes a login with the second factor, a code or the answer of a passkey (BeginPasskeyMFA), and creates a session.
func (*Service) MFAEnrolled ¶ added in v0.2.0
MFAEnrolled blocks sessions without two-factor authentication while it is required. API keys are not affected: they are a separate credential; nor are single sign-on sessions, whose provider checks the second factor (#76).
func (*Service) MFAStatusOf ¶ added in v0.2.0
MFAStatusOf returns a user's status.
func (*Service) NewBackupCodes ¶ added in v0.2.0
func (s *Service) NewBackupCodes(ctx context.Context, userID int64, password string) ([]string, error)
NewBackupCodes replaces a user's backup codes after checking the password.
func (*Service) OIDCFinish ¶ added in v0.2.0
func (s *Service) OIDCFinish(ctx context.Context, cookieState, state, code string, c Client) (User, Issued, string, OIDCIdentity, error)
OIDCFinish completes a sign-in: it checks the state against the one kept in the cookie, exchanges the code, verifies the ID token and signs the user in. It returns the user, the session and where to go next.
func (*Service) OIDCSettings ¶ added in v0.2.0
func (s *Service) OIDCSettings(ctx context.Context) (OIDCSettings, error)
OIDCSettings returns the stored settings, without the secret.
func (*Service) OIDCStart ¶ added in v0.2.0
func (s *Service) OIDCStart(ctx context.Context, redirect, callback string) (authURL, state string, err error)
OIDCStart begins a sign-in: it returns the provider's authorization URL and the state, which the caller keeps in a cookie. redirect is where to go after signing in; callback is the callback URL derived from the request, unless the settings override it.
func (*Service) OptionalSession ¶
OptionalSession attaches the principal when a valid session cookie is present and otherwise passes the request through unchanged.
func (*Service) RequireMFA ¶ added in v0.2.0
RequireMFA reports whether every user must use two-factor authentication.
func (*Service) RequireSession ¶
RequireSession rejects requests without a valid session or API key with 401. An "Authorization: Bearer" header is an API key (#87); otherwise the session cookie is used.
func (*Service) ResetMFA ¶ added in v0.2.0
ResetMFA turns off another user's two-factor authentication: the authenticator app, the passkeys and the backup codes (administrators, e.g. a lost phone).
func (*Service) Routes ¶
Routes registers the authentication and user management endpoints under the API root.
func (*Service) SecureCookie ¶
SecureCookie reports whether session cookies are marked Secure.
func (*Service) SetDisabled ¶
func (s *Service) SetDisabled(ctx context.Context, actor, id int64, disabled bool) (UserDetail, error)
SetDisabled disables or enables another user. Disabling revokes the user's sessions.
func (*Service) SetOIDCSettings ¶ added in v0.2.0
func (s *Service) SetOIDCSettings(ctx context.Context, c OIDCSettings) (OIDCSettings, error)
SetOIDCSettings validates and stores the settings. When sign-in is enabled the provider's discovery document must be reachable, so a wrong issuer shows at once.
func (*Service) SetPreferences ¶
func (s *Service) SetPreferences(ctx context.Context, userID int64, p Preferences) (Preferences, error)
SetPreferences validates and saves a user's preferences.
func (*Service) SetRequireMFA ¶ added in v0.2.0
SetRequireMFA turns the requirement on or off.
func (*Service) SetTemporaryPassword ¶
func (s *Service) SetTemporaryPassword(ctx context.Context, actor, id int64, password string) (string, error)
SetTemporaryPassword sets another user's password, revokes their sessions and requires a change at the next sign-in. An empty password is generated and returned.
func (*Service) Setup ¶
func (s *Service) Setup(ctx context.Context, token, username, password string, c Client) (User, Issued, error)
Setup creates the first admin account and logs it in.
func (*Service) SetupRequired ¶
SetupRequired reports whether the first admin still has to be created.
func (*Service) StartMFA ¶ added in v0.2.0
func (s *Service) StartMFA(ctx context.Context, userID int64, password string) (MFAEnrollment, error)
StartMFA creates a pending secret after checking the password.
func (*Service) UnlinkOIDC ¶ added in v0.2.0
UnlinkOIDC removes the link of a user to their account at the provider.
type SessionResponse ¶
type SessionResponse struct {
User User `json:"user"`
CSRFToken string `json:"csrfToken"`
ExpiresAt time.Time `json:"expiresAt"`
// MFASetupRequired: two-factor authentication is required and the user has none yet (#75).
MFASetupRequired bool `json:"mfaSetupRequired"`
}
SessionResponse is returned by setup, login and me. Keep in sync with api/openapi.yaml.
type User ¶
type User struct {
ID int64 `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
// MustChangePassword is set after an administrator chose the password (#74): until the
// user changes it, only their own session endpoints are available.
MustChangePassword bool `json:"mustChangePassword"`
// MFAEnabled: the user signs in with a second factor (#75).
MFAEnabled bool `json:"mfaEnabled"`
// SSO: the user is linked to an account at the single sign-on provider (#76).
SSO bool `json:"sso"`
}
User is the public view of a user.
type UserDetail ¶
type UserDetail struct {
User
Disabled bool `json:"disabled"`
CreatedAt time.Time `json:"createdAt"`
LastLoginAt *time.Time `json:"lastLoginAt,omitempty"`
}
UserDetail is the administrator's view of a user.
type UserPasswordResponse ¶
type UserPasswordResponse struct {
User *UserDetail `json:"user,omitempty"`
GeneratedPassword string `json:"generatedPassword,omitempty"`
}
UserPasswordResponse carries a generated temporary password; it is shown once.