work-timer/app/models/user.server.ts

65 lines
1.4 KiB
TypeScript
Raw Normal View History

import type { Password, User } from '@prisma/client';
import bcrypt from 'bcryptjs';
2023-02-11 03:14:14 +01:00
import { prisma } from '~/db.server';
2023-02-11 03:14:14 +01:00
export type { User } from '@prisma/client';
2023-02-11 03:14:14 +01:00
export async function getUserById(id: User['id']) {
2023-02-11 03:14:14 +01:00
return prisma.user.findUnique({ where: { id } });
}
export async function getUserByEmail(email: User['email']) {
2023-02-11 03:14:14 +01:00
return prisma.user.findUnique({ where: { email } });
}
export async function createUser(email: User['email'], password: string) {
2023-02-11 03:14:14 +01:00
const hashedPassword = await bcrypt.hash(password, 10);
return prisma.user.create({
data: {
email,
password: {
create: {
hash: hashedPassword
}
}
}
2023-02-11 03:14:14 +01:00
});
}
export async function deleteUserByEmail(email: User['email']) {
2023-02-11 03:14:14 +01:00
return prisma.user.delete({ where: { email } });
}
export async function verifyLogin(
email: User['email'],
password: Password['hash']
2023-02-11 03:14:14 +01:00
) {
const userWithPassword = await prisma.user.findUnique({
where: { email },
include: {
password: true
}
2023-02-11 03:14:14 +01:00
});
console.log(userWithPassword);
2023-02-11 03:14:14 +01:00
if (!userWithPassword || !userWithPassword.password) {
return null;
}
const isValid = await bcrypt.compare(
password,
userWithPassword.password.hash
);
console.log(isValid, password, userWithPassword.password.hash);
2023-02-11 03:14:14 +01:00
if (!isValid) {
return null;
}
const { password: _password, ...userWithoutPassword } = userWithPassword;
return userWithoutPassword;
}