habits.andr33v.ru/server/api/auth/login.post.ts

57 lines
1.4 KiB
TypeScript

import { PrismaClient } from '@prisma/client';
import { verifyPassword } from '../utils/password';
import { useSession } from 'h3';
const prisma = new PrismaClient();
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const { email, password } = body;
// 1. Validate input
if (!email || !password) {
throw createError({
statusCode: 400,
statusMessage: 'Email and password are required',
});
}
// 2. Find the user
const user = await prisma.user.findUnique({
where: { email },
});
if (!user) {
throw createError({
statusCode: 401, // Unauthorized
statusMessage: 'Invalid credentials',
});
}
// 3. Verify the password
const isPasswordValid = await verifyPassword(password, user.password);
if (!isPasswordValid) {
throw createError({
statusCode: 401,
statusMessage: 'Invalid credentials',
});
}
// 4. Create and update the session
const session = await useSession(event, {
password: process.env.SESSION_PASSWORD || 'your-super-secret-32-character-password', // Should be in .env
maxAge: 60 * 60 * 24 * 7, // 1 week
});
await session.update({
user: {
id: user.id,
email: user.email,
}
});
// 5. Return user data
const { password: _password, ...userWithoutPassword } = user;
return { user: userWithoutPassword };
});