/var/www/greso.tech/server/nsm/controllers/user
Edit: /var/www/greso.tech/server/nsm/controllers/user/create.js (2680B)
module.exports = function ({ db, logger }) {
const { NotFound, BadRequest } = require('../../responseModels/errors')
const { isSet, isEmail, isPhone, isEmpty, minLength, isNumber, isArray } = require('../../utils/validator.util')
const bcrypt = require('bcryptjs')
return async (req, res, next) => {
logger.child({ path: req.path, request: req.query }).info()
let transaction = await db.sequelize.transaction()
try {
let t1 = performance.now()
const {emails, phones, roleId, companyId } = req.body
if (!isSet(emails) || !isArray(emails) || emails.length == 0) {
throw new BadRequest({
code: 1003,
lang: req.user?.languageCode
})
}
if (!isSet(roleId) || isEmpty(roleId) || !minLength(roleId, 32)) {
throw new BadRequest({
code: 2001,
lang: req.user?.languageCode
})
}
// check exists emails
for (let index = 0; index < emails.length; index++) {
const foundEmail = await db.userEmail.findOne({
where: { email: emails[index].email }
})
if (foundEmail) {
throw new BadRequest({
code: 1008,
lang: req.user?.languageCode
})
}
}
const user = await db.user.create({
roleId,
})
var first_email = '';
// add emails
for (let index = 0; index < emails.length; index++) {
first_email = emails[index].email
let u = {
id: emails[index].id,
name: emails[index].name,
email: emails[index].email,
userId: user.id
}
if (isSet(emails[index].password) && !isEmpty(emails[index].password)) {
const salt = await bcrypt.genSalt(10)
const passwordHash = await bcrypt.hash(emails[index].password, salt)
u.passwordHash = passwordHash
}
await db.userEmail.create(u)
}
// add phones
if (isSet(phones) && isArray(phones) && phones.length > 0) {
for (let index = 0; index < phones.length; index++) {
await db.userPhone.create({
id: phones[index].id,
phone: phones[index].phone,
userId: user.id
})
}
}
transaction.commit()
transaction = null
if(isSet(companyId)&&!isEmpty(companyId)){
// const company = await db.company.findOne({
// where: { id: companyId }
// })
// if (!company) {
// throw new NotFound({ lang: req.user?.languageCode })
// }
await db.companyClients.create({
userId: user.id,
companyId,
discount: 0
})
SERVICES.MailService.SendNewUser(user.id,companyId)
}
const time = performance.now() - t1
return res.status(200).json({ status: 'success', id: user.id, time })
} catch (err) {
transaction?.rollback()
next(err)
}
}
}