From f68505eeb5f6ab36204e5fb5cf04dd3ea96f3277 Mon Sep 17 00:00:00 2001 From: MohammadHMazarei Date: Mon, 23 Dec 2024 22:18:10 +0330 Subject: [PATCH] ADD: signup service logic --- components/user/userService.js | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/components/user/userService.js b/components/user/userService.js index 09c3ee9..5ae580a 100644 --- a/components/user/userService.js +++ b/components/user/userService.js @@ -1,6 +1,47 @@ // userService.js const User = require('./userModel') const AppError = require('../../globalErrorHandler/AppError') +const jwt = require('jsonwebtoken') +const bcrypt = require('bcryptjs') +const maxAge = 60 * 60 * 24 * 90 + +const signToken = (id) => { + return jwt.sign({ id }, process.env.JWT_SECRET, { + expiresIn: maxAge, + }) +} + +const signup = async (name, email, password, passwordConfirm) => { + let userExist = await User.findOne({ email }, null, null) + + if (userExist) { + throw new AppError('UserAlreadyExist', 500, {}) + } + + if (password != passwordConfirm) throw new AppError('PasswordIncorrect', 401, {}) + + const hashedPassword = bcrypt.hashSync(password, 10) + + const user = await createUser({ + name, + email, + password: hashedPassword, + passwordConfirm: undefined, + }) + + const token = signToken(user._id) + const cookieOptions = { + expires: new Date(Date.now() + maxAge * 24 * 60 * 60 * 1000), + httpOnly: true, + } + + if (process.env.NODE_ENV === 'production') cookieOptions.secure = true + + // set user password to undefined before sending data + user.password = undefined + return { token, user, cookieOptions } +} + const loginUser = async (rawPassword) => { const user = await User.findOne({ rawPassword }, null, null) @@ -61,4 +102,5 @@ module.exports = { deleteUser, updateUser, createUser, + signup, }