M1: authentication with better-auth, verified end to end

Switches from the planned Auth.js v5 to better-auth 1.7.1. The plan
assumed the blocker would be schema fit; it is not. @auth/drizzle-adapter
accepts our tables verbatim. What rules Auth.js out is that credentials
providers hardcode JWT and never call adapter.createSession, and the
config assertion that would catch it only fires when EVERY provider is
credentials — so adding Google suppresses the warning and the app ships
silently broken. Phone OTP with database sessions is not reachable there
without hand-building the whole OTP security layer.

Also corrects a premise: better-auth's drizzle-orm peer is declared
OPTIONAL, so no 0.38 -> 0.45 upgrade is forced. Verified on 0.38.4.

- auth schema rewritten to better-auth 1.7.1's own getSchema() output:
  sessions/accounts/verifications reshaped, emailVerified and
  phoneVerified are BOOLEAN (a timestamptz there fails 100% of signups),
  accounts.issuer added, phone_otps dropped. Ban state now comes from the
  admin plugin rather than a second bannedAt column.
- Session resolution is one file. Everything downstream is written
  against our own Session type, so the provider stays swappable.
- Ban enforcement lives in the resolver because Session carries no ban
  field and protectedProcedure promises a non-banned user.
- Phone OTP sign-in, Google, role selection, tRPC user router.
- Synthetic emails for phone-first users, with isSyntheticEmail() gating
  every future send. Pros must supply a real address; clients need not.
- Duplicate-account detection, since both signup routes stay open and
  nothing correlates a phone to a Google identity. Detects only — merging
  accounts that carry reviews and payments needs its own tooling.
- SMS sender refuses to fall back to console logging in production.
- declaration:false for the app, which is the actual fix for the TS2742
  wall from better-auth's transitive zod under pnpm.

Verified against a live server: OTP sent, code verified, uuid PK honoured,
database session written, and an authenticated tRPC call resolved. A
signed-in stranger gets NOT_FOUND on another client's deck; anonymous
gets UNAUTHORIZED.

124 tests passing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
serfowi
2026-08-20 14:40:23 -04:00
co-authored by Claude Opus 5
parent 66dd4ac942
commit cebeda7f4c
32 changed files with 1873 additions and 397 deletions
@@ -12,46 +12,49 @@ CREATE TYPE "public"."urgency" AS ENUM('now', 'this_week', 'flexible');--> state
CREATE TYPE "public"."user_role" AS ENUM('client', 'pro', 'admin');--> statement-breakpoint
CREATE TYPE "public"."verification_status" AS ENUM('draft', 'pending', 'verified', 'rejected', 'suspended');--> statement-breakpoint
CREATE TABLE "accounts" (
"user_id" uuid NOT NULL,
"type" text NOT NULL,
"provider" text NOT NULL,
"provider_account_id" text NOT NULL,
"refresh_token" text,
"access_token" text,
"expires_at" integer,
"token_type" text,
"scope" text,
"id_token" text,
"session_state" text,
CONSTRAINT "accounts_provider_provider_account_id_pk" PRIMARY KEY("provider","provider_account_id")
);
--> statement-breakpoint
CREATE TABLE "phone_otps" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"phone" text NOT NULL,
"code_hash" text NOT NULL,
"attempts" integer DEFAULT 0 NOT NULL,
"consumed" boolean DEFAULT false NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
"issuer" text NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" uuid NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp with time zone,
"refresh_token_expires_at" timestamp with time zone,
"scope" text,
"password" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "accounts_issuer_account_unique" UNIQUE("issuer","account_id")
);
--> statement-breakpoint
CREATE TABLE "sessions" (
"session_token" text PRIMARY KEY NOT NULL,
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"token" text NOT NULL,
"user_id" uuid NOT NULL,
"expires" timestamp with time zone NOT NULL
"expires_at" timestamp with time zone NOT NULL,
"ip_address" text,
"user_agent" text,
"impersonated_by" uuid,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "sessions_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" text,
"email" text,
"email_verified" timestamp with time zone,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean DEFAULT false NOT NULL,
"phone" text,
"phone_verified" timestamp with time zone,
"phone_verified" boolean DEFAULT false,
"phone_verified_at" timestamp with time zone,
"image" text,
"role" "user_role" DEFAULT 'client' NOT NULL,
"banned_at" timestamp with time zone,
"banned" boolean DEFAULT false,
"ban_reason" text,
"ban_expires" timestamp with time zone,
"last_active_at" timestamp with time zone DEFAULT now(),
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
@@ -59,11 +62,13 @@ CREATE TABLE "users" (
CONSTRAINT "users_phone_unique" UNIQUE("phone")
);
--> statement-breakpoint
CREATE TABLE "verification_tokens" (
CREATE TABLE "verifications" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"identifier" text NOT NULL,
"token" text NOT NULL,
"expires" timestamp with time zone NOT NULL,
CONSTRAINT "verification_tokens_identifier_token_pk" PRIMARY KEY("identifier","token")
"value" text NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "categories" (
@@ -290,6 +295,7 @@ CREATE TABLE "audit_log" (
--> statement-breakpoint
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_impersonated_by_users_id_fk" FOREIGN KEY ("impersonated_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_pro_id_pro_profiles_user_id_fk" FOREIGN KEY ("pro_id") REFERENCES "public"."pro_profiles"("user_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_reviewed_by_users_id_fk" FOREIGN KEY ("reviewed_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "pro_availability" ADD CONSTRAINT "pro_availability_pro_id_pro_profiles_user_id_fk" FOREIGN KEY ("pro_id") REFERENCES "public"."pro_profiles"("user_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
@@ -319,9 +325,11 @@ ALTER TABLE "reviews" ADD CONSTRAINT "reviews_booking_id_bookings_id_fk" FOREIGN
ALTER TABLE "reviews" ADD CONSTRAINT "reviews_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "reviews" ADD CONSTRAINT "reviews_subject_id_users_id_fk" FOREIGN KEY ("subject_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "audit_log" ADD CONSTRAINT "audit_log_actor_id_users_id_fk" FOREIGN KEY ("actor_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "phone_otps_phone_idx" ON "phone_otps" USING btree ("phone","expires_at");--> statement-breakpoint
CREATE INDEX "accounts_user_idx" ON "accounts" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "sessions_user_idx" ON "sessions" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "users_role_idx" ON "users" USING btree ("role");--> statement-breakpoint
CREATE INDEX "users_phone_idx" ON "users" USING btree ("phone");--> statement-breakpoint
CREATE INDEX "verifications_identifier_idx" ON "verifications" USING btree ("identifier","expires_at");--> statement-breakpoint
CREATE INDEX "credentials_pro_idx" ON "credentials" USING btree ("pro_id");--> statement-breakpoint
CREATE INDEX "credentials_review_idx" ON "credentials" USING btree ("review_status");--> statement-breakpoint
CREATE INDEX "credentials_expiry_idx" ON "credentials" USING btree ("expires_at");--> statement-breakpoint
+219 -130
View File
@@ -1,5 +1,5 @@
{
"id": "9da9b63e-a29c-425d-806f-357f6f04e2e5",
"id": "d2669c23-7683-48e2-a271-03f7e5ddcbd1",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
@@ -8,56 +8,45 @@
"name": "accounts",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"issuer": {
"name": "issuer",
"type": "text",
"primaryKey": false,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider": {
"name": "provider",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_account_id": {
"name": "provider_account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"token_type": {
"name": "token_type",
"type": "text",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
@@ -68,14 +57,62 @@
"primaryKey": false,
"notNull": false
},
"session_state": {
"name": "session_state",
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"accounts_user_idx": {
"name": "accounts_user_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"indexes": {},
"foreignKeys": {
"accounts_user_id_users_id_fk": {
"name": "accounts_user_id_users_id_fk",
@@ -91,22 +128,23 @@
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"accounts_provider_provider_account_id_pk": {
"name": "accounts_provider_provider_account_id_pk",
"compositePrimaryKeys": {},
"uniqueConstraints": {
"accounts_issuer_account_unique": {
"name": "accounts_issuer_account_unique",
"nullsNotDistinct": false,
"columns": [
"provider",
"provider_account_id"
"issuer",
"account_id"
]
}
},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.phone_otps": {
"name": "phone_otps",
"public.sessions": {
"name": "sessions",
"schema": "",
"columns": {
"id": {
@@ -116,58 +154,63 @@
"notNull": true,
"default": "gen_random_uuid()"
},
"phone": {
"name": "phone",
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"code_hash": {
"name": "code_hash",
"type": "text",
"user_id": {
"name": "user_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"attempts": {
"name": "attempts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"consumed": {
"name": "consumed",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"impersonated_by": {
"name": "impersonated_by",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"phone_otps_phone_idx": {
"name": "phone_otps_phone_idx",
"sessions_user_idx": {
"name": "sessions_user_idx",
"columns": [
{
"expression": "phone",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "expires_at",
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -179,37 +222,6 @@
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.sessions": {
"name": "sessions",
"schema": "",
"columns": {
"session_token": {
"name": "session_token",
"type": "text",
"primaryKey": true,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"expires": {
"name": "expires",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk",
@@ -223,10 +235,31 @@
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"sessions_impersonated_by_users_id_fk": {
"name": "sessions_impersonated_by_users_id_fk",
"tableFrom": "sessions",
"tableTo": "users",
"columnsFrom": [
"impersonated_by"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"uniqueConstraints": {
"sessions_token_unique": {
"name": "sessions_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
@@ -246,19 +279,20 @@
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": false
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": false
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "timestamp with time zone",
"type": "boolean",
"primaryKey": false,
"notNull": false
"notNull": true,
"default": false
},
"phone": {
"name": "phone",
@@ -268,6 +302,13 @@
},
"phone_verified": {
"name": "phone_verified",
"type": "boolean",
"primaryKey": false,
"notNull": false,
"default": false
},
"phone_verified_at": {
"name": "phone_verified_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
@@ -286,8 +327,21 @@
"notNull": true,
"default": "'client'"
},
"banned_at": {
"name": "banned_at",
"banned": {
"name": "banned",
"type": "boolean",
"primaryKey": false,
"notNull": false,
"default": false
},
"ban_reason": {
"name": "ban_reason",
"type": "text",
"primaryKey": false,
"notNull": false
},
"ban_expires": {
"name": "ban_expires",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
@@ -368,40 +422,75 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification_tokens": {
"name": "verification_tokens",
"public.verifications": {
"name": "verifications",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires": {
"name": "expires",
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {
"verification_tokens_identifier_token_pk": {
"name": "verification_tokens_identifier_token_pk",
"indexes": {
"verifications_identifier_idx": {
"name": "verifications_identifier_idx",
"columns": [
"identifier",
"token"
]
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "expires_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
+2 -2
View File
@@ -5,8 +5,8 @@
{
"idx": 0,
"version": "7",
"when": 1787246593084,
"tag": "0000_old_gorilla_man",
"when": 1787250714989,
"tag": "0000_colossal_masked_marvel",
"breakpoints": true
}
]
+2 -2
View File
@@ -105,7 +105,7 @@ export async function getDeck(
WHERE j.id = ${args.jobId}
AND p.verification_status = 'verified'
AND p.is_accepting_jobs = true
AND u.banned_at IS NULL
AND (u.banned IS NOT TRUE OR (u.ban_expires IS NOT NULL AND u.ban_expires < now()))
-- the pro must be willing to travel to this job, index-accelerated
AND ST_DWithin(p.base_location, j.location, p.service_radius_m)
-- never show a card the client has already decided on
@@ -173,7 +173,7 @@ export async function getDeckCount(db: Db, jobId: string): Promise<number> {
WHERE j.id = ${jobId}
AND p.verification_status = 'verified'
AND p.is_accepting_jobs = true
AND u.banned_at IS NULL
AND (u.banned IS NOT TRUE OR (u.ban_expires IS NOT NULL AND u.ban_expires < now()))
AND ST_DWithin(p.base_location, j.location, p.service_radius_m)
AND NOT EXISTS (SELECT 1 FROM swipes s WHERE s.job_id = j.id AND s.pro_id = p.user_id)
AND NOT EXISTS (SELECT 1 FROM requests r WHERE r.job_id = j.id AND r.pro_id = p.user_id)
+110 -47
View File
@@ -1,83 +1,146 @@
import { relations } from 'drizzle-orm';
import { boolean, index, integer, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core';
import {
boolean,
index,
pgTable,
text,
timestamp,
unique,
uuid,
} from 'drizzle-orm/pg-core';
import { userRole } from './enums';
/** Auth.js v5 compatible tables, plus the fields the marketplace needs. */
/**
* Tables owned by better-auth, plus the marketplace columns we add on top.
*
* The shapes here are not a matter of taste — they were derived from
* better-auth 1.7.1's own `getSchema()` output for our exact plugin set
* (phoneNumber + admin + bearer). Two of them are easy to get wrong:
*
* - `emailVerified` and `phoneVerified` are BOOLEAN, not timestamps.
* better-auth injects `emailVerified: false` on every insert, so a
* timestamptz column fails 100% of signups with "value.toISOString is not a
* function". Where we want to know *when*, we keep a separate *_at column.
* - `accounts.issuer` is required in 1.7.x.
*
* Table and column names are mapped back to our conventions in
* apps/web/src/lib/auth.ts via `modelName` / `fields`.
*/
export const users = pgTable(
'users',
{
id: uuid('id').primaryKey().defaultRandom(),
name: text('name'),
email: text('email').unique(),
emailVerified: timestamp('email_verified', { withTimezone: true }),
/** E.164. The identity that actually matters on both sides of a local marketplace. */
phone: text('phone').unique(),
phoneVerified: timestamp('phone_verified', { withTimezone: true }),
name: text('name').notNull(),
/**
* Required and unique by better-auth. Phone-first users get a synthetic
* address on a domain we control — ALWAYS gate outbound mail on
* `isSyntheticEmail()` from @linkder/shared. Pros must supply a real
* address during onboarding; clients may never have one.
*/
email: text('email').notNull().unique(),
emailVerified: boolean('email_verified').notNull().default(false),
/** E.164. The identity that actually matters on both sides of the market. */
phoneNumber: text('phone').unique(),
phoneNumberVerified: boolean('phone_verified').default(false),
/** When the number was confirmed, for support and dispute history. */
phoneVerifiedAt: timestamp('phone_verified_at', { withTimezone: true }),
image: text('image'),
role: userRole('role').notNull().default('client'),
/** Set when an admin bans someone; checked in the auth callback. */
bannedAt: timestamp('banned_at', { withTimezone: true }),
/** Ban state, owned by better-auth's admin plugin. One source of truth. */
banned: boolean('banned').default(false),
banReason: text('ban_reason'),
banExpires: timestamp('ban_expires', { withTimezone: true }),
/** Deck ranking penalises dormant pros, so this has to be maintained. */
lastActiveAt: timestamp('last_active_at', { withTimezone: true }).defaultNow(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index('users_role_idx').on(t.role), index('users_phone_idx').on(t.phone)],
(t) => [index('users_role_idx').on(t.role), index('users_phone_idx').on(t.phoneNumber)],
);
export const sessions = pgTable(
'sessions',
{
id: uuid('id').primaryKey().defaultRandom(),
/** The bearer credential itself. Treat as a secret. */
token: text('token').notNull().unique(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
ipAddress: text('ip_address'),
userAgent: text('user_agent'),
/** Set when an admin is impersonating this user for support. */
impersonatedBy: uuid('impersonated_by').references(() => users.id, { onDelete: 'set null' }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index('sessions_user_idx').on(t.userId)],
);
export const accounts = pgTable(
'accounts',
{
id: uuid('id').primaryKey().defaultRandom(),
/** Required by better-auth 1.7.x. */
issuer: text('issuer').notNull(),
accountId: text('account_id').notNull(),
providerId: text('provider_id').notNull(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
type: text('type').notNull(),
provider: text('provider').notNull(),
providerAccountId: text('provider_account_id').notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: text('token_type'),
accessToken: text('access_token'),
refreshToken: text('refresh_token'),
idToken: text('id_token'),
accessTokenExpiresAt: timestamp('access_token_expires_at', { withTimezone: true }),
refreshTokenExpiresAt: timestamp('refresh_token_expires_at', { withTimezone: true }),
scope: text('scope'),
id_token: text('id_token'),
session_state: text('session_state'),
password: text('password'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.provider, t.providerAccountId] })],
(t) => [
unique('accounts_issuer_account_unique').on(t.issuer, t.accountId),
index('accounts_user_idx').on(t.userId),
],
);
export const sessions = pgTable('sessions', {
sessionToken: text('session_token').primaryKey(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expires: timestamp('expires', { withTimezone: true }).notNull(),
});
export const verificationTokens = pgTable(
'verification_tokens',
{
identifier: text('identifier').notNull(),
token: text('token').notNull(),
expires: timestamp('expires', { withTimezone: true }).notNull(),
},
(t) => [primaryKey({ columns: [t.identifier, t.token] })],
);
/** Short-lived SMS codes for phone login. Separate from Auth.js email tokens. */
export const phoneOtps = pgTable(
'phone_otps',
/**
* One-time codes and tokens, including phone OTPs.
*
* `value` holds the OTP as plaintext in the form "123456:0", the suffix being
* the attempt count. That is better-auth's design and we accept it — see the
* long note in apps/web/src/lib/auth.ts for the reasoning. It is a recorded
* decision, not an oversight.
*/
export const verifications = pgTable(
'verifications',
{
id: uuid('id').primaryKey().defaultRandom(),
phone: text('phone').notNull(),
codeHash: text('code_hash').notNull(),
attempts: integer('attempts').notNull().default(0),
consumed: boolean('consumed').notNull().default(false),
identifier: text('identifier').notNull(),
value: text('value').notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index('phone_otps_phone_idx').on(t.phone, t.expiresAt)],
(t) => [index('verifications_identifier_idx').on(t.identifier, t.expiresAt)],
);
export const usersRelations = relations(users, ({ many }) => ({
accounts: many(accounts),
sessions: many(sessions),
}));
export const accountsRelations = relations(accounts, ({ one }) => ({
user: one(users, { fields: [accounts.userId], references: [users.id] }),
}));
export const sessionsRelations = relations(sessions, ({ one }) => ({
user: one(users, { fields: [sessions.userId], references: [users.id] }),
}));
+11 -9
View File
@@ -107,7 +107,7 @@ async function main() {
matches, requests, swipes, jobs,
pro_availability, verification_sessions, credentials,
pro_media, pro_categories, pro_profiles,
sessions, accounts, phone_otps, users, categories
sessions, accounts, verifications, users, categories
RESTART IDENTITY CASCADE
`);
@@ -124,10 +124,11 @@ async function main() {
CLIENTS.map((name, i) => ({
name,
email: `client${i + 1}@linkder.test`,
phone: `+3460000${String(i + 1).padStart(4, '0')}`,
phoneNumber: `+3460000${String(i + 1).padStart(4, '0')}`,
role: 'client' as const,
emailVerified: new Date(),
phoneVerified: new Date(),
emailVerified: true,
phoneNumberVerified: true,
phoneVerifiedAt: new Date(),
})),
)
.returning();
@@ -136,9 +137,9 @@ async function main() {
await db.insert(schema.users).values({
name: 'Linkder Admin',
email: 'admin@linkder.test',
phone: '+34600009999',
phoneNumber: '+34600009999',
role: 'admin',
emailVerified: new Date(),
emailVerified: true,
});
const now = Date.now();
@@ -151,10 +152,11 @@ async function main() {
.values({
name: p.name,
email: `pro${i + 1}@linkder.test`,
phone: `+3461000${String(i + 1).padStart(4, '0')}`,
phoneNumber: `+3461000${String(i + 1).padStart(4, '0')}`,
role: 'pro' as const,
emailVerified: new Date(),
phoneVerified: new Date(),
emailVerified: true,
phoneNumberVerified: true,
phoneVerifiedAt: new Date(),
lastActiveAt: new Date(now - (i % 5) * 86_400_000),
})
.returning();