65 lines
1.4 KiB
TypeScript
65 lines
1.4 KiB
TypeScript
|
|
// lib/auth/credentials.ts
|
||
|
|
import bcrypt from "bcryptjs"
|
||
|
|
import { prisma } from "@/lib/prisma"
|
||
|
|
|
||
|
|
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) {
|
||
|
|
// Verificar se usuário já existe
|
||
|
|
const existing = await prisma.user.findUnique({ where: { email } })
|
||
|
|
if (existing) {
|
||
|
|
throw new Error("Email já cadastrado")
|
||
|
|
}
|
||
|
|
|
||
|
|
// Hash da senha
|
||
|
|
const hashedPassword = await hashPassword(password)
|
||
|
|
|
||
|
|
// Criar usuário
|
||
|
|
const user = await prisma.user.create({
|
||
|
|
data: {
|
||
|
|
email,
|
||
|
|
password: hashedPassword,
|
||
|
|
name,
|
||
|
|
role: "EMPLOYEE"
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
return user
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function authenticateUser(email: string, password: string) {
|
||
|
|
// Buscar usuário
|
||
|
|
const user = await prisma.user.findUnique({ where: { email } })
|
||
|
|
|
||
|
|
if (!user || !user.password) {
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
|
||
|
|
// Verificar senha
|
||
|
|
const isValid = await verifyPassword(password, user.password)
|
||
|
|
|
||
|
|
if (!isValid) {
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
|
||
|
|
// Atualizar último login
|
||
|
|
await prisma.user.update({
|
||
|
|
where: { id: user.id },
|
||
|
|
data: { lastLoginAt: new Date() }
|
||
|
|
})
|
||
|
|
|
||
|
|
return {
|
||
|
|
id: user.id,
|
||
|
|
email: user.email,
|
||
|
|
name: user.name,
|
||
|
|
role: user.role
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|