russ_react/server/services/authService.ts
2024-12-09 16:06:47 +03:00

62 lines
1.3 KiB
TypeScript

import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { User } from '../../src/types/auth';
const prisma = new PrismaClient();
export const authService = {
login: async (email: string, password: string) => {
const user = await prisma.user.findUnique({
where: { email },
select: {
id: true,
email: true,
password: true,
displayName: true,
permissions: true
}
});
if (!user || !await bcrypt.compare(password, user.password)) {
throw new Error('Invalid credentials');
}
const token = jwt.sign(
{ id: user.id },
process.env.JWT_SECRET || 'fallback-secret',
{ expiresIn: '24h' }
);
const { password: _, ...userWithoutPassword } = user;
return {
user: userWithoutPassword as User,
token
};
},
createUser: async (userData: {
email: string;
password: string;
displayName: string;
permissions: any;
}) => {
const hashedPassword = await bcrypt.hash(userData.password, 10);
const user = await prisma.user.create({
data: {
...userData,
password: hashedPassword
},
select: {
id: true,
email: true,
displayName: true,
permissions: true
}
});
return user as User;
}
};