Documentation
¶
Overview ¶
Package auth implements local accounts, session cookies, and API keys. No external identity provider — bcrypt-hashed passwords in the same SQLite DB, signed HTTP-only session cookies, and per-user API keys for headless/programmatic access.
Package auth handles accounts, passwords (bcrypt), sessions and API keys.
Index ¶
- Constants
- Variables
- func ClearSessionCookie(w http.ResponseWriter, secure bool)
- func SetSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time, secure bool)
- type APIKey
- type Account
- type AccountUpdate
- type LoginLimiter
- type Service
- func (s *Service) Authenticate(username, password string) (*User, error)
- func (s *Service) ChangePassword(userID int64, currentPassword, newPassword string) error
- func (s *Service) CreateAPIKey(userID int64, name string) (rawKey string, err error)
- func (s *Service) CreateAccount(username, password, firstName, lastName, email string, isAdmin bool) (*Account, error)
- func (s *Service) CreateFirstAdmin(username, password, firstName, lastName, email string) (*User, error)
- func (s *Service) CreateSession(userID int64) (token string, expiresAt time.Time, err error)
- func (s *Service) CreateUser(username, password string) (*User, error)
- func (s *Service) CreateUserWithProfile(username, password, firstName, lastName, email string) (*User, error)
- func (s *Service) DeleteAccount(id int64) error
- func (s *Service) DeleteSession(token string) error
- func (s *Service) FirstRunNeeded() (bool, error)
- func (s *Service) GetAccount(id int64) (*Account, error)
- func (s *Service) GetUser(id int64) (*User, error)
- func (s *Service) ListAPIKeys(userID int64) ([]APIKey, error)
- func (s *Service) ListAccounts() ([]Account, error)
- func (s *Service) Middleware(next http.Handler) http.Handler
- func (s *Service) RecordLogin(id int64) error
- func (s *Service) ResetPassword(username, newPassword string) error
- func (s *Service) RevokeAPIKey(userID, id int64) error
- func (s *Service) UpdateAccount(id int64, upd AccountUpdate) (*Account, error)
- func (s *Service) UpdateProfile(userID int64, username, firstName, lastName, email string) (*User, error)
- func (s *Service) UserForAPIKey(rawKey string) (*User, error)
- func (s *Service) UserForSession(token string) (*User, error)
- type User
Constants ¶
const ( RoleAdmin = "admin" // everything, including settings and accounts RoleMember = "member" // browse, add titles and follow downloads; no settings )
Roles. is_admin in the users table is the source of truth; Role is the name the API and the docs use for it.
const CookieName = "mediarium_session"
const MaxPasswordBytes = 72
MaxPasswordBytes is the longest password bcrypt takes: it looks at no more than 72 bytes, and refuses anything longer.
Variables ¶
var ( // ErrUserNotFound is returned when an account id does not exist. ErrUserNotFound = errors.New("no such account") // ErrLastAdmin is returned when a change would leave no administrator. ErrLastAdmin = errors.New("there must always be at least one administrator") )
var ( ErrInvalidCredentials = errors.New("invalid username or password") ErrUsernameTaken = errors.New("username already taken") ErrSessionNotFound = errors.New("session not found or expired") // ErrSetupDone is returned by CreateFirstAdmin once any account exists. ErrSetupDone = errors.New("an admin account already exists") // ErrPasswordTooLong is returned for a password bcrypt cannot use whole. ErrPasswordTooLong = errors.New("password must be at most 72 bytes") )
Functions ¶
func ClearSessionCookie ¶
func ClearSessionCookie(w http.ResponseWriter, secure bool)
ClearSessionCookie expires the session cookie; secure must match the way it was set.
func SetSessionCookie ¶
SetSessionCookie writes the session cookie: an opaque random token that is looked up server-side, HttpOnly (scripts cannot read it) and SameSite=Strict (browsers never send it on a request started by another site). secure marks it Secure (HTTPS only); the caller sets it whenever the visitor reached Mediarium over HTTPS, directly or through a trusted proxy.
Types ¶
type Account ¶
type Account struct {
User
CreatedAt time.Time
LastLoginAt *time.Time // nil until the account first signs in
}
Account is a User plus the bookkeeping the account list shows.
type AccountUpdate ¶
type AccountUpdate struct {
FirstName *string
LastName *string
Email *string
IsAdmin *bool
Password *string // a new password; the account's sessions are signed out
}
AccountUpdate lists the changes an administrator makes to an account; a nil field is left as it is.
type LoginLimiter ¶
type LoginLimiter struct {
// contains filtered or unexported fields
}
LoginLimiter blunts brute-force login attempts ("a handful of attempts per IP/window") with a simple in-memory sliding window. Deliberately not persisted to the DB: a restart resetting attempt counts is an acceptable tradeoff for avoiding a write on every single login attempt, and this only needs to survive for the duration of an actual brute-force burst, not across restarts.
func NewLoginLimiter ¶
func NewLoginLimiter(maxAttempts int, window time.Duration) *LoginLimiter
func (*LoginLimiter) Allow ¶
func (l *LoginLimiter) Allow(key string) bool
Allow reports whether key (typically a client IP) is still under the attempt limit for the current window.
func (*LoginLimiter) RecordFailure ¶
func (l *LoginLimiter) RecordFailure(key string)
RecordFailure counts one failed attempt against key.
func (*LoginLimiter) RecordSuccess ¶
func (l *LoginLimiter) RecordSuccess(key string)
RecordSuccess clears key's attempt history — a successful login isn't itself an attack signal, and shouldn't count toward the next window.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
func (*Service) Authenticate ¶
Authenticate verifies a username/password pair.
func (*Service) ChangePassword ¶
ChangePassword verifies the user's current password before setting a new one, so a hijacked-but-still-open session can't be used to lock the real owner out by itself. Every session of the account is signed out (the caller starts a fresh one for the browser that made the change), so a stolen session does not survive the password change.
func (*Service) CreateAPIKey ¶
CreateAPIKey generates a new API key for userID. The raw key is returned once and never recoverable afterward.
func (*Service) CreateAccount ¶
func (s *Service) CreateAccount(username, password, firstName, lastName, email string, isAdmin bool) (*Account, error)
CreateAccount adds an account with an explicit role, for an administrator setting up someone else's login. ErrUsernameTaken when the name is in use.
func (*Service) CreateFirstAdmin ¶
func (s *Service) CreateFirstAdmin(username, password, firstName, lastName, email string) (*User, error)
CreateFirstAdmin creates the first account, an administrator, for the onboarding wizard. The check that no account exists and the insert are one statement, so two simultaneous requests can never both become administrator: the second gets ErrSetupDone.
func (*Service) CreateSession ¶
CreateSession issues a new opaque session token, returning the raw token (only this call ever sees the plaintext — the DB stores its hash).
func (*Service) CreateUser ¶
CreateUser creates a new local account. The very first account created is implicitly admin.
func (*Service) CreateUserWithProfile ¶
func (s *Service) CreateUserWithProfile(username, password, firstName, lastName, email string) (*User, error)
CreateUserWithProfile is CreateUser plus the profile fields the onboarding wizard collects.
func (*Service) DeleteAccount ¶
DeleteAccount removes an account together with its sessions and API keys. Deleting the last administrator fails with ErrLastAdmin.
func (*Service) DeleteSession ¶
DeleteSession logs a single session out.
func (*Service) FirstRunNeeded ¶
FirstRunNeeded reports whether no admin account exists yet (the onboarding wizard triggers automatically until this is false).
func (*Service) GetAccount ¶
GetAccount loads one account, or ErrUserNotFound.
func (*Service) ListAPIKeys ¶
ListAPIKeys returns userID's API keys, active and revoked alike, newest first — never the raw key itself, which is only ever seen once, at creation (credentials are never exposed beyond what's needed).
func (*Service) ListAccounts ¶
ListAccounts returns every account, oldest first.
func (*Service) Middleware ¶
Middleware resolves the caller's session cookie or X-API-Key header into a *User in the request context, or rejects with 401.
func (*Service) RecordLogin ¶
RecordLogin stamps the account's last sign-in time.
func (*Service) ResetPassword ¶
ResetPassword sets a new password for username without needing the old one — the recovery path for a forgotten password, reachable only by someone with shell access to the container (cmd/app's reset-password subcommand), never over HTTP. Also drops every existing session for that user, so a stolen/forgotten-open session doesn't outlive the reset.
func (*Service) RevokeAPIKey ¶
RevokeAPIKey marks id revoked, scoped to userID so one user can't revoke another's key by guessing an ID.
func (*Service) UpdateAccount ¶
func (s *Service) UpdateAccount(id int64, upd AccountUpdate) (*Account, error)
UpdateAccount applies upd to account id in one transaction. Taking the administrator role away from the last administrator fails with ErrLastAdmin; a new password signs every session of the account out.
func (*Service) UpdateProfile ¶
func (s *Service) UpdateProfile(userID int64, username, firstName, lastName, email string) (*User, error)
UpdateProfile changes a user's username and profile details, returning the updated account. ErrUsernameTaken when another account already has the name.
func (*Service) UserForAPIKey ¶
UserForAPIKey resolves a raw API key header value to its user.
type User ¶
type User struct {
ID int64
Username string
IsAdmin bool
FirstName string
LastName string
Email string
}
func UserFromContext ¶
UserFromContext retrieves the authenticated user set by Middleware.
func (*User) DisplayName ¶
DisplayName is "First Last" (either half may be missing), falling back to the username when no name has been set.