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>
68 lines
2 KiB
Go
68 lines
2 KiB
Go
package authkit
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"git.juancwu.dev/juancwu/errx"
|
|
)
|
|
|
|
// RequestMagicLink mints a single-use magic-link token for the email and
|
|
// returns the plaintext for delivery.
|
|
//
|
|
// Default behavior is anti-enumeration: if the email is not registered,
|
|
// returns ("", nil) — the caller cannot distinguish "exists" from "doesn't
|
|
// exist". Set Config.RevealUnknownEmail = true to surface ErrUserNotFound.
|
|
func (a *Auth) RequestMagicLink(ctx context.Context, email string) (string, error) {
|
|
const op = "authkit.Auth.RequestMagicLink"
|
|
u, err := a.storeGetUserByEmail(ctx, normalizeEmail(email))
|
|
if err != nil {
|
|
if errors.Is(err, ErrUserNotFound) && !a.cfg.RevealUnknownEmail {
|
|
return "", nil
|
|
}
|
|
return "", errx.Wrap(op, err)
|
|
}
|
|
plaintext, hash, err := MintOpaqueSecret(a.cfg.Random, prefixMagicLink)
|
|
if err != nil {
|
|
return "", errx.Wrap(op, err)
|
|
}
|
|
now := a.now()
|
|
t := &Token{
|
|
Hash: hash,
|
|
Kind: TokenMagicLink,
|
|
UserID: u.ID,
|
|
CreatedAt: now,
|
|
ExpiresAt: now.Add(a.cfg.MagicLinkTTL),
|
|
}
|
|
if err := a.storeCreateToken(ctx, t); err != nil {
|
|
return "", errx.Wrap(op, err)
|
|
}
|
|
return plaintext, nil
|
|
}
|
|
|
|
// ConsumeMagicLink consumes the magic-link token and returns the
|
|
// authenticated user. Callers typically follow with IssueSession or
|
|
// IssueJWT to actually log the user in. A successful consume implicitly
|
|
// verifies the email (the user demonstrably controls the inbox).
|
|
func (a *Auth) ConsumeMagicLink(ctx context.Context, plaintextToken string) (*User, error) {
|
|
const op = "authkit.Auth.ConsumeMagicLink"
|
|
hash, ok := ParseOpaqueSecret(prefixMagicLink, plaintextToken)
|
|
if !ok {
|
|
return nil, errx.Wrap(op, ErrTokenInvalid)
|
|
}
|
|
now := a.now()
|
|
t, err := a.storeConsumeToken(ctx, TokenMagicLink, hash, now)
|
|
if err != nil {
|
|
return nil, errx.Wrap(op, err)
|
|
}
|
|
u, err := a.storeGetUserByID(ctx, t.UserID)
|
|
if err != nil {
|
|
return nil, errx.Wrap(op, err)
|
|
}
|
|
if u.EmailVerifiedAt == nil {
|
|
if err := a.storeSetEmailVerified(ctx, u.ID, now); err == nil {
|
|
u.EmailVerifiedAt = &now
|
|
}
|
|
}
|
|
return u, nil
|
|
}
|