authkit/store_sessions.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

95 lines
2.4 KiB
Go

package authkit
import (
"context"
"database/sql"
"time"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
func (a *Auth) storeCreateSession(ctx context.Context, s *Session) error {
const op = "authkit.storeCreateSession"
now := a.now()
if s.CreatedAt.IsZero() {
s.CreatedAt = now
}
if s.LastSeenAt.IsZero() {
s.LastSeenAt = s.CreatedAt
}
_, err := a.db.ExecContext(ctx, a.q.createSession,
s.IDHash, uuidArg(s.UserID), s.UserAgent, nullableAddrString(s.IP),
s.CreatedAt, s.LastSeenAt, s.ExpiresAt)
if err != nil {
return errx.Wrap(op, err)
}
return nil
}
func (a *Auth) storeGetSession(ctx context.Context, idHash []byte) (*Session, error) {
const op = "authkit.storeGetSession"
var (
s Session
uidStr string
ipStr sql.NullString
)
err := a.db.QueryRowContext(ctx, a.q.getSession, idHash).Scan(
&s.IDHash, &uidStr, &s.UserAgent, &ipStr,
&s.CreatedAt, &s.LastSeenAt, &s.ExpiresAt)
if err != nil {
return nil, errx.Wrap(op, mapNotFound(err, ErrSessionInvalid))
}
uid, err := scanUUID(uidStr)
if err != nil {
return nil, errx.Wrap(op, err)
}
s.UserID = uid
if ipStr.Valid {
addr, err := scanAddr(&ipStr.String)
if err != nil {
return nil, errx.Wrap(op, err)
}
s.IP = addr
}
return &s, nil
}
func (a *Auth) storeTouchSession(ctx context.Context, idHash []byte, lastSeenAt, newExpiresAt time.Time) error {
const op = "authkit.storeTouchSession"
tag, err := a.db.ExecContext(ctx, a.q.touchSession, lastSeenAt, newExpiresAt, idHash)
if err != nil {
return errx.Wrap(op, err)
}
n, _ := tag.RowsAffected()
if n == 0 {
return errx.Wrap(op, ErrSessionInvalid)
}
return nil
}
func (a *Auth) storeDeleteSession(ctx context.Context, idHash []byte) error {
const op = "authkit.storeDeleteSession"
if _, err := a.db.ExecContext(ctx, a.q.deleteSession, idHash); err != nil {
return errx.Wrap(op, err)
}
return nil
}
func (a *Auth) storeDeleteUserSessions(ctx context.Context, userID uuid.UUID) error {
const op = "authkit.storeDeleteUserSessions"
if _, err := a.db.ExecContext(ctx, a.q.deleteUserSessions, uuidArg(userID)); err != nil {
return errx.Wrap(op, err)
}
return nil
}
func (a *Auth) storeDeleteExpiredSessions(ctx context.Context, now time.Time) (int64, error) {
const op = "authkit.storeDeleteExpiredSessions"
tag, err := a.db.ExecContext(ctx, a.q.deleteExpiredSessions, now)
if err != nil {
return 0, errx.Wrap(op, err)
}
n, _ := tag.RowsAffected()
return n, nil
}