feat(auth): wire getAdminUser() to Auth.js v5 Google sign-in
Deploy to route.crispygoat.com / deploy (push) Failing after 2s
Deploy to route.crispygoat.com / deploy (push) Failing after 2s
After a user signs in with Google, they land on /admin but see
'Your account does not have admin access' because getAdminUser()
only checked the legacy dev_session and rc_auth_uid cookies.
This completes the Auth.js path:
- New src/lib/db.ts: shared pg.Pool singleton (extracted from
src/lib/auth.ts). The single connection pool for the whole app
— server actions, API routes, and Auth.js all import from here.
- src/lib/auth.ts: imports the shared pool, signIn event now calls
the new upsert_admin_user_for_authjs RPC (idempotent) to
auto-create a platform_admin row on first sign-in.
- New supabase/migrations/209_authjs_auto_create_admin.sql:
- Defensive ALTER TABLE ADD COLUMN IF NOT EXISTS for
can_manage_settings (was likely dashboard-added, not in any
tracked migration)
- SECURITY DEFINER RPC upsert_admin_user_for_authjs(p_user_id UUID)
that inserts a platform_admin row with all permissions true
and ON CONFLICT (user_id) DO NOTHING
- NOTIFY pgrst to reload PostgREST schema cache
- src/lib/admin-permissions.ts: new Auth.js session check between
dev_session and rc_auth_uid. Uses auth() from @/lib/auth to
decrypt the JWT cookie server-side, then getAdminUserFromPool()
queries admin_users + admin_user_brands via the shared pool.
Legacy rc_auth_uid path unchanged (deferred).
- src/middleware.ts: recognizes Auth.js session cookies
(authjs.session-token and __Secure-authjs.session-token) at the
edge so signed-in users aren't bounced to /login.
Flow after this change:
Dev/demo: visit /admin → middleware auto-issues dev_session → in
Prod: click Google → Auth.js OAuth → signIn event creates
admin_users row → redirect to /admin → getAdminUser()
reads JWT, queries pool, returns platform_admin.
This commit is contained in:
+12
-59
@@ -1,11 +1,8 @@
|
||||
import NextAuth from "next-auth";
|
||||
import PostgresAdapter from "@auth/pg-adapter";
|
||||
import { Pool } from "pg";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import {
|
||||
authConfig,
|
||||
isDevLoginEnabled,
|
||||
} from "@/auth.config";
|
||||
import { pool } from "@/lib/db";
|
||||
import { authConfig, isDevLoginEnabled } from "@/auth.config";
|
||||
|
||||
/**
|
||||
* Build the dev Credentials provider. Lives here (Node-only) because
|
||||
@@ -39,51 +36,11 @@ function buildDevCredentialsProvider() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared Postgres pool for Auth.js. Reuses the same database the rest of
|
||||
* the app talks to (via `pg`). Lives behind a module-level singleton so
|
||||
* Next.js hot reload doesn't open a new pool on every request.
|
||||
*
|
||||
* Note: in production, `DATABASE_URL` should be the only DB env var. The
|
||||
* Supabase project URL / service role key are no longer required for auth
|
||||
* (they are still used elsewhere until the rest of the app is migrated off
|
||||
* the @supabase client — see CLAUDE.md).
|
||||
*/
|
||||
const globalForPool = globalThis as unknown as { __pgPool?: Pool };
|
||||
|
||||
function getPool(): Pool {
|
||||
if (globalForPool.__pgPool) return globalForPool.__pgPool;
|
||||
|
||||
const connectionString =
|
||||
process.env.DATABASE_URL ??
|
||||
process.env.SUPABASE_DB_URL ??
|
||||
process.env.POSTGRES_URL;
|
||||
|
||||
if (!connectionString) {
|
||||
// Don't throw at module load — let route handlers return a clean 500
|
||||
// if env is missing. The smoke test instructions tell the user to
|
||||
// set DATABASE_URL.
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
"[auth] No DATABASE_URL / SUPABASE_DB_URL / POSTGRES_URL set — Auth.js database adapter will not be wired up."
|
||||
);
|
||||
}
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString,
|
||||
// Reasonable defaults; override via connection string if you need more
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30_000,
|
||||
});
|
||||
globalForPool.__pgPool = pool;
|
||||
return pool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Final server-side Auth.js config.
|
||||
*
|
||||
* Builds on `authConfig` (edge-safe) and layers on:
|
||||
* 1. The Postgres database adapter
|
||||
* 1. The Postgres database adapter (uses the shared `pool` from @/lib/db)
|
||||
* 2. The dev Credentials provider (only in development)
|
||||
*
|
||||
* Note: when using a database adapter the session strategy is fixed to
|
||||
@@ -96,7 +53,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
// must use JWT. The Postgres adapter is still wired up so that user
|
||||
// records are created/updated when a new OAuth sign-in happens — but
|
||||
// the session itself is stored in the cookie as an encrypted JWT.
|
||||
adapter: PostgresAdapter(getPool()),
|
||||
adapter: PostgresAdapter(pool),
|
||||
// `session.strategy` is inherited from `authConfig` ("jwt")
|
||||
providers: [
|
||||
// Re-declare the providers from authConfig and append the dev
|
||||
@@ -108,27 +65,23 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
events: {
|
||||
/**
|
||||
* First-time sign-in: auto-create a `platform_admin` row in
|
||||
* `admin_users` keyed to this auth.js user id, mirroring the legacy
|
||||
* `rc_auth_uid` flow. This is the seam between the new auth layer
|
||||
* and the existing admin authorization model.
|
||||
* `admin_users` keyed to this Auth.js user id. The RPC is
|
||||
* idempotent (ON CONFLICT DO NOTHING) so repeat sign-ins are no-ops.
|
||||
*
|
||||
* This is the seam between the new Auth.js auth layer and the
|
||||
* existing admin authorization model. After this fires, the user
|
||||
* is recognized by `getAdminUser()` in `src/lib/admin-permissions.ts`.
|
||||
*/
|
||||
async signIn({ user }) {
|
||||
try {
|
||||
const pool = getPool();
|
||||
const userId = user.id;
|
||||
if (!userId) return;
|
||||
// Fire and forget — don't block sign-in on a missing admin_users row.
|
||||
await pool.query(
|
||||
`SELECT id FROM admin_users WHERE user_id = $1 LIMIT 1`,
|
||||
"SELECT * FROM upsert_admin_user_for_authjs($1)",
|
||||
[userId]
|
||||
);
|
||||
// Note: we don't auto-create here; the existing `getAdminUser()`
|
||||
// in `src/lib/admin-permissions.ts` is the source of truth for
|
||||
// role lookups and is unchanged. After this migration the user
|
||||
// is authenticated; the existing `dev_session` demo path still
|
||||
// works for the smoke test.
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line no-console
|
||||
// Don't block sign-in on a missing admin_users row.
|
||||
console.warn("[auth] signIn event error (non-fatal):", e);
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user