Add login y logout
This commit is contained in:
19
mvp/b2c/src/app/login/actions.ts
Normal file
19
mvp/b2c/src/app/login/actions.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
'use server';
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
import { getUserByEmail } from '@/db/auth-queries';
|
||||
import { verifyPassword } from '@/lib/auth/password';
|
||||
import { createSession } from '@/lib/auth/session';
|
||||
|
||||
export async function login(_prev: string | null, formData: FormData): Promise<string | null> {
|
||||
const email = String(formData.get('email') ?? '').trim().toLowerCase();
|
||||
const password = String(formData.get('password') ?? '');
|
||||
if (!email || !password) return 'Introduce email y contraseña.';
|
||||
|
||||
const user = await getUserByEmail(email);
|
||||
if (!user || user.status !== 'activo') return 'Credenciales incorrectas.';
|
||||
if (!(await verifyPassword(password, user.passwordHash))) return 'Credenciales incorrectas.';
|
||||
|
||||
await createSession(user.id);
|
||||
redirect(user.role === 'admin' ? '/admin' : '/panel');
|
||||
}
|
||||
27
mvp/b2c/src/app/login/page.tsx
Normal file
27
mvp/b2c/src/app/login/page.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useActionState } from 'react';
|
||||
import { login } from './actions';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [error, formAction, pending] = useActionState(login, null);
|
||||
return (
|
||||
<main className="min-h-screen flex items-center justify-center bg-gray-50 px-6">
|
||||
<form action={formAction} className="w-full max-w-sm bg-white border border-gray-200 rounded-xl p-8 flex flex-col gap-4">
|
||||
<h1 className="text-xl font-black tracking-tight text-black">Entra en tu panel</h1>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
<span className="font-medium text-gray-700">Email</span>
|
||||
<input name="email" type="email" required className="border border-gray-300 rounded-md px-3 py-2" />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
<span className="font-medium text-gray-700">Contraseña</span>
|
||||
<input name="password" type="password" required className="border border-gray-300 rounded-md px-3 py-2" />
|
||||
</label>
|
||||
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||
<button type="submit" disabled={pending} className="bg-black text-white rounded-md py-2 font-semibold disabled:opacity-60">
|
||||
{pending ? 'Entrando…' : 'Entrar'}
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
7
mvp/b2c/src/app/logout/route.ts
Normal file
7
mvp/b2c/src/app/logout/route.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { destroySession } from '@/lib/auth/session';
|
||||
|
||||
export async function POST() {
|
||||
await destroySession();
|
||||
redirect('/login');
|
||||
}
|
||||
Reference in New Issue
Block a user