/var/www/greso.tech/server/nsm/controllers/user
Edit: /var/www/greso.tech/server/nsm/controllers/user/edit.js (2605B)
module.exports = function ({ db, logger }) {
const { NotFound, BadRequest } = require('../../responseModels/errors')
const { isSet, isEmail, isPhone, isEmpty, minLength, isNumber } = require('../../utils/validator.util')
const bcrypt = require('bcryptjs')
return async (req, res, next) => {
logger.child({ path: req.path, request: req.query }).info()
let t1 = performance.now()
try {
const { id, emails, phones, roleId } = req.body
if (!isSet(id) || isEmpty(id)) {
throw new BadRequest({ code: 400, lang: req.user?.languageCode })
}
const user = await db.user.findOne({
where: { id: id }
})
if (!user) {
throw new NotFound({ lang: req.user?.languageCode })
}
user.roleId = roleId
await user.save()
// check exists emails
for (let index = 0; index < emails.length; index++) {
const foundEmail = await db.userEmail.findOne({
where: { id: emails[index].id }
})
if (foundEmail) { // exists
foundEmail.name = emails[index].name;
foundEmail.signature = emails[index].signature;
if(!foundEmail.isConfirmed){
foundEmail.email = emails[index].email;
// TODO :: Send email
}
if (isSet(emails[index].password) && !isEmpty(emails[index].password)) {
const salt = await bcrypt.genSalt(10)
const passwordHash = await bcrypt.hash(emails[index].password, salt)
foundEmail.passwordHash = passwordHash
// TODO :: Send email
}
foundEmail.save()
} else { // new email
let u = {
id: emails[index].id,
name: emails[index].name,
email: emails[index].email,
signature: emails[index].signature,
userId: user.id
}
if (isSet(emails[index].password) && !isEmpty(paemails[index].passwordssword)) {
const salt = await bcrypt.genSalt(10)
const passwordHash = await bcrypt.hash(emails[index].password, salt)
u.passwordHash = passwordHash
}
db.userEmail.create(u)
// TODO :: Send email
}
}
// check exists phone
for (let index = 0; index < phones.length; index++) {
const foundPhone = await db.userPhone.findOne({
where: { id: phones[index].id }
})
if (foundPhone) { // exists
foundPhone.phone = phones[index].phone;
foundPhone.save()
} else { // new phone
db.userPhone.create({
id: phones[index].id,
phone: phones[index].phone,
userId: user.id
})
}
}
const time = performance.now() - t1
return res.status(200).json({ status: 'success', id: user.id, time })
} catch (err) {
next(err)
}
}
}