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:
2026-05-30 11:54:38 +01:00
parent bed5419409
commit 1bc837e606
25 changed files with 1119 additions and 80 deletions
@@ -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 })}
/>
);
}
+8 -1
View File
@@ -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 }) {
+21 -15
View File
@@ -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 {
+4 -3
View File
@@ -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.