MAI CALL - auth v0.2
# O que mudou 1 Schema: failedAttempts + lockedUntil em User; migration auth_v0_2_lockout aplicada; crypto.ts com hashSecret/verifySecret (Node scrypt nativo, zero deps) 2 packages/api/src/auth.ts — authenticateCredential com lockout de 5 tentativas 3 Seed reescrito: admin hashed admin1234, operadores hashed 1111/2222/3333 4 Porta das traseiras fechada: AUTH_DEV_AUTOLOGIN ignorado quando NODE_ENV=production, em ambas as apps 5 operator-pwa: Credentials provider usa PIN + allowedRoles:['OPERATOR']; cookies fieldops-op.* 6 Picker em 2 estados: lista → teclado PIN (botões grandes, dots de progresso, mensagem de erro sem dar pistas) 7 admin-web: Auth.js completo (auth.config, auth.ts, route handler, middleware, /login page, AUTH_SECRET no env) com cookies fieldops-admin.* 8 scripts/auth-smoke.ts (11/11 ✓); .env.example e README atualizados
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
import { handlers } from '@/lib/auth';
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
export const runtime = 'nodejs';
|
||||
@@ -0,0 +1,79 @@
|
||||
'use client';
|
||||
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { signIn } from 'next-auth/react';
|
||||
|
||||
export function LoginForm() {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const form = e.currentTarget;
|
||||
const email = (form.elements.namedItem('email') as HTMLInputElement).value;
|
||||
const password = (form.elements.namedItem('password') as HTMLInputElement).value;
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await signIn('credentials', { email, password, redirect: false });
|
||||
if (result?.error) {
|
||||
setError('Email ou password incorretos. Tente novamente.');
|
||||
} else {
|
||||
router.push('/maintenance');
|
||||
router.refresh();
|
||||
}
|
||||
} catch {
|
||||
setError('Erro inesperado. Tente novamente.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label htmlFor="email" className="text-sm font-medium">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
disabled={busy}
|
||||
className="rounded-lg border border-border bg-background px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
|
||||
placeholder="admin@demo.local"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label htmlFor="password" className="text-sm font-medium">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="current-password"
|
||||
disabled={busy}
|
||||
className="rounded-lg border border-border bg-background px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
className="mt-2 w-full rounded-xl bg-primary py-3 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 active:scale-[0.98] disabled:opacity-50"
|
||||
>
|
||||
{busy ? 'A entrar…' : 'Entrar'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { LoginForm } from './login-form';
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen max-w-sm flex-col justify-center gap-8 p-6">
|
||||
<header className="text-center">
|
||||
<h1 className="text-2xl font-bold tracking-tight">FieldOps</h1>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Acesso à consola de manutenção
|
||||
</p>
|
||||
</header>
|
||||
<LoginForm />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
||||
export const env = createEnv({
|
||||
server: {
|
||||
DATABASE_URL: z.string().url(),
|
||||
AUTH_SECRET: z.string().min(1, 'AUTH_SECRET is required'),
|
||||
AUTH_DEV_AUTOLOGIN: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -17,6 +18,7 @@ export const env = createEnv({
|
||||
},
|
||||
runtimeEnv: {
|
||||
DATABASE_URL: process.env.DATABASE_URL,
|
||||
AUTH_SECRET: process.env.AUTH_SECRET,
|
||||
AUTH_DEV_AUTOLOGIN: process.env.AUTH_DEV_AUTOLOGIN,
|
||||
LOG_LEVEL: process.env.LOG_LEVEL,
|
||||
NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { NextAuthConfig } from 'next-auth';
|
||||
|
||||
/**
|
||||
* Edge-safe portion of the Auth.js config for admin-web.
|
||||
* Imported by middleware — no Credentials provider, no Prisma.
|
||||
*/
|
||||
export const authConfig = {
|
||||
trustHost: true,
|
||||
session: { strategy: 'jwt' },
|
||||
pages: {
|
||||
signIn: '/login',
|
||||
},
|
||||
// Distinct cookie names prevent session collision with operator-pwa on localhost
|
||||
// (cookies are not isolated by port — only by name and domain).
|
||||
cookies: {
|
||||
sessionToken: { name: 'fieldops-admin.session-token' },
|
||||
callbackUrl: { name: 'fieldops-admin.callback-url' },
|
||||
csrfToken: { name: 'fieldops-admin.csrf-token' },
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const u = user as any;
|
||||
token.id = u.id;
|
||||
token.role = u.role;
|
||||
token.tenantId = u.tenantId;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (token && session.user) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(session.user as any).id = token.id;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(session.user as any).role = token.role;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(session.user as any).tenantId = token.tenantId;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
providers: [],
|
||||
} satisfies NextAuthConfig;
|
||||
+65
-11
@@ -1,18 +1,72 @@
|
||||
import NextAuth from 'next-auth';
|
||||
import Credentials from 'next-auth/providers/credentials';
|
||||
import { prisma } from '@repo/db';
|
||||
import { authenticateCredential } from '@repo/api';
|
||||
import type { SessionUser } from '@repo/api';
|
||||
import { authConfig } from './auth.config';
|
||||
|
||||
// v0.1 admin-web auth: AUTH_DEV_AUTOLOGIN=true → always admin@demo.local.
|
||||
// No session/cookie mechanism needed for the demo phase.
|
||||
const AUTH_SECRET = process.env['AUTH_SECRET'];
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
...authConfig,
|
||||
secret: AUTH_SECRET,
|
||||
providers: [
|
||||
Credentials({
|
||||
name: 'Email + password',
|
||||
credentials: {
|
||||
email: { label: 'Email', type: 'email' },
|
||||
password: { label: 'Password', type: 'password' },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const email = credentials?.email;
|
||||
const password = credentials?.password;
|
||||
if (typeof email !== 'string' || typeof password !== 'string') return null;
|
||||
const u = await authenticateCredential({
|
||||
email,
|
||||
secret: password,
|
||||
allowedRoles: ['ADMIN', 'SUPERVISOR'],
|
||||
});
|
||||
if (!u) return null;
|
||||
return {
|
||||
id: u.id,
|
||||
email: u.email,
|
||||
name: u.email,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: u.role as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
tenantId: u.tenantId as any,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* Resolve the current user for server-side code (RSC, route handlers, tRPC).
|
||||
* Falls back to dev autologin only outside production.
|
||||
*/
|
||||
export async function resolveUser(): Promise<SessionUser | null> {
|
||||
if (process.env['AUTH_DEV_AUTOLOGIN'] !== 'true') return null;
|
||||
const session = await auth();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const u = session?.user as any;
|
||||
if (u?.id && u?.tenantId) {
|
||||
return { id: u.id, email: u.email, role: u.role, tenantId: u.tenantId };
|
||||
}
|
||||
|
||||
const admin = await prisma.user.findFirst({ where: { email: 'admin@demo.local' } });
|
||||
if (!admin) return null;
|
||||
const autologinAllowed =
|
||||
process.env['AUTH_DEV_AUTOLOGIN'] === 'true' && process.env.NODE_ENV !== 'production';
|
||||
if (autologinAllowed) {
|
||||
const admin = await prisma.user.findFirst({ where: { email: 'admin@demo.local' } });
|
||||
if (admin) {
|
||||
return {
|
||||
id: admin.id,
|
||||
email: admin.email,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: admin.role as any,
|
||||
tenantId: admin.tenantId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: admin.id,
|
||||
email: admin.email,
|
||||
role: admin.role as 'ADMIN',
|
||||
tenantId: admin.tenantId,
|
||||
};
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import NextAuth from 'next-auth';
|
||||
import { authConfig } from './lib/auth.config';
|
||||
|
||||
const { auth } = NextAuth(authConfig);
|
||||
|
||||
export default auth((req) => {
|
||||
const isLoggedIn = !!req.auth?.user;
|
||||
const isAutologin =
|
||||
process.env['AUTH_DEV_AUTOLOGIN'] === 'true' && process.env.NODE_ENV !== 'production';
|
||||
const { pathname } = req.nextUrl;
|
||||
|
||||
if (pathname === '/login') {
|
||||
if (isLoggedIn) return Response.redirect(new URL('/maintenance', req.url));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isLoggedIn && !isAutologin) {
|
||||
return Response.redirect(new URL('/login', req.url));
|
||||
}
|
||||
});
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
'/((?!api/auth|api/trpc|_next/static|_next/image|favicon.ico).*)',
|
||||
],
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { NextConfig } from 'next';
|
||||
import './env'; // Validate env vars at build time
|
||||
|
||||
const config: NextConfig = {
|
||||
transpilePackages: ['@repo/db', '@repo/api', '@repo/ui', '@repo/storage'],
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"@trpc/server": "^11.0.0",
|
||||
"lucide-react": "^0.469.0",
|
||||
"next": "15.3.9",
|
||||
"next-auth": "5.0.0-beta.25",
|
||||
"pino": "^9.5.0",
|
||||
"pino-pretty": "^11.3.0",
|
||||
"react": "^19.0.0",
|
||||
|
||||
@@ -3,35 +3,31 @@
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { signIn } from 'next-auth/react';
|
||||
import { ArrowLeft, Delete } from 'lucide-react';
|
||||
|
||||
interface Operator {
|
||||
id: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export function OperatorPicker({ operators }: { operators: Operator[] }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// ── State types ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function handleSelect(email: string) {
|
||||
setBusy(email);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await signIn('credentials', { email, redirect: false });
|
||||
if (result?.error) {
|
||||
setError(`Não foi possível entrar como ${email}`);
|
||||
} else {
|
||||
router.push('/');
|
||||
router.refresh();
|
||||
}
|
||||
} catch {
|
||||
setError('Erro inesperado. Tente novamente.');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
type PickerState =
|
||||
| { step: 'list' }
|
||||
| { step: 'pin'; operator: Operator };
|
||||
|
||||
const PIN_MIN = 4;
|
||||
const PIN_MAX = 6;
|
||||
|
||||
// ── Sub-components ───────────────────────────────────────────────────────────
|
||||
|
||||
function OperatorList({
|
||||
operators,
|
||||
onSelect,
|
||||
}: {
|
||||
operators: Operator[];
|
||||
onSelect: (op: Operator) => void;
|
||||
}) {
|
||||
if (operators.length === 0) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
@@ -39,20 +35,170 @@ export function OperatorPicker({ operators }: { operators: Operator[] }) {
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{operators.map((op) => (
|
||||
<button
|
||||
key={op.id}
|
||||
onClick={() => handleSelect(op.email)}
|
||||
disabled={busy !== null}
|
||||
className="w-full rounded-xl border border-border bg-card px-6 py-5 text-left text-base font-medium transition-colors hover:bg-accent active:scale-[0.98] disabled:opacity-50"
|
||||
onClick={() => onSelect(op)}
|
||||
className="w-full rounded-xl border border-border bg-card px-6 py-5 text-left text-base font-medium transition-colors hover:bg-accent active:scale-[0.98]"
|
||||
>
|
||||
{busy === op.email ? 'A entrar…' : op.email}
|
||||
{op.email}
|
||||
</button>
|
||||
))}
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PinPad({
|
||||
operator,
|
||||
onBack,
|
||||
}: {
|
||||
operator: Operator;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [digits, setDigits] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function press(d: string) {
|
||||
if (digits.length >= PIN_MAX) return;
|
||||
setDigits((prev) => prev + d);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
function erase() {
|
||||
setDigits((prev) => prev.slice(0, -1));
|
||||
setError(null);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (digits.length < PIN_MIN || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await signIn('credentials', {
|
||||
email: operator.email,
|
||||
pin: digits,
|
||||
redirect: false,
|
||||
});
|
||||
if (result?.error) {
|
||||
setDigits('');
|
||||
setError('PIN incorreto ou conta bloqueada. Tente novamente.');
|
||||
} else {
|
||||
router.push('/');
|
||||
router.refresh();
|
||||
}
|
||||
} catch {
|
||||
setDigits('');
|
||||
setError('Erro inesperado. Tente novamente.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', 'del'];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={onBack}
|
||||
disabled={busy}
|
||||
className="rounded-lg p-2 hover:bg-accent disabled:opacity-50"
|
||||
aria-label="Voltar"
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</button>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Operador selecionado</p>
|
||||
<p className="text-sm font-medium">{operator.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PIN dots */}
|
||||
<div className="flex justify-center gap-4">
|
||||
{Array.from({ length: PIN_MAX }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`h-4 w-4 rounded-full border-2 transition-colors ${
|
||||
i < digits.length
|
||||
? 'border-primary bg-primary'
|
||||
: 'border-muted-foreground bg-transparent'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<p className="text-center text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
|
||||
{/* Numpad */}
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{keys.map((key, idx) => {
|
||||
if (key === '') {
|
||||
return <div key={idx} />;
|
||||
}
|
||||
if (key === 'del') {
|
||||
return (
|
||||
<button
|
||||
key={idx}
|
||||
onClick={erase}
|
||||
disabled={busy || digits.length === 0}
|
||||
className="flex items-center justify-center rounded-2xl border border-border bg-card py-5 text-lg font-medium transition-colors hover:bg-accent active:scale-[0.97] disabled:opacity-40"
|
||||
aria-label="Apagar"
|
||||
>
|
||||
<Delete className="h-5 w-5" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button
|
||||
key={idx}
|
||||
onClick={() => press(key)}
|
||||
disabled={busy || digits.length >= PIN_MAX}
|
||||
className="rounded-2xl border border-border bg-card py-5 text-xl font-semibold transition-colors hover:bg-accent active:scale-[0.97] disabled:opacity-40"
|
||||
>
|
||||
{key}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
onClick={submit}
|
||||
disabled={digits.length < PIN_MIN || busy}
|
||||
className="w-full rounded-xl bg-primary py-4 text-base font-semibold text-primary-foreground transition-opacity hover:opacity-90 active:scale-[0.98] disabled:opacity-40"
|
||||
>
|
||||
{busy ? 'A entrar…' : 'Entrar'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function OperatorPicker({ operators }: { operators: Operator[] }) {
|
||||
const [state, setState] = useState<PickerState>({ step: 'list' });
|
||||
|
||||
if (state.step === 'pin') {
|
||||
return (
|
||||
<PinPad
|
||||
operator={state.operator}
|
||||
onBack={() => setState({ step: 'list' })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<OperatorList
|
||||
operators={operators}
|
||||
onSelect={(op) => setState({ step: 'pin', operator: op })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,14 @@ export const authConfig = {
|
||||
trustHost: true,
|
||||
session: { strategy: 'jwt' },
|
||||
pages: {
|
||||
// No login UI in this scaffold phase. See auth.ts for the placeholder.
|
||||
signIn: '/select-operator',
|
||||
},
|
||||
// Distinct cookie names prevent session collision when both apps run on localhost
|
||||
// (cookies are not isolated by port — only by name and domain).
|
||||
cookies: {
|
||||
sessionToken: { name: 'fieldops-op.session-token' },
|
||||
callbackUrl: { name: 'fieldops-op.callback-url' },
|
||||
csrfToken: { name: 'fieldops-op.csrf-token' },
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import NextAuth from 'next-auth';
|
||||
import Credentials from 'next-auth/providers/credentials';
|
||||
import { prisma } from '@repo/db';
|
||||
import type { SessionUser } from '@repo/api';
|
||||
import { authenticateCredential } from '@repo/api';
|
||||
import type { SessionUser } from '@repo/api'; // eslint-disable-line @typescript-eslint/no-unused-vars
|
||||
import { env } from '../env';
|
||||
import { authConfig } from './auth.config';
|
||||
|
||||
@@ -36,24 +37,29 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
secret: env.AUTH_SECRET,
|
||||
providers: [
|
||||
Credentials({
|
||||
name: 'Email (placeholder)',
|
||||
name: 'Operador (PIN)',
|
||||
credentials: {
|
||||
email: { label: 'Email', type: 'email' },
|
||||
email: { label: 'Email', type: 'text' },
|
||||
pin: { label: 'PIN', type: 'password' },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const email = credentials?.email;
|
||||
if (typeof email !== 'string' || !email) return null;
|
||||
const user = await prisma.user.findFirst({ where: { email } });
|
||||
if (!user) return null;
|
||||
// NO password verification — placeholder only.
|
||||
const pin = credentials?.pin;
|
||||
if (typeof email !== 'string' || typeof pin !== 'string') return null;
|
||||
const u = await authenticateCredential({
|
||||
email,
|
||||
secret: pin,
|
||||
allowedRoles: ['OPERATOR'],
|
||||
});
|
||||
if (!u) return null;
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.email,
|
||||
id: u.id,
|
||||
email: u.email,
|
||||
name: u.email,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: user.role as any,
|
||||
role: u.role as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
tenantId: user.tenantId as any,
|
||||
tenantId: u.tenantId as any,
|
||||
};
|
||||
},
|
||||
}),
|
||||
@@ -74,9 +80,9 @@ export async function resolveUser(): Promise<SessionUser | null> {
|
||||
return { id: u.id, email: u.email, role: u.role, tenantId: u.tenantId };
|
||||
}
|
||||
|
||||
if (env.AUTH_DEV_AUTOLOGIN) {
|
||||
// Dev back door. Production guards: env flag default is false; this branch
|
||||
// is also a no-op if the seed user doesn't exist.
|
||||
const autologinAllowed = env.AUTH_DEV_AUTOLOGIN && process.env.NODE_ENV !== 'production';
|
||||
if (autologinAllowed) {
|
||||
// Dev back door. Disabled in production even if the env flag is set.
|
||||
const admin = await prisma.user.findFirst({ where: { email: 'admin@demo.local' } });
|
||||
if (admin) {
|
||||
return {
|
||||
|
||||
@@ -9,9 +9,10 @@ const { auth } = NextAuth(authConfig);
|
||||
|
||||
export default auth((req) => {
|
||||
const isLoggedIn = !!req.auth?.user;
|
||||
// AUTH_DEV_AUTOLOGIN bypasses the picker redirect — resolveUser() handles
|
||||
// the autologin fallback server-side; the middleware just stays out of the way.
|
||||
const isAutologin = process.env['AUTH_DEV_AUTOLOGIN'] === 'true';
|
||||
// AUTH_DEV_AUTOLOGIN bypasses the picker redirect in dev only.
|
||||
// Ignored in production even when the flag is set.
|
||||
const isAutologin =
|
||||
process.env['AUTH_DEV_AUTOLOGIN'] === 'true' && process.env.NODE_ENV !== 'production';
|
||||
const { pathname } = req.nextUrl;
|
||||
|
||||
// On the picker itself: skip if already logged in.
|
||||
|
||||
Reference in New Issue
Block a user