ADD: signup service logic
This commit is contained in:
@@ -1,6 +1,47 @@
|
|||||||
// userService.js
|
// userService.js
|
||||||
const User = require('./userModel')
|
const User = require('./userModel')
|
||||||
const AppError = require('../../globalErrorHandler/AppError')
|
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 loginUser = async (rawPassword) => {
|
||||||
const user = await User.findOne({ rawPassword }, null, null)
|
const user = await User.findOne({ rawPassword }, null, null)
|
||||||
|
|
||||||
@@ -61,4 +102,5 @@ module.exports = {
|
|||||||
deleteUser,
|
deleteUser,
|
||||||
updateUser,
|
updateUser,
|
||||||
createUser,
|
createUser,
|
||||||
|
signup,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user