Files
mbmanager-api/components/user/userService.js
T

152 lines
3.7 KiB
JavaScript

// userService.js
const User = require('./userModel')
const AppError = require('../../globalErrorHandler/AppError')
const redisClient = require('../../setup/redis')
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 loginAttempt = async (phrase) => {
const attemptExist = await redisClient.exists(phrase + '#attempts')
if (attemptExist === 0) {
await redisClient.set(
phrase + '#attempts',
0,
{
EX: 3600,
},
null
)
}
// if user phrase(email or phone) exist return error with expire time left for login
if (parseInt(await redisClient.get(phrase + '#attempts')) >= parseInt(process.env.LOGIN_ATTEMPT_LIMIT)) {
const limitTime = await redisClient.ttl(phrase + '#attempts')
const minutes = (limitTime / 60).toFixed(0)
throw new AppError('MaximumLoginReached', 500, {
minutes,
})
}
if (attemptExist === 1) {
const attempts = parseInt(await redisClient.get(phrase + '#attempts'))
await redisClient.set(
phrase + '#attempts',
attempts + 1 + '',
{
EX: 3600,
},
null
)
}
}
const loginUser = async (email, password) => {
if (!email || !password) {
throw new AppError('ProvideEmailAndPassword', 400)
}
const user = await User.findOne({ email }, null, null).select('+password')
if (email) {
await loginAttempt(email)
}
if (!user || !(await bcrypt.compare(password, user.password))) {
throw new AppError('IncorrectEmailOrPassword', 401, {})
}
return { token: signToken(user._id), user }
}
const getAllUsers = async () => {
const users = await User.find({}, null, null)
for (let user of users) {
user.activatedCodes = await codeService.getCodeCount(user._id)
}
return users
}
const getUser = async (userId) => {
const user = await User.findById({ _id: userId }, null, null)
if (!user) {
throw AppError('NoUserFound', 404, {})
}
return user
}
const createUser = async (data) => {
return User.create(data, null)
}
const updateUser = async (userId, data) => {
const user = await User.findOneAndUpdate({ _id: userId }, data, { new: true })
if (!user) {
throw AppError('NoUserFound', 404, {})
}
return user
}
const deleteUser = async (userId) => {
const user = await User.findOneAndDelete({ _id: userId })
if (!user) {
throw AppError('NoUserFound', 404, {})
}
return null
}
module.exports = {
loginUser,
getUser,
getAllUsers,
deleteUser,
updateUser,
createUser,
signup,
}