forked from noxious/server
59 lines
1.2 KiB
TypeScript
59 lines
1.2 KiB
TypeScript
import bcrypt from 'bcryptjs'
|
|
import UserRepository from '../repositories/userRepository'
|
|
import prisma from '../utilities/prisma'
|
|
import { User } from '@prisma/client'
|
|
|
|
/**
|
|
* User service
|
|
* Handles user login and registration
|
|
* @class UserService
|
|
*/
|
|
class UserService {
|
|
/**
|
|
* Login user
|
|
* @param username
|
|
* @param password
|
|
*/
|
|
async login(username: string, password: string): Promise<boolean | User> {
|
|
const user = await UserRepository.getByUsername(username)
|
|
if (!user) {
|
|
return false
|
|
}
|
|
|
|
const passwordMatch = await bcrypt.compare(password, user.password)
|
|
if (!passwordMatch) {
|
|
return false
|
|
}
|
|
|
|
return user
|
|
}
|
|
|
|
/**
|
|
* Register user
|
|
* @param username
|
|
* @param password
|
|
*/
|
|
async register(username: string, email: string, password: string): Promise<boolean | User> {
|
|
const user = await UserRepository.getByUsername(username)
|
|
if (user) {
|
|
return false
|
|
}
|
|
|
|
const userByEmail = await UserRepository.getByEmail(email)
|
|
if (userByEmail) {
|
|
return false
|
|
}
|
|
|
|
const hashedPassword = await bcrypt.hash(password, 10)
|
|
return prisma.user.create({
|
|
data: {
|
|
username,
|
|
email,
|
|
password: hashedPassword
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
export default UserService
|