Documentation
¶
Overview ¶
loghash provides email hashing for debug-log correlation.
Password-reset Debug logs must never carry a raw email address: a log-shipping operator could otherwise distinguish "known but rate-limited" from "unknown email" branches and enumerate registered emails. The hash is for debug correlation only — not a credential, not stored, not used for any security decision — so truncation to 16 hex characters is acceptable.
Package auth handles user authentication, session management, and password security for Chronicle. It provides registration, login, logout, and session validation via PASETO v4 tokens stored in Redis.
This is a CORE plugin -- always enabled, cannot be disabled.
Index ¶
- Constants
- Variables
- func AllowInvitationLookup(c *echo.Context) bool
- func ConfigureAccountDeletion(svc AuthService, hooks AccountDeletionHooks)
- func ConfigureAvatarUploader(svc AuthService, uploader AvatarUploader)
- func ConfigureGuests(svc AuthService, codes GuestCodes)
- func ConfigureInvitations(svc AuthService, src InvitationSource)
- func ConfigureMailSender(svc AuthService, mail MailSender, baseURL string)
- func ConfigureOIDC(svc AuthService, store OIDCStore, siteSecret, baseURL string)
- func ConfigureRegistrationGate(svc AuthService, policy RegistrationPolicy, checker RegistrationInviteChecker)
- func ConfigureTwoFactor(svc AuthService, siteSecret string)
- func ForceSessionRevalidation(ctx context.Context, svc AuthService) (int, error)
- func GetSessionTokenFromCookie(c *echo.Context) string
- func GetUserID(c *echo.Context) string
- func IsGuestEmail(email string) bool
- func OnAccountDeleted(svc AuthService, fn func(ctx context.Context, userID string))
- func OnGuestMerged(svc AuthService, ...)
- func OnSessionsRevoked(svc AuthService, fn func(ctx context.Context, userID string))
- func OptionalAuth(service AuthService) echo.MiddlewareFunc
- func ReadSessionToken(req *http.Request) string
- func ReconcileLegacyAvatarPaths(ctx context.Context, repo LegacyAvatarRepository, uploader AvatarUploader, ...) (moved, cleared int, err error)
- func RegisterRoutes(e *echo.Echo, h *Handler)
- func RequireAuth(service AuthService) echo.MiddlewareFunc
- func RequireReauth(service AuthService) echo.MiddlewareFunc
- func RequireSiteAdmin() echo.MiddlewareFunc
- func SameSitePath(raw string) string
- func SessionCookieNames() []string
- func SetOIDCStateCookie(c *echo.Context, state string)
- func SetSession(c *echo.Context, session *Session)
- type AccountDeletionHooks
- type AuthService
- type AvatarUploader
- type CampaignLister
- type CampaignSettingsList
- type CampaignSettingsRef
- type ConnectedApp
- type ConnectedApps
- type DeleteAccountInput
- type GuestCodes
- type Handler
- func (h *Handler) AccountPage(c *echo.Context) error
- func (h *Handler) ChangePasswordAPI(c *echo.Context) error
- func (h *Handler) ClearAvatarAPI(c *echo.Context) error
- func (h *Handler) ConfirmEmailChange(c *echo.Context) error
- func (h *Handler) DeleteAccountAPI(c *echo.Context) error
- func (h *Handler) DisconnectAppAPI(c *echo.Context) error
- func (h *Handler) ForgotPassword(c *echo.Context) error
- func (h *Handler) ForgotPasswordForm(c *echo.Context) error
- func (h *Handler) GuestPanelFragment(c *echo.Context) error
- func (h *Handler) Join(c *echo.Context) error
- func (h *Handler) JoinPage(c *echo.Context) error
- func (h *Handler) KeepGuestAccount(c *echo.Context) error
- func (h *Handler) LinkOIDC(c *echo.Context) error
- func (h *Handler) Login(c *echo.Context) error
- func (h *Handler) LoginForm(c *echo.Context) error
- func (h *Handler) LoginOIDC(c *echo.Context) error
- func (h *Handler) LoginTwoFactor(c *echo.Context) error
- func (h *Handler) Logout(c *echo.Context) error
- func (h *Handler) MergeGuest(c *echo.Context) error
- func (h *Handler) OIDCCallback(c *echo.Context) error
- func (h *Handler) ReauthConfirm(c *echo.Context) error
- func (h *Handler) Register(c *echo.Context) error
- func (h *Handler) RegisterForm(c *echo.Context) error
- func (h *Handler) RequestEmailChangeAPI(c *echo.Context) error
- func (h *Handler) ResetPassword(c *echo.Context) error
- func (h *Handler) ResetPasswordForm(c *echo.Context) error
- func (h *Handler) SetBrushAPI(c *echo.Context) error
- func (h *Handler) SetCampaignLister(l CampaignLister)
- func (h *Handler) SetConnectedApps(apps ConnectedApps)
- func (h *Handler) SetSecurityLogger(logger SecurityEventLogger)
- func (h *Handler) SignOutEverywhereAPI(c *echo.Context) error
- func (h *Handler) SignOutSessionAPI(c *echo.Context) error
- func (h *Handler) TwoFactorDisableAPI(c *echo.Context) error
- func (h *Handler) TwoFactorEnableAPI(c *echo.Context) error
- func (h *Handler) TwoFactorRecoveryCodesAPI(c *echo.Context) error
- func (h *Handler) TwoFactorSetupAPI(c *echo.Context) error
- func (h *Handler) UnlinkOIDCAPI(c *echo.Context) error
- func (h *Handler) UpdateDisplayNameAPI(c *echo.Context) error
- func (h *Handler) UpdateNotifyPrefsAPI(c *echo.Context) error
- func (h *Handler) UpdateTimezoneAPI(c *echo.Context) error
- func (h *Handler) UpdateViewPrefsAPI(c *echo.Context) error
- func (h *Handler) UploadAvatarAPI(c *echo.Context) error
- type Identity
- type Invitation
- type InvitationMember
- type InvitationNight
- type InvitationSource
- type JoinInput
- type JoinResult
- type KeepGuestInput
- type LegacyAvatarRepository
- type LoginInput
- type LoginOptions
- type LoginRequest
- type MailSender
- type MergeGuestInput
- type MySession
- type OIDCCallbackInput
- type OIDCResult
- type OIDCSettings
- type OIDCSettingsInput
- type OIDCStore
- type OwnedCampaignRef
- type RegisterInput
- type RegisterRequest
- type RegistrationInviteChecker
- type RegistrationPolicy
- type SecurityEventLogger
- type Session
- type SessionInfo
- type SignInMethods
- type TwoFactorLoginInput
- type TwoFactorLoginResult
- type TwoFactorRequired
- type TwoFactorSetup
- type TwoFactorStatus
- type UpdateViewPrefsInput
- type User
- type UserFilter
- type UserFilterCounts
- type UserRepository
- type UserSearchOptions
- type ViewPrefs
Constants ¶
const ( OIDCModeLogin = "login" OIDCModeLink = "link" OIDCModeTest = "test" )
Sign-in modes a provider round trip can be for.
const DeletedDisplayName = "Former member"
DeletedDisplayName is what a deleted account is shown as wherever its pages, posts and shared notes stay behind.
Variables ¶
var ErrLastAdmin = apperror.NewBadRequest("This is the only admin, so their admin rights can't be removed. Make someone else an admin first.")
ErrLastAdmin refuses removing admin rights from the only admin who can still sign in, which would lock everyone out of the admin pages.
Functions ¶
func AllowInvitationLookup ¶
AllowInvitationLookup spends one lookup from the caller's address. When it reports false the page is drawn plain, the same as for a wrong code.
func ConfigureAccountDeletion ¶
func ConfigureAccountDeletion(svc AuthService, hooks AccountDeletionHooks)
ConfigureAccountDeletion wires the campaign-side steps. Without them deletion is refused, so an account can never be removed while still holding campaigns.
func ConfigureAvatarUploader ¶
func ConfigureAvatarUploader(svc AuthService, uploader AvatarUploader)
ConfigureAvatarUploader wires the media-backed avatar uploader into the auth service. Called from routes.go once the media service exists. Mirrors ConfigureMailSender.
func ConfigureGuests ¶
func ConfigureGuests(svc AuthService, codes GuestCodes)
ConfigureGuests wires guest codes. Without it the join page refuses.
func ConfigureInvitations ¶
func ConfigureInvitations(svc AuthService, src InvitationSource)
ConfigureInvitations wires the door's lookups. Without it the pages stay plain.
func ConfigureMailSender ¶
func ConfigureMailSender(svc AuthService, mail MailSender, baseURL string)
ConfigureMailSender wires a mail sender into the auth service for password reset emails. Called from routes.go after both services are initialized.
func ConfigureOIDC ¶
func ConfigureOIDC(svc AuthService, store OIDCStore, siteSecret, baseURL string)
ConfigureOIDC wires provider sign-in. The client secret is sealed under a key derived from the site secret, separate from the two-factor key.
func ConfigureRegistrationGate ¶
func ConfigureRegistrationGate(svc AuthService, policy RegistrationPolicy, checker RegistrationInviteChecker)
ConfigureRegistrationGate wires the registration-mode policy and invite checker into the auth service. Called from routes.go after the settings and invite services exist. Mirrors ConfigureMailSender.
func ConfigureTwoFactor ¶
func ConfigureTwoFactor(svc AuthService, siteSecret string)
ConfigureTwoFactor gives the service the key that encrypts stored authenticator secrets. It is derived from the site secret, so a database copy alone can't produce codes. Without it two-factor can't be turned on. HKDF gives this purpose its own key, separate from anything else the site secret signs.
func ForceSessionRevalidation ¶
func ForceSessionRevalidation(ctx context.Context, svc AuthService) (int, error)
ForceSessionRevalidation makes every live session check itself against the database on its next request, instead of waiting out the usual interval. It is for the moment the database has been replaced: a session whose user is missing from the restored data is then destroyed, and one whose user remains picks up the restored admin flag and details. Sessions are kept, not deleted, so people whose accounts survive stay signed in. It returns how many sessions it marked.
func GetSessionTokenFromCookie ¶
GetSessionTokenFromCookie reads the raw session token from the cookie on the incoming request. Exported so that other plugins which implement their own session-aware middleware (e.g. the syncapi multi-auth middleware that lets in-app widgets authenticate with a cookie instead of a Bearer token) can read the cookie without reaching into unexported helpers.
func GetUserID ¶
GetUserID retrieves the authenticated user's ID from the Echo context. Returns empty string if the request is not authenticated.
func IsGuestEmail ¶
IsGuestEmail reports whether an address is a guest's placeholder.
func OnAccountDeleted ¶
func OnAccountDeleted(svc AuthService, fn func(ctx context.Context, userID string))
OnAccountDeleted registers fn to run once an account is gone, for data other plugins hold about the person (character links, private notes, API keys). A failing step is logged; the account stays deleted.
func OnGuestMerged ¶
func OnGuestMerged(svc AuthService, fn func(ctx context.Context, campaignID, guestID, targetID string) error)
OnGuestMerged registers fn to move what a guest made in their campaign to the account they merge into. Steps must be safe to run twice: a failed merge is retried from the start.
func OnSessionsRevoked ¶
func OnSessionsRevoked(svc AuthService, fn func(ctx context.Context, userID string))
OnSessionsRevoked registers fn to run whenever all of a user's sessions are destroyed. Other plugins use it to end their own credentials for that user without auth importing them.
func OptionalAuth ¶
func OptionalAuth(service AuthService) echo.MiddlewareFunc
OptionalAuth returns middleware that loads the session if a valid cookie exists, but does NOT reject unauthenticated requests. Use this on routes that should work both with and without authentication (e.g., public campaign pages where logged-in users see more features than guests).
func ReadSessionToken ¶
ReadSessionToken reads the session token from an http.Request using the same scheme-aware dual-read as the web handlers. For callers outside this package (the WebSocket handshake) that don't have an *echo.Context.
func ReconcileLegacyAvatarPaths ¶
func ReconcileLegacyAvatarPaths(ctx context.Context, repo LegacyAvatarRepository, uploader AvatarUploader, avatarsDir string) (moved, cleared int, err error)
ReconcileLegacyAvatarPaths migrates every users.avatar_path still pointing at a dead legacy /uploads/avatars/ web path: if the file still exists under avatarsDir, its bytes are moved into the media store through uploader and the column is rewritten to the returned media id; if the file is already gone (the common case — the path was never served and the directory itself lived outside the Docker volume), the column is cleared so the default avatar renders instead of a broken image. Every clear uses ClearAvatarPathIfMatches rather than an unconditional write, so a row a user has already overwritten with a real upload between the listing above and this call is never clobbered back to NULL. Rows that already hold a media id never match the prefix, so a second run changes nothing. Idempotent reconciler, not a migration; safe to re-run every boot. Best-effort: reports its error to the caller to log and continue, and never blocks startup.
func RegisterRoutes ¶
RegisterRoutes sets up all auth-related routes on the given Echo instance. Auth routes are public (no session required) -- the middleware is exported separately for other plugins to use on their route groups.
POST endpoints are rate-limited to prevent brute-force and credential stuffing attacks: 10 attempts per IP per minute for login, 5 for register.
func RequireAuth ¶
func RequireAuth(service AuthService) echo.MiddlewareFunc
RequireAuth returns middleware that validates the session cookie and injects session data into the request context. If the session is invalid or missing, it redirects browsers to /login or returns 401 for API requests.
func RequireReauth ¶
func RequireReauth(service AuthService) echo.MiddlewareFunc
RequireReauth returns middleware that ensures the admin has recently confirmed their password (within the 5-minute reauth window). Must be applied AFTER RequireAuth. If reauth has not been confirmed, returns 403 with an HX-Trigger header that tells the client JS to show the password modal.
func RequireSiteAdmin ¶
func RequireSiteAdmin() echo.MiddlewareFunc
RequireSiteAdmin returns middleware that ensures the user has the site-wide is_admin flag set. Must be applied AFTER RequireAuth.
Used by: admin plugin routes, SMTP settings routes.
func SameSitePath ¶
SameSitePath returns raw only if it is a safe same-site path. Anything else becomes "" so the caller falls back to a default. Control characters and backslashes are rejected outright because browsers strip tabs and newlines and treat "\" as "/", turning "/\t/evil.example" into the protocol-relative "//evil.example". Other plugins use it for the "return here" fields of their own forms.
func SessionCookieNames ¶
func SessionCookieNames() []string
SessionCookieNames returns the session cookie names the auth plugin sets, so the maintenance gate, which cannot import this package, can be pinned to the same names by a test.
func SetOIDCStateCookie ¶
SetOIDCStateCookie remembers the round trip's state in this browser. It is Lax so it comes back on the provider's top-level redirect.
func SetSession ¶
SetSession stores an authenticated session on the Echo context, using the same keys that RequireAuth populates. Exported so other plugins that run their own session validation (see syncapi.RequireAuthOrAPIKey) can advertise the session to downstream code — anything calling GetSession / GetUserID afterwards sees a uniform result regardless of which middleware did the validation.
Types ¶
type AccountDeletionHooks ¶
type AccountDeletionHooks interface {
// OwnedCampaigns lists campaigns the user owns, archived ones included.
OwnedCampaigns(ctx context.Context, userID string) ([]OwnedCampaignRef, error)
// LeaveAllCampaigns removes the user from every campaign the way an
// owner's Remove does. It refuses while the user still owns one.
LeaveAllCampaigns(ctx context.Context, userID string) error
}
AccountDeletionHooks are the campaign-side steps of deleting an account, implemented by an adapter over the campaigns service.
type AuthService ¶
type AuthService interface {
Register(ctx context.Context, input RegisterInput) (*User, error)
// RegistrationStatus reports the current registration mode and whether a
// registration bearing inviteToken would be allowed right now (first-user
// bootstrap is always allowed). Used by the register page to choose between
// the form and a friendly gated state.
RegistrationStatus(ctx context.Context, inviteToken string) (mode string, allowed bool, err error)
Login(ctx context.Context, input LoginInput) (token string, user *User, err error)
ValidateSession(ctx context.Context, token string) (*Session, error)
DestroySession(ctx context.Context, token string) error
// Password reset flow.
CanEmailResetLinks(ctx context.Context) bool
InitiatePasswordReset(ctx context.Context, email string) error
ValidateResetToken(ctx context.Context, token string) (email string, err error)
ResetPassword(ctx context.Context, token, newPassword string) error
// User profile.
GetUser(ctx context.Context, userID string) (*User, error)
GetTimezonesByIDs(ctx context.Context, userIDs []string) (map[string]string, error)
UpdateTimezone(ctx context.Context, userID, timezone string) error
GetViewPrefs(ctx context.Context, userID string) (ViewPrefs, error)
UpdateViewPrefs(ctx context.Context, userID string, input UpdateViewPrefsInput) (ViewPrefs, error)
SetBrushHidden(ctx context.Context, userID, campaignID string, hidden bool) (ViewPrefs, error)
GetNotifyPrefs(ctx context.Context, userID string) (notifyprefs.Prefs, error)
UpdateNotifyPrefs(ctx context.Context, userID string, in notifyprefs.Update) (notifyprefs.Prefs, error)
AllowedRecipients(ctx context.Context, ids []string, category string, ch notifyprefs.Channel) []string
OwnedCampaigns(ctx context.Context, userID string) ([]OwnedCampaignRef, error)
DeleteOwnAccount(ctx context.Context, userID string, input DeleteAccountInput) error
UpdateDisplayName(ctx context.Context, userID, displayName string) error
UpdateAvatarPath(ctx context.Context, userID string, avatarPath *string) error
ChangePassword(ctx context.Context, userID, currentPassword, newPassword, ip, userAgent string) (string, error)
// UploadAvatar stores fileBytes as userID's avatar through the wired
// AvatarUploader (media.MediaService, usage_type "avatar", no campaign)
// and persists the returned media id to users.avatar_path, deleting
// whatever avatar it replaces. Returns apperror.NewInternal if no
// uploader is configured (should never happen outside a test that
// constructs authService directly without ConfigureAvatarUploader).
UploadAvatar(ctx context.Context, userID string, fileBytes []byte, originalName, mimeType string) (mediaID, url string, err error)
// ClearAvatar removes the user's avatar (sets avatar_path to NULL) and
// deletes its underlying media file. A user may only clear their own
// avatar -- the handler binds userID from the caller's own session,
// never from a request parameter.
ClearAvatar(ctx context.Context, userID string) error
// Email change with verification.
RequestEmailChange(ctx context.Context, userID, newEmail, currentPassword string) error
ConfirmEmailChange(ctx context.Context, token string) error
// Admin session management.
ListAllSessions(ctx context.Context) ([]SessionInfo, error)
DestroyAllUserSessions(ctx context.Context, userID string) (int, error)
// DestroySessionByHash finds a session by the SHA-256 hash of its token
// and destroys it. Used by the admin dashboard to avoid exposing raw tokens.
DestroySessionByHash(ctx context.Context, tokenHash string) error
// ListMySessions and SignOutMySession back the account page's list of
// where the user is signed in. They only ever touch the user's own set.
ListMySessions(ctx context.Context, userID, currentToken string) ([]MySession, error)
SignOutMySession(ctx context.Context, userID, sessionID, currentToken string) error
// Two-factor sign-in.
TwoFactorStatus(ctx context.Context, userID string) (TwoFactorStatus, error)
BeginTwoFactor(ctx context.Context, userID, password string) (*TwoFactorSetup, error)
EnableTwoFactor(ctx context.Context, userID, code string) ([]string, error)
DisableTwoFactor(ctx context.Context, userID, password, code string) error
RegenerateRecoveryCodes(ctx context.Context, userID, password, code string) ([]string, error)
AdminDisableTwoFactor(ctx context.Context, userID string) error
CompleteTwoFactorLogin(ctx context.Context, in TwoFactorLoginInput) (*TwoFactorLoginResult, error)
// Sign-in with an outside provider (OpenID Connect).
OIDCSettings(ctx context.Context) (OIDCSettings, error)
SaveOIDCSettings(ctx context.Context, in OIDCSettingsInput) error
LoginOptions(ctx context.Context) LoginOptions
SignInMethods(ctx context.Context, userID string) (SignInMethods, error)
BeginOIDC(ctx context.Context, mode, userID, redirect string) (authURL, state string, err error)
FinishOIDC(ctx context.Context, in OIDCCallbackInput) (*OIDCResult, error)
UnlinkOIDC(ctx context.Context, userID string) error
// Guests: join with a code, then keep the account or merge it.
JoinWithGuestCode(ctx context.Context, in JoinInput) (*JoinResult, error)
KeepGuestAccount(ctx context.Context, userID string, in KeepGuestInput, ip, userAgent string) (string, error)
MergeGuest(ctx context.Context, guestID string, in MergeGuestInput, ip, userAgent string) (string, *User, error)
EndGuest(ctx context.Context, userID, campaignID string)
GuestCanKeep(ctx context.Context) bool
EndCampaignGuests(ctx context.Context, campaignID string)
// Re-authentication for sensitive operations.
ConfirmReauth(ctx context.Context, userID, sessionToken, password string) error
IsReauthValid(ctx context.Context, userID, sessionToken string) (bool, error)
// NoteSeen records that someone used Chronicle by another route than a
// browser session, such as a sync key.
NoteSeen(ctx context.Context, userID string)
}
AuthService defines the business logic contract for authentication. Handlers call these methods -- they never touch the repository directly.
func NewAuthService ¶
func NewAuthService(repo UserRepository, rdb *redis.Client, sessionTTL time.Duration) AuthService
NewAuthService creates a new auth service with the given dependencies.
type AvatarUploader ¶
type AvatarUploader interface {
UploadAvatar(ctx context.Context, userID string, fileBytes []byte, originalName, mimeType string) (mediaID, url string, err error)
// DeleteAvatarMedia removes a previously-stored avatar's media row and
// file, but only if mediaID still belongs to userID and is still an
// avatar (never someone else's file, and never one repurposed for
// something else since it was last a user's avatar). Called after a
// replacement avatar or a clear has already been persisted, so this is
// best-effort cleanup of what the column used to point at -- an error
// here is logged and swallowed, never surfaced to the caller.
DeleteAvatarMedia(ctx context.Context, userID, mediaID string) error
}
AvatarUploader stores a profile picture through the media pipeline's Upload (magic-byte validation, EXIF stripping/re-encode, the per-file size limit, a disk-space check, 0640 permissions; NOT the per-campaign storage/file-count quota, since an avatar has no campaign). Implemented by an adapter over media.MediaService in routes.go, keeping auth decoupled from the media plugin the same way MediaCampaignVerifier keeps entities decoupled from it. UploadAvatar returns the stored file's media id (persisted to users.avatar_path) and a URL ready for immediate display (signed if URL signing is configured).
type CampaignLister ¶
type CampaignLister interface {
SettingsCampaigns(ctx context.Context, userID string) (CampaignSettingsList, error)
}
CampaignLister lists the campaigns a person belongs to. It lives outside auth (the campaigns plugin provides it) so auth never imports campaigns.
type CampaignSettingsList ¶
type CampaignSettingsList struct {
Campaigns []CampaignSettingsRef
More int
}
CampaignSettingsList is the campaigns a person belongs to, as the account rail lists them. More counts the campaigns past the ones listed, so the rail can say so rather than silently stopping.
type CampaignSettingsRef ¶
CampaignSettingsRef is one campaign in Account settings' "Your campaigns" list, which leads to that campaign's own settings page.
type ConnectedApp ¶
type ConnectedApp struct {
ID string
Name string
Place string // Where it is used: a campaign name.
Origin string
LastUsed time.Time
}
ConnectedApp is an app outside Chronicle the user let act for them, such as a Foundry world using their notes. Owned by whichever plugin issued it; the account page only lists and disconnects.
type ConnectedApps ¶
type ConnectedApps interface {
ListForUser(ctx context.Context, userID string) ([]ConnectedApp, error)
// DisconnectForUser ends one of the user's own apps; anyone else's is
// NotFound.
DisconnectForUser(ctx context.Context, userID, appID string) error
}
ConnectedApps lists and disconnects the apps a user allowed. Wired in app/routes.go so auth never imports the plugin that issues them.
type DeleteAccountInput ¶
type DeleteAccountInput struct {
Password string `json:"password"`
Confirm string `json:"confirm"`
// Code is asked for only when two-factor is on.
Code string `json:"code"`
}
DeleteAccountInput is what the Delete account form sends.
type GuestCodes ¶
type GuestCodes interface {
// ClaimGuestCode marks a live code used before anyone is made, so two
// people racing for one code can't both get in.
ClaimGuestCode(ctx context.Context, code string) (codeID, campaignID string, err error)
// ReleaseGuestCode undoes a claim whose join then failed.
ReleaseGuestCode(ctx context.Context, codeID string)
// AdmitWithGuestCode makes the user a player in the code's campaign and
// records them as the one who used it.
AdmitWithGuestCode(ctx context.Context, codeID, campaignID, userID string) error
}
GuestCodes is the campaign side of guest codes, implemented by an adapter over the campaigns service so auth imports no other plugin.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for authentication (login, register, logout). Handlers are thin: they bind the request, call the service, and render the response. No business logic lives here.
func NewHandler ¶
func NewHandler(service AuthService, sessionTTL time.Duration) *Handler
NewHandler creates a new auth handler with the given service and session TTL.
func (*Handler) AccountPage ¶
AccountPage renders the user account settings page (GET /account).
func (*Handler) ChangePasswordAPI ¶
ChangePasswordAPI changes the authenticated user's password (PUT /account/password).
func (*Handler) ClearAvatarAPI ¶
ClearAvatarAPI removes the current user's avatar (DELETE /account/avatar). A user may only clear their own avatar: userID comes from the session, never from a request parameter.
func (*Handler) ConfirmEmailChange ¶
ConfirmEmailChange handles the verification link click (GET /account/email/verify?token=...). On success, redirects to login since all sessions are invalidated.
func (*Handler) DeleteAccountAPI ¶
DeleteAccountAPI deletes the signed-in person's own account (POST /account/delete) after checking their password and the typed confirmation, then signs this browser out.
func (*Handler) DisconnectAppAPI ¶
DisconnectAppAPI ends one of the user's connected apps (POST /account/signed-in/apps/:id/disconnect).
func (*Handler) ForgotPassword ¶
ForgotPassword processes the forgot password form (POST /forgot-password). Always shows a success message to avoid leaking whether the email exists.
func (*Handler) ForgotPasswordForm ¶
ForgotPasswordForm renders the forgot password page (GET /forgot-password).
func (*Handler) GuestPanelFragment ¶
GuestPanelFragment loads the keep-your-account panel under a guest's banner (GET /account/guest). tab=close empties it.
func (*Handler) Join ¶
Join takes a guest code (POST /join): a new guest is made and signed in, or someone already signed in is added to the campaign.
func (*Handler) JoinPage ¶
JoinPage shows the guest code form (GET /join). A guest already belongs to a campaign, so they go back to it.
func (*Handler) KeepGuestAccount ¶
KeepGuestAccount adds an email and password to a guest's account (POST /account/guest/keep).
func (*Handler) LinkOIDC ¶
LinkOIDC starts linking the signed-in person's provider account (POST /account/sign-in/link). It's a POST so another site can't start it.
func (*Handler) LoginTwoFactor ¶
LoginTwoFactor is the code step of a sign-in (POST /login/two-factor). The challenge from the password step stands in for the email and password, so neither is sent twice.
func (*Handler) MergeGuest ¶
MergeGuest moves a guest into an account they already have (POST /account/guest/merge).
func (*Handler) OIDCCallback ¶
OIDCCallback is where the provider sends the browser back (GET /login/oidc/callback). The state must match this browser's cookie before anything else is looked at.
func (*Handler) ReauthConfirm ¶
ReauthConfirm handles password re-confirmation for sensitive admin operations (POST /account/reauth). It validates the admin's password and, if correct, sets a short-lived reauth token in Redis that allows sensitive operations for 5 minutes without re-prompting.
func (*Handler) RegisterForm ¶
RegisterForm renders the registration page (GET /register).
func (*Handler) RequestEmailChangeAPI ¶
RequestEmailChangeAPI initiates an email change (PUT /account/email). Requires the user's current password for security.
func (*Handler) ResetPassword ¶
ResetPassword processes the new password form (POST /reset-password).
func (*Handler) ResetPasswordForm ¶
ResetPasswordForm renders the reset password page (GET /reset-password?token=...).
func (*Handler) SetBrushAPI ¶
SetBrushAPI saves whether the signed-in person sees the header's Customize brush in one campaign (PUT /account/brush/:campaignID, {"brush":"shown"| "hidden"}). It writes only the caller's own row and no other campaign's choice.
func (*Handler) SetCampaignLister ¶
func (h *Handler) SetCampaignLister(l CampaignLister)
SetCampaignLister wires the "Your campaigns" list into Account settings. Unwired, the rail lists only the account's own sections.
func (*Handler) SetConnectedApps ¶
func (h *Handler) SetConnectedApps(apps ConnectedApps)
SetConnectedApps wires the apps list into the account page. Unwired, the page lists browsers only.
func (*Handler) SetSecurityLogger ¶
func (h *Handler) SetSecurityLogger(logger SecurityEventLogger)
SetSecurityLogger wires a security event logger for recording auth events.
func (*Handler) SignOutEverywhereAPI ¶
SignOutEverywhereAPI ends every session the user has, this one included, and every connected app with them, then sends the browser to sign in (POST /account/signed-in/sign-out-everywhere).
func (*Handler) SignOutSessionAPI ¶
SignOutSessionAPI ends another of the user's browsers (POST /account/signed-in/sessions/:id/sign-out).
func (*Handler) TwoFactorDisableAPI ¶
TwoFactorDisableAPI turns two-factor off (POST /account/two-factor/disable).
func (*Handler) TwoFactorEnableAPI ¶
TwoFactorEnableAPI finishes turning two-factor on and returns the recovery codes (POST /account/two-factor/enable).
func (*Handler) TwoFactorRecoveryCodesAPI ¶
TwoFactorRecoveryCodesAPI replaces the recovery codes (POST /account/two-factor/recovery-codes).
func (*Handler) TwoFactorSetupAPI ¶
TwoFactorSetupAPI starts turning two-factor on (POST /account/two-factor/setup).
func (*Handler) UnlinkOIDCAPI ¶
UnlinkOIDCAPI removes the link (POST /account/sign-in/unlink).
func (*Handler) UpdateDisplayNameAPI ¶
UpdateDisplayNameAPI updates the authenticated user's display name (PUT /account/display-name).
func (*Handler) UpdateNotifyPrefsAPI ¶
UpdateNotifyPrefsAPI saves the signed-in person's notification choices (PUT /account/notifications). The body is partial: only the switches sent change.
func (*Handler) UpdateTimezoneAPI ¶
UpdateTimezoneAPI updates the user's timezone preference (PUT /account/timezone).
func (*Handler) UpdateViewPrefsAPI ¶
UpdateViewPrefsAPI saves the signed-in person's own viewing choices (PUT /account/view-prefs). The body is partial: only the keys sent change.
func (*Handler) UploadAvatarAPI ¶
UploadAvatarAPI handles avatar image upload for the current user (POST /account/avatar). Delegates entirely to mediaService.Upload (via AuthService.UploadAvatar): magic-byte validation, EXIF stripping/ re-encode, the per-file size limit, disk-space check and 0640 permissions all happen there — this handler only binds the multipart form and renders the result. The per-campaign storage/file-count quota does NOT apply (there is no campaign to scope it to); the route-level rate limit (routes.go) is the only throttle on repeated avatar uploads.
type Invitation ¶
type Invitation struct {
CampaignName string
// BackdropPath is the campaign's backdrop media id, "" when it has none.
BackdropPath string
Members []InvitationMember
// NextNight is the next planned game night, nil when none is planned.
NextNight *InvitationNight
}
Invitation is what a signed-out person sees about the campaign a link, emailed invite or guest code opens. It is built only for one that is valid right now.
type InvitationMember ¶
InvitationMember is one person at the table: a name and a picture, nothing else, so the door never carries an email address or a role.
type InvitationNight ¶
type InvitationNight struct {
// Date is YYYY-MM-DD and Time "HH:MM", both on the wall clock of TZ.
Date string
Time string
TZ string
// At is the start instant, so the page can show it in the reader's own zone.
At time.Time
}
InvitationNight is the next game night. Time is "" for an all-day night.
type InvitationSource ¶
type InvitationSource interface {
ByLink(ctx context.Context, code string) *Invitation
ByToken(ctx context.Context, token string) *Invitation
ByGuestCode(ctx context.Context, code string) *Invitation
}
InvitationSource is the campaign side of the door, implemented by an adapter in app so auth imports no other plugin. Each lookup returns nil for anything that is not valid right now: wrong, used, expired, revoked or archived all look the same.
type JoinInput ¶
JoinInput is what the join page sends. SessionUserID is set when someone already signed in uses a code, which only adds them to the campaign.
type JoinResult ¶
JoinResult says where the person landed. SessionToken is set only when a new guest was made.
type KeepGuestInput ¶
KeepGuestInput is the "Keep my account" form.
type LegacyAvatarRepository ¶
type LegacyAvatarRepository interface {
ListLegacyAvatarPaths(ctx context.Context, prefix string) (map[string]string, error)
UpdateAvatarPath(ctx context.Context, userID string, avatarPath *string) error
ClearAvatarPathIfMatches(ctx context.Context, userID, expectedPath string) (bool, error)
}
LegacyAvatarRepository is the repository surface ReconcileLegacyAvatarPaths needs. Satisfied by UserRepository.
type LoginInput ¶
type LoginInput struct {
Email string
Password string
IP string // Client IP for session tracking.
UserAgent string // Client User-Agent for session tracking.
// TrustedDevice is the remembered-device cookie, which skips the code
// step for the person it was issued to.
TrustedDevice string
}
LoginInput is the validated input for authenticating a user.
type LoginOptions ¶
type LoginOptions struct {
// ProviderName is the button's name; empty means no provider button.
ProviderName string
// HidePassword folds the password form away behind an "admins" link.
HidePassword bool
}
LoginOptions is what the sign-in page needs to know about the provider.
type LoginRequest ¶
type LoginRequest struct {
Email string `json:"email" form:"email" validate:"required,email"`
Password string `json:"password" form:"password" validate:"required"`
}
LoginRequest holds the data submitted by the login form.
type MailSender ¶
type MailSender interface {
SendMail(ctx context.Context, to []string, subject, body string) error
IsConfigured(ctx context.Context) bool
}
MailSender sends email for password reset and other auth-related flows. Matches smtp.MailService to avoid importing the smtp package directly.
type MergeGuestInput ¶
MergeGuestInput is the "I already have an account" form.
type MySession ¶
MySession is one browser signed in as the user, as their own account page lists it. ID is the token's hash, so the page never holds a usable token.
type OIDCCallbackInput ¶
type OIDCCallbackInput struct {
State string
Code string
ProviderError string
SessionUserID string
IP string
UserAgent string
TrustedDevice string
}
OIDCCallbackInput is the provider's answer as the callback received it.
type OIDCResult ¶
OIDCResult says what a finished round trip did.
type OIDCSettings ¶
type OIDCSettings struct {
Enabled bool
ButtonName string
Issuer string
ClientID string
HasSecret bool
AllowSignup bool
HidePassword bool
RedirectURL string
LastTestAt *time.Time
LastTestOK bool
LastTestNote string
}
OIDCSettings is the provider setting as the admin page shows it. The secret itself never leaves the service.
type OIDCSettingsInput ¶
type OIDCSettingsInput struct {
Enabled bool
ButtonName string
Issuer string
ClientID string
ClientSecret string
AllowSignup bool
HidePassword bool
}
OIDCSettingsInput is what the admin form saves. An empty ClientSecret keeps the stored one.
type OIDCStore ¶
type OIDCStore interface {
GetOIDCSettings(ctx context.Context) (oidcSettingsRow, error)
SaveOIDCSettings(ctx context.Context, row oidcSettingsRow) error
RecordOIDCTest(ctx context.Context, ok bool, note string) error
FindIdentity(ctx context.Context, issuer, subject string) (userID string, err error)
LinkIdentity(ctx context.Context, userID, issuer, subject, email string) error
TouchIdentity(ctx context.Context, issuer, subject string) error
ListIdentities(ctx context.Context, userID string) ([]Identity, error)
UnlinkIdentities(ctx context.Context, userID, issuer string) error
}
OIDCStore keeps the provider setting and the account links. It is a separate interface from UserRepository so only the provider code needs it.
type OwnedCampaignRef ¶
OwnedCampaignRef is a campaign that blocks deletion until it is handed over or deleted.
type RegisterInput ¶
type RegisterInput struct {
Email string
DisplayName string
Password string
// InviteToken carries a campaign invite token when the registration came
// through the invite-accept flow. In invite-only mode it is the only way a
// non-first user may register; ignored in open mode.
InviteToken string
}
RegisterInput is the validated input for creating a new user.
type RegisterRequest ¶
type RegisterRequest struct {
Email string `json:"email" form:"email" validate:"required,email,max=255"`
DisplayName string `json:"display_name" form:"display_name" validate:"required,min=2,max=100"`
Password string `json:"password" form:"password" validate:"required,min=8,max=128"`
Confirm string `json:"confirm" form:"confirm" validate:"required,eqfield=Password"`
}
RegisterRequest holds the data submitted by the registration form.
type RegistrationInviteChecker ¶
type RegistrationInviteChecker interface {
IsRegistrationInviteValid(ctx context.Context, token, email string) bool
}
RegistrationInviteChecker reports whether a campaign invite token currently permits creating an account: the invite exists, is unaccepted and unexpired, and — when email is non-empty — was issued to that email (campaign invites are email-scoped). An empty email checks only token liveness (the register-page pre-check). Satisfied by an adapter over the campaigns invite service, wired in app/routes.go.
type RegistrationPolicy ¶
RegistrationPolicy reads the site registration mode. Satisfied by the settings service; kept as a local interface so auth stays decoupled from that plugin.
type SecurityEventLogger ¶
type SecurityEventLogger interface {
LogEvent(ctx context.Context, eventType, userID, actorID, ip, userAgent string, details map[string]any) error
}
SecurityEventLogger records security events for the admin security dashboard. Implemented by the admin security service; wired after both are initialized.
type Session ¶
type Session struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Name string `json:"name"`
IsAdmin bool `json:"is_admin"`
// AvatarPath is the user's avatar media id (empty if unset). Cached here
// like Name/Email so the top bar can render it without a DB hit on every
// page; it carries the same eventual-consistency lag as those fields —
// refreshed at login and by the periodic revalidation below.
AvatarPath string `json:"avatar_path,omitempty"`
// GuestCampaignID fences a guest's session to their one campaign.
GuestCampaignID string `json:"guest_campaign_id,omitempty"`
IP string `json:"ip,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastValidated time.Time `json:"last_validated"`
}
Session represents an authenticated user session stored in Redis. The session ID is the key, and this struct is the value (JSON-encoded). LastValidated tracks when the session was last checked against the database to detect user deletions, disablements, or privilege changes that occurred outside the normal service layer. Zero-value triggers immediate revalidation (backwards-compatible with sessions created before this field existed).
func GetSession ¶
GetSession retrieves the authenticated session from the Echo context. Returns nil if the request is not authenticated (middleware not applied).
type SessionInfo ¶
type SessionInfo struct {
Token string `json:"-"` // Full token (for termination). Never expose in UI.
TokenHash string `json:"-"` // SHA-256 hash of token for safe URL references.
TokenHint string `json:"token_hint"` // First 8 chars for display.
UserID string `json:"user_id"`
Email string `json:"email"`
Name string `json:"name"`
IsAdmin bool `json:"is_admin"`
IP string `json:"ip"`
UserAgent string `json:"user_agent"`
CreatedAt time.Time `json:"created_at"`
TTL time.Duration `json:"ttl"` // Remaining time-to-live.
}
SessionInfo extends Session with metadata for the admin active sessions view.
type SignInMethods ¶
SignInMethods is the account page's Sign-in methods section.
type TwoFactorLoginInput ¶
type TwoFactorLoginInput struct {
Challenge string
// Code is a 6-digit authenticator code or a recovery code; the shape
// tells them apart.
Code string
Remember bool
IP string
UserAgent string
}
TwoFactorLoginInput is the second sign-in step.
type TwoFactorLoginResult ¶
TwoFactorLoginResult carries the new session and, when the person asked not to be asked again, the trusted-device token for its cookie.
type TwoFactorRequired ¶
type TwoFactorRequired struct {
Challenge string
}
TwoFactorRequired is what Login returns when the password was right but the account also wants a code. Challenge names the half-finished sign-in for CompleteTwoFactorLogin; it is not a session.
func (*TwoFactorRequired) Error ¶
func (e *TwoFactorRequired) Error() string
type TwoFactorSetup ¶
type TwoFactorSetup struct {
// Secret is the key spaced in groups of four for typing by hand.
Secret string `json:"secret"`
// QR is a PNG data URI of the otpauth address.
QR string `json:"qr"`
}
TwoFactorSetup is what the account page shows while turning two-factor on.
type TwoFactorStatus ¶
TwoFactorStatus is the account page's view of a person's two-factor.
type UpdateViewPrefsInput ¶
type UpdateViewPrefsInput struct {
Theme patch.Field[string] `json:"theme"`
Motion patch.Field[string] `json:"motion"`
TextSize patch.Field[string] `json:"textSize"`
Contrast patch.Field[string] `json:"contrast"`
}
UpdateViewPrefsInput is a PARTIAL update: each choice saves on its own as the person taps it, so an absent key preserves the stored choice, an explicit null or "" resets that one choice to its default, and a value replaces it. Echoing the others back would race a second device.
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
PasswordHash string `json:"-"` // Never expose in JSON responses.
AvatarPath *string `json:"avatar_path,omitempty"`
IsAdmin bool `json:"is_admin"`
IsDisabled bool `json:"is_disabled"`
TOTPSecret *string `json:"-"` // Never expose.
TOTPEnabled bool `json:"totp_enabled"`
Timezone *string `json:"timezone,omitempty"` // IANA timezone (e.g. "America/New_York"). Nil = UTC.
// GuestCampaignID is set while the account is a guest: joined with a
// guest code, fenced to that one campaign, with no email or password.
GuestCampaignID *string `json:"guest_campaign_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
LastLoginAt *time.Time `json:"last_login_at,omitempty"`
}
User represents a registered Chronicle user. This is the domain model used throughout the application. Database scanning and JSON marshaling use this struct directly.
type UserFilter ¶
type UserFilter string
UserFilter narrows the admin people list to one chip's worth of users.
const ( // UserFilterAll applies no role/status narrowing. UserFilterAll UserFilter = "" // UserFilterAdmins keeps only users with is_admin set. UserFilterAdmins UserFilter = "admins" // UserFilterDisabled keeps only disabled accounts. UserFilterDisabled UserFilter = "disabled" )
func ParseUserFilter ¶
func ParseUserFilter(raw string) UserFilter
ParseUserFilter maps a raw query value to a known filter. Anything unrecognised means "all" so a stale or hand-edited URL still lists people.
type UserFilterCounts ¶
UserFilterCounts are the chip counts for one search text, each counting the users that chip would show.
func (UserFilterCounts) For ¶
func (c UserFilterCounts) For(f UserFilter) int
For returns the count a chip shows for the given filter.
type UserRepository ¶
type UserRepository interface {
Create(ctx context.Context, user *User) error
FindByID(ctx context.Context, id string) (*User, error)
FindByEmail(ctx context.Context, email string) (*User, error)
EmailExists(ctx context.Context, email string) (bool, error)
UpdateLastLogin(ctx context.Context, id string) error
// Password reset.
UpdatePassword(ctx context.Context, userID, passwordHash string) error
CreateResetToken(ctx context.Context, userID, email, tokenHash string, expiresAt time.Time) error
FindResetToken(ctx context.Context, tokenHash string) (userID, email string, expiresAt time.Time, usedAt *time.Time, err error)
MarkResetTokenUsed(ctx context.Context, tokenHash string) (bool, error)
// User profile.
UpdateTimezone(ctx context.Context, userID, timezone string) error
GetTimezonesByIDs(ctx context.Context, userIDs []string) (map[string]string, error)
UpdateDisplayName(ctx context.Context, userID, displayName string) error
UpdateAvatarPath(ctx context.Context, userID string, avatarPath *string) error
// View preferences: the person's own look, as the stored JSON (nil when
// they have chosen nothing).
GetViewPrefs(ctx context.Context, userID string) ([]byte, error)
SetViewPrefs(ctx context.Context, userID string, prefs []byte) error
GetNotifyPrefs(ctx context.Context, userID string) ([]byte, error)
SetNotifyPrefs(ctx context.Context, userID string, prefs []byte) error
// ListNotifyPrefs returns the stored notify_prefs JSON of each listed
// user that has any; users with none are absent from the map.
ListNotifyPrefs(ctx context.Context, userIDs []string) (map[string][]byte, error)
// AnonymizeUser empties a deleted account's row: personal fields
// cleared, a placeholder email and name, an unusable password,
// disabled and stamped deleted_at. Its reset tokens are removed.
AnonymizeUser(ctx context.Context, userID, email, displayName, passwordHash string) error
// ListLegacyAvatarPaths returns userID -> avatar_path for every user
// whose avatar_path still starts with prefix. Used only by the boot
// reconciler (reconcile_avatar_paths.go) to find rows still pointing at
// a dead legacy web path; ordinary reads use FindByID/FindByEmail.
ListLegacyAvatarPaths(ctx context.Context, prefix string) (map[string]string, error)
// ClearAvatarPathIfMatches sets avatar_path to NULL only if it still
// equals expectedPath, reporting whether it actually cleared the row.
// Used by the boot reconciler so a legacy row a user has already
// overwritten with a real upload between listing and this write is
// never clobbered back to NULL.
ClearAvatarPathIfMatches(ctx context.Context, userID, expectedPath string) (bool, error)
// Email change verification.
SetPendingEmail(ctx context.Context, userID, pendingEmail, tokenHash string, expiresAt time.Time) error
FindByEmailVerifyToken(ctx context.Context, tokenHash string) (userID, pendingEmail string, expiresAt time.Time, err error)
ConfirmEmailChange(ctx context.Context, userID, newEmail string) error
// Admin operations.
ListUsers(ctx context.Context, offset, limit int) ([]User, int, error)
SearchUsers(ctx context.Context, opts UserSearchOptions) ([]User, error)
CountUserFilters(ctx context.Context, query string) (UserFilterCounts, error)
UpdateIsAdmin(ctx context.Context, id string, isAdmin bool) error
UpdateIsDisabled(ctx context.Context, id string, isDisabled bool) error
CountUsers(ctx context.Context) (int, error)
CountAdmins(ctx context.Context) (int, error)
// Two-factor sign-in. The secret arrives already encrypted; nil clears it.
SetTOTP(ctx context.Context, userID string, encryptedSecret *string, enabled bool) error
ReplaceRecoveryCodes(ctx context.Context, userID string, hashes []string) error
UseRecoveryCode(ctx context.Context, userID, hash string) (bool, error)
CountRecoveryCodes(ctx context.Context, userID string) (int, error)
// Guests. KeepGuestAccount gives a guest an email and password and lifts
// the fence; an email someone else uses is a Conflict.
KeepGuestAccount(ctx context.Context, userID, email, passwordHash string) error
ListCampaignGuests(ctx context.Context, campaignID string) ([]string, error)
// TouchLastSeen records that the person used the site just now.
TouchLastSeen(ctx context.Context, userID string) error
}
UserRepository defines the data access contract for user operations. All SQL lives in the concrete implementation -- no SQL leaks out.
func NewUserRepository ¶
func NewUserRepository(db *sql.DB) UserRepository
NewUserRepository creates a new user repository backed by the given DB pool.
type UserSearchOptions ¶
type UserSearchOptions struct {
// Query matches display name or email as a case-insensitive substring.
Query string
Filter UserFilter
Offset int
PerPage int
}
UserSearchOptions are the already-validated inputs of the people list.
type ViewPrefs ¶
type ViewPrefs struct {
Theme string `json:"theme"` // device | light | dark
Motion string `json:"motion"` // owner | calm | off
TextSize string `json:"textSize"` // standard | larger | largest
Contrast string `json:"contrast"` // standard | high
// BrushHidden lists the campaigns where this person put the header's
// Customize brush away. The choice is per campaign: hiding it in one
// leaves it shown in the rest. Newest last; never nil.
BrushHidden []string `json:"brushHidden"`
}
ViewPrefs are one person's own viewing choices. They are per account and per viewer only: nothing here is ever read for another member's page or written to a campaign's settings, so a player's choice can never change what the owner or anyone else sees. Every field always holds one of its allowed values; the first value of each list is the default.
func DefaultViewPrefs ¶
func DefaultViewPrefs() ViewPrefs
DefaultViewPrefs is the look a person gets before choosing anything.
func ParseViewPrefs ¶
ParseViewPrefs reads the stored JSON column. Missing, malformed or out-of-list values fall back to the default for that one choice, so a hand-edited row or a future rename degrades to the default look rather than failing the page.
func (ViewPrefs) HidesBrushIn ¶
HidesBrushIn reports whether the brush is put away in this campaign.