2026-01-20 17:20:13 +01:00
|
|
|
import bcrypt from 'bcryptjs';
|
|
|
|
|
import { prisma } from './prisma';
|
|
|
|
|
import { cookies } from 'next/headers';
|
|
|
|
|
|
|
|
|
|
export async function hashPassword(password: string): Promise<string> {
|
|
|
|
|
return bcrypt.hash(password, 10);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function verifyPassword(password: string, hashedPassword: string): Promise<boolean> {
|
|
|
|
|
return bcrypt.compare(password, hashedPassword);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function createUser(email: string, password: string, name?: string) {
|
|
|
|
|
const hashedPassword = await hashPassword(password);
|
|
|
|
|
return prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
email,
|
|
|
|
|
password: hashedPassword,
|
|
|
|
|
name,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getUserByEmail(email: string) {
|
|
|
|
|
return prisma.user.findUnique({
|
|
|
|
|
where: { email },
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function login(email: string, password: string) {
|
|
|
|
|
const user = await getUserByEmail(email);
|
|
|
|
|
if (!user) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isValid = await verifyPassword(password, user.password);
|
|
|
|
|
if (!isValid) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getCurrentUser() {
|
|
|
|
|
const cookieStore = await cookies();
|
|
|
|
|
const userId = cookieStore.get('user_id')?.value;
|
|
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return prisma.user.findUnique({
|
|
|
|
|
where: { id: userId },
|
|
|
|
|
select: {
|
|
|
|
|
id: true,
|
|
|
|
|
email: true,
|
|
|
|
|
name: true,
|
2026-02-08 14:21:07 +01:00
|
|
|
photoUrl: true,
|
2026-01-20 17:20:13 +01:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function setSession(userId: string) {
|
|
|
|
|
const cookieStore = await cookies();
|
|
|
|
|
cookieStore.set('user_id', userId, {
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
secure: process.env.NODE_ENV === 'production',
|
|
|
|
|
sameSite: 'lax',
|
|
|
|
|
maxAge: 60 * 60 * 24 * 7, // 7 days
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function clearSession() {
|
|
|
|
|
const cookieStore = await cookies();
|
|
|
|
|
cookieStore.delete('user_id');
|
|
|
|
|
}
|