authkit/service_user.go
juancwu d3c5367492 Rebuild for v1.0.0: postgres-only, slug-keyed authz, predicate API
Drops the Dialect/Queries abstraction in favor of a single PostgreSQL 16+
implementation collapsed into the root authkit package, removes the
public store interfaces, and reshapes the authorization model around
seeded slugs (roles, permissions, abilities) with optional labels.

Schema is now squashed into one migrations/0001_init.sql and applied
automatically on authkit.New (opt-out via Config.SkipAutoMigrate). A
schema verifier checks tables/columns/types/nullability on startup,
tolerates extra columns, and falls back to default table names when a
configured override is missing.

Auth API: CreateUser + SetPassword replace Register; password is
nullable. Email OTP (RequestEmailOTP/ConsumeEmailOTP) joins magic links
and password reset, all with anti-enumeration silent-success defaults
and a Config.RevealUnknownEmail opt-in. Service tokens drop owner
columns and validate ability slugs against authkit_abilities at issue.
Direct user permissions live alongside role-derived ones; queries
return their UNION.

Predicate API: HasRole/HasPermission/HasAbility leaves with
AnyLogin/AllLogin/AnyServiceKey/AllServiceKey combinators. Validate
runs at middleware construction, panicking on unknown slugs.

Middleware collapses to RequireLogin (cookie + JWT), RequireGuest
(configurable OnAuthenticated), and RequireServiceKey. UserIDFromCtx /
UserFromCtx (lazy) / RefreshUserInCtx provide request-lifetime user
caching. Cookie defaults flip to Secure=true and HttpOnly=true via
*bool with BoolPtr opt-out.

CLIs ship under cmd/perms, cmd/roles, cmd/abilities for seeding the
authorization vocabulary; the library never seeds rows itself.

Tests cover unit-level (slug validation + fuzz, opaque secrets, email
normalization, extractors, predicates, OTP generator) and integration
flows gated on AUTHKIT_TEST_DATABASE_URL (every Auth method, schema
drift detection, migration idempotency, lazy user cache, all middleware
paths).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 23:27:30 +00:00

219 lines
6.9 KiB
Go

package authkit
import (
"context"
"errors"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// CreateUser registers a new account with the given email. Password is
// optional — accounts can be created without a credential and have one set
// later via SetPassword. Returns ErrEmailTaken if the normalized email is
// already registered.
func (a *Auth) CreateUser(ctx context.Context, email string) (*User, error) {
const op = "authkit.Auth.CreateUser"
if email == "" {
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
now := a.now()
u := &User{
ID: uuid.New(),
Email: email,
EmailNormalized: normalizeEmail(email),
CreatedAt: now,
UpdatedAt: now,
}
if err := a.storeCreateUser(ctx, u); err != nil {
return nil, errx.Wrap(op, err)
}
return u, nil
}
// SetPassword stores a password hash for the user. Use for the
// initial-credential flow and for administrative password changes.
// Bumping session_version is the caller's responsibility; SetPassword does
// not invalidate existing sessions on its own. ChangePassword is the
// safer wrapper for end-user-driven changes.
func (a *Auth) SetPassword(ctx context.Context, userID uuid.UUID, password string) error {
const op = "authkit.Auth.SetPassword"
if password == "" {
return errx.Wrap(op, ErrInvalidCredentials)
}
hash, err := a.hasher.Hash(password)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeSetPassword(ctx, userID, hash); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// LoginPassword verifies the password and returns the authenticated user.
// Failure does not increment any counter — consumers wanting lockout should
// implement it via LoginHook (see README). Success resets nothing and stamps
// last_login_at. LoginHook is invoked with the success outcome.
func (a *Auth) LoginPassword(ctx context.Context, email, password string) (*User, error) {
const op = "authkit.Auth.LoginPassword"
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
if err != nil {
_ = a.fireLoginHook(ctx, email, false)
if errors.Is(err, ErrUserNotFound) {
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
return nil, errx.Wrap(op, err)
}
if u.PasswordHash == "" {
// Password-less account (invite-only / magic-link-only). Treat the
// same as wrong password to avoid leaking account state.
_ = a.fireLoginHook(ctx, email, false)
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
ok, needsRehash, err := a.hasher.Verify(password, u.PasswordHash)
if err != nil {
return nil, errx.Wrap(op, err)
}
if !ok {
_ = a.fireLoginHook(ctx, email, false)
return nil, errx.Wrap(op, ErrInvalidCredentials)
}
now := a.now()
u.LastLoginAt = &now
if err := a.storeUpdateUser(ctx, u); err != nil {
return nil, errx.Wrap(op, err)
}
if needsRehash {
if newHash, herr := a.hasher.Hash(password); herr == nil {
_ = a.storeSetPassword(ctx, u.ID, newHash)
u.PasswordHash = newHash
}
}
_ = a.fireLoginHook(ctx, email, true)
return u, nil
}
// ChangePassword verifies the current password, sets the new one, and bumps
// the user's session_version (invalidating outstanding JWTs). Outstanding
// opaque sessions are also revoked.
func (a *Auth) ChangePassword(ctx context.Context, userID uuid.UUID, oldPassword, newPassword string) error {
const op = "authkit.Auth.ChangePassword"
u, err := a.storeGetUserByID(ctx, userID)
if err != nil {
return errx.Wrap(op, err)
}
if u.PasswordHash == "" {
return errx.Wrap(op, ErrInvalidCredentials)
}
ok, _, err := a.hasher.Verify(oldPassword, u.PasswordHash)
if err != nil {
return errx.Wrap(op, err)
}
if !ok {
return errx.Wrap(op, ErrInvalidCredentials)
}
newHash, err := a.hasher.Hash(newPassword)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.storeSetPassword(ctx, userID, newHash); err != nil {
return errx.Wrap(op, err)
}
if _, err := a.storeBumpSessionVersion(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
if err := a.storeDeleteUserSessions(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// GetUser fetches the user by ID. Returns ErrUserNotFound if absent.
func (a *Auth) GetUser(ctx context.Context, userID uuid.UUID) (*User, error) {
const op = "authkit.Auth.GetUser"
u, err := a.storeGetUserByID(ctx, userID)
if err != nil {
return nil, errx.Wrap(op, err)
}
return u, nil
}
// GetUserByEmail fetches the user by email (input is normalized internally).
func (a *Auth) GetUserByEmail(ctx context.Context, email string) (*User, error) {
const op = "authkit.Auth.GetUserByEmail"
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
if err != nil {
return nil, errx.Wrap(op, err)
}
return u, nil
}
// DeleteUser removes the user. Cascades to sessions, tokens, role
// assignments, and direct permission grants via FK ON DELETE CASCADE.
func (a *Auth) DeleteUser(ctx context.Context, userID uuid.UUID) error {
const op = "authkit.Auth.DeleteUser"
if err := a.storeDeleteUser(ctx, userID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// RequestEmailVerification mints a single-use email-verify token for the
// user. Return the plaintext to the caller for delivery; the lookup hash
// is what's stored.
func (a *Auth) RequestEmailVerification(ctx context.Context, userID uuid.UUID) (string, error) {
const op = "authkit.Auth.RequestEmailVerification"
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixEmailVerify)
if err != nil {
return "", errx.Wrap(op, err)
}
now := a.now()
t := &Token{
Hash: hash,
Kind: TokenEmailVerify,
UserID: userID,
CreatedAt: now,
ExpiresAt: now.Add(a.cfg.EmailVerifyTTL),
}
if err := a.storeCreateToken(ctx, t); err != nil {
return "", errx.Wrap(op, err)
}
return plaintext, nil
}
// ConfirmEmail consumes a verification token and marks the user's email
// verified. Returns ErrTokenInvalid for missing/expired/already-used tokens.
func (a *Auth) ConfirmEmail(ctx context.Context, plaintextToken string) (*User, error) {
const op = "authkit.Auth.ConfirmEmail"
hash, ok := ParseOpaqueSecret(prefixEmailVerify, plaintextToken)
if !ok {
return nil, errx.Wrap(op, ErrTokenInvalid)
}
now := a.now()
t, err := a.storeConsumeToken(ctx, TokenEmailVerify, hash, now)
if err != nil {
return nil, errx.Wrap(op, err)
}
if err := a.storeSetEmailVerified(ctx, t.UserID, now); err != nil {
return nil, errx.Wrap(op, err)
}
return a.storeGetUserByID(ctx, t.UserID)
}
// fireLoginHook runs Config.LoginHook if configured. Returned errors are
// surfaced for the caller to log; they never break login. The hook is
// wrapped in recover() so a misbehaving hook can't take down the auth path.
func (a *Auth) fireLoginHook(ctx context.Context, email string, success bool) (err error) {
if a.cfg.LoginHook == nil {
return nil
}
defer func() {
if r := recover(); r != nil {
err = errx.Newf("authkit.fireLoginHook", "login hook panicked: %v", r)
}
}()
return a.cfg.LoginHook(ctx, email, success)
}