forked from noxious/server
110 lines
2.6 KiB
TypeScript
110 lines
2.6 KiB
TypeScript
import bcrypt from 'bcryptjs'
|
|
import UserRepository from '../repositories/userRepository'
|
|
import prisma from '../utilities/prisma'
|
|
import { User, PasswordResetToken } from '@prisma/client'
|
|
import config from '../utilities/config'
|
|
import NodeMailer from 'nodemailer'
|
|
|
|
/**
|
|
* 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
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Reset password
|
|
* @param email
|
|
*/
|
|
async resetPassword(email: string): Promise<boolean | undefined> {
|
|
|
|
const user = await UserRepository.getByEmail(email)
|
|
if ( !user ) return
|
|
const token = await bcrypt.genSalt(10)
|
|
|
|
//Check if password reset has been requested recently
|
|
if (await prisma.passwordResetToken.findFirst({
|
|
where: {
|
|
userId: user.id
|
|
},
|
|
})) return
|
|
|
|
prisma.passwordResetToken.create({
|
|
data: {
|
|
userId: user.id,
|
|
token: token,
|
|
}
|
|
});
|
|
|
|
const transporter = NodeMailer.createTransport({
|
|
host: config.SMTP_HOST,
|
|
port: config.SMTP_PORT,
|
|
secure: false,
|
|
auth: {
|
|
user: config.SMTP_USER,
|
|
pass: config.SMTP_PASSWORD,
|
|
},
|
|
});
|
|
|
|
const info = await transporter.sendMail({
|
|
from: config.SMTP_USER,
|
|
to: email,
|
|
subject: "Reset your password",
|
|
text: "A password reset has been requested, reset your password here: " + config.CLIENT_URL + "/" + token, // Plain text body
|
|
html: "<p>A password reset has been requested, reset your password here: " + config.CLIENT_URL + "/" + token + "</p>", // Html body
|
|
});
|
|
console.log("Message sent: %s", info.messageId);
|
|
|
|
|
|
if (info) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
export default UserService
|