Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const userValidator = require('../validators/userValidator');
- const logger = require('../utils/LoggerUtil');
- const router = require('express').Router();
- const CommonUtil = require('../utils/CommonUtil');
- const ErrorUtil = require('../utils/ErrorUtil');
- const {upload, checkPermissions} = require('../utils/MiddlewareUtil');
- const {Campaign, Platform, User} = require('../models').db;
- /**
- * Проверяет доступ к изменению пароля и в случае успеха возвращает инстанс модели User - пользователя по указанному хэшу
- *
- * @name getChangePassword-Access
- * @route {GET} /change-password-access
- * @memberof module:controller/user
- * @queryparam {string} hash - временный хэш для восстановления пароля
- */
- router.get('/change-password-access', userValidator.changePasswordAccess, (req, res, next) => {
- User.findOne({where: {verificationHash: {$eq: req.query.hash}}}).then(()=> {
- res.json({hash: req.query.hash});
- }).catch(next);
- });
- /**
- * Возвращает массив инстансов модели User
- *
- * @name getUsers
- * @route {GET} /
- * @memberof module:controller/user
- * @queryparam {string} searchString - строка для поиска по полям: fullName, username, email, phone, company, position
- * @queryparam {string} role - роль пользователя
- * @queryparam {string} roles - сериализованный массив ролей пользователя
- */
- router.get('/', [
- checkPermissions(),
- userValidator.getUsers
- ], (req, res, next) => {
- var whereParams = {
- where: {$or: [], $and: []},
- include: null,
- limit: 50,
- offset: 0
- };
- if (req.query.searchString) {
- whereParams.where.$or.push({fullName: {$iLike: '%' + req.query.searchString + '%'}});
- whereParams.where.$or.push({username: {$iLike: '%' + req.query.searchString + '%'}});
- whereParams.where.$or.push({email: {$iLike: '%' + req.query.searchString + '%'}});
- whereParams.where.$or.push({phone: {$iLike: '%' + req.query.searchString + '%'}});
- whereParams.where.$or.push({company: {$iLike: '%' + req.query.searchString + '%'}});
- whereParams.where.$or.push({position: {$iLike: '%' + req.query.searchString + '%'}});
- }
- if (req.query.role) {
- whereParams.where.$or.push({role: {$eq: req.query.role}});
- if (req.query.role === 'ofruser') {
- whereParams.include = Campaign;
- }
- if (req.query.role === 'publisher') {
- whereParams.include = Platform;
- }
- }
- if (req.query.roles) {
- var rolesArray = JSON.parse(req.query.roles);
- rolesArray.map((role)=> {
- whereParams.where.$or.push({role: {$eq: role}});
- });
- }
- if (req.query.pageNum > 1) {
- whereParams.offset = (parseInt(req.query.pageNum) - 1) * 50;
- }
- if (!whereParams.where.$or.length) {
- delete whereParams.where.$or;
- }
- if (!whereParams.where.$and.length) {
- delete whereParams.where.$and;
- }
- User.findAll(whereParams).then((users) => {
- res.json({users: users});
- }).catch(next);
- });
- /**
- * Возвращает инстанс модели User
- *
- * @name getUser
- * @route {GET} /:id
- * @memberof module:controller/user
- * @routeparam {int} id - id пользователя
- */
- router.get('/:id', userValidator.getUserById, (req, res, next) => {
- User.findOne({where: {id: {$eq: req.params.id}}}).then((user) => {
- res.json({user: user});
- }).catch(next);
- });
- /**
- * Создает и возвращает инстанс модели User
- *
- * @name createUser
- * @route {POST} /
- * @memberof module:controller/user
- * @bodyparam {string} username - username
- * @bodyparam {string} fullName - ФИО
- * @bodyparam {string} password - пароль
- * @bodyparam {string} email - адрес электронной почты
- * @bodyparam {string} phone - номер телефона
- * @bodyparam {string} company - название компании
- * @bodyparam {string} position - должность
- * @bodyparam {string} withdrawalLimit - значение ограничения на вывод средств
- * @bodyparam {string} role - роль
- */
- router.post('/', [
- upload(process.env.COMMON_STORAGE_PATH + '/avatars').single('avatar'),
- userValidator.createUser,
- checkPermissions()
- ], (req, res, next) => {
- var params = {
- username: req.body.username,
- fullName: req.body.fullName,
- password: CommonUtil.generatePasswordHash(req.body.password),
- email: req.body.email.toLowerCase(),
- phone: req.body.phone,
- company: req.body.company || '',
- position: req.body.position || '',
- withdrawalLimit: parseFloat(req.body.withdrawalLimit).toFixed(2) || 10000,
- role: req.body.role,
- isModerator: (req.body.isModerator && (req.body.role == 'admin' || req.body.role == 'publisher')),
- avatar: req.file ? req.file.filename : ''
- };
- var whereParams = {
- where: {
- $or: [
- {username: {$eq: req.body.username}},
- {email: {$eq: req.body.email.toLowerCase()}}
- ]
- }
- };
- User.findOne(whereParams).then(foundedUser => {
- if (foundedUser) {
- if (foundedUser.username == req.body.username) {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователь с таким Юзернеймом уже существует'));
- } else if (foundedUser.email == req.body.email.toLowerCase()) {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователь с таким такой электронной почтой уже существует'));
- }
- } else {
- return User.create(params);
- }
- }).then(createdUser => {
- res.json({user: createdUser});
- }).catch(next);
- });
- /**
- * Изменяет и возвращает инстанс модели User
- *
- * @name updateUser
- * @route {PUT} /
- * @memberof module:controller/user
- * @routeparam {int} userId - id изменяемого пользователя
- * @bodyparam {string} fullName - ФИО
- * @bodyparam {string} password - пароль
- * @bodyparam {string} phone - номер телефона
- * @bodyparam {string} company - название компании
- * @bodyparam {string} position - должность
- * @bodyparam {string} withdrawalLimit - значение ограничения на вывод средств
- * @bodyparam {string} role - роль
- */
- router.put('/', [
- upload(process.env.COMMON_STORAGE_PATH + '/avatars').single('avatar'),
- userValidator.updateUser,
- checkPermissions(['ofruser', 'publisher'])
- ], (req, res, next) => {
- var user;
- var userQueryConditions;
- // if we have userId in body - use it. Else update authorised user
- if (req.body.userId) {
- userQueryConditions = {where: {id: {$eq: req.body.userId}}};
- } else {
- userQueryConditions = {where: {username: {$eq: req.body.username}}};
- }
- User.findOne(userQueryConditions).then((foundedUser) => {
- if (!foundedUser) {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователя не существует'));
- }
- var fieldsForUpdate = {};
- var filePath = 'public/uploads/avatars/' + foundedUser.avatar;
- user = foundedUser;
- if (req.file) {
- fieldsForUpdate.avatar = req.file.filename;
- if (foundedUser.avatar && foundedUser.avatar != 'user-default-avatar.jpg') {
- fs.unlink(filePath, (error) => {
- if (error) logger.log('error', 'Trying to unlink file ' + filePath + ' with error: ' + error.message);
- });
- }
- } else if (req.body.avatar == 'null') {
- if (foundedUser.avatar && foundedUser.avatar != 'user-default-avatar.jpg') {
- fs.unlink(filePath, (error) => {
- if (error) logger.log('error', 'Trying to unlink file ' + filePath + ' with error: ' + error.message);
- });
- }
- fieldsForUpdate.avatar = '';
- }
- if (req.body.fullName) {
- fieldsForUpdate.fullName = req.body.fullName;
- }
- if (req.body.phone) {
- fieldsForUpdate.phone = req.body.phone;
- }
- if (req.body.company) {
- fieldsForUpdate.company = req.body.company;
- }
- if (req.body.position) {
- fieldsForUpdate.position = req.body.position;
- }
- if (req.body.isModerator) {
- fieldsForUpdate.isModerator = (req.body.isModerator == 'true');
- }
- if (req.body.withdrawalLimit) {
- fieldsForUpdate.withdrawalLimit = parseFloat(req.body.withdrawalLimit).toFixed(2) || parseInt(req.body.withdrawalLimit);
- }
- if (req.body.password) {
- fieldsForUpdate.password = CommonUtil.generatePasswordHash(req.body.password);
- }
- var whereParams = {where: {id: {$eq: foundedUser.id}}};
- return User.update(fieldsForUpdate, whereParams);
- }).then(() => {
- if (req.body.password) {
- var emailSubject = 'Изменение пароля';
- var emailHtml = '<p>Ваш пароль был изменен на ' + req.body.password + '</p>';
- CommonUtil.sendEmail(user.email, emailSubject, emailHtml).then((result)=> {
- }).catch((error)=> {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Письмо с информацией об изменении пароля не было отпралено. ' + error.message));
- });
- }
- return User.findOne({where: {id: user.id}});
- }).then((foundedUser) => {
- res.json({user: foundedUser});
- }).catch(next);
- });
- /**
- * Авторизация. При успехе возвращает инстанс модели User
- *
- * @name signIn
- * @route {POST} /sign-in
- * @memberof module:controller/user
- * @bodyparam {string} username - username
- * @bodyparam {string} password - пароль
- */
- router.post('/sign-in', userValidator.signIn, (req, res, next) => {
- var user;
- var conditions = {
- where: {
- $and: [
- {username: {$eq: req.body.username}},
- {password: {$eq: CommonUtil.generatePasswordHash(req.body.password)}}
- ]
- }
- };
- User.findOne(conditions).then((foundedUser) => {
- if (!foundedUser) {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Неверный логин/пароль!'));
- } else {
- user = foundedUser;
- return Promise.resolve(foundedUser.update({lastVisit: new Date()}, {where: {id: foundedUser.id}}));
- }
- }).then(() => {
- res.setHeader(process.env.COMMON_TOKEN_NAME, CommonUtil.buildJWT(user.id, user.username, user.email, user.role));
- res.json({user: user});
- }).catch(next);
- });
- /**
- * Авторизация по токену. При успехе возвращает инстанс модели User
- *
- * @name signInByToken
- * @route {POST} /sign-in-by-token
- * @memberof module:controller/user
- * @bodyparam {string} token - токен авторизации
- */
- router.post('/sign-in-by-token', userValidator.signInByToken, (req, res, next)=> {
- return new Promise((resolve, reject)=> {
- var userObj = CommonUtil.decodeJWT(req.body.token);
- if (userObj instanceof Error) {
- return reject(new ErrorUtil.ErrorBadRequest('Wrong parameters'));
- }
- var params = {
- where: {
- $and: [
- {username: {$eq: userObj.username}},
- {email: {$eq: userObj.email.toLowerCase()}}
- ]
- }
- };
- return resolve(User.findOne(params));
- }).then((foundedUser)=> {
- if (foundedUser) {
- res.json({user: foundedUser});
- } else {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Wrong token or user is not verified'));
- }
- }).catch(next);
- });
- /**
- * Отправляет email для восстановления пароля
- *
- * @name sendRecoveryEmail
- * @route {POST} /send-recovery-email
- * @memberof module:controller/user
- * @bodyparam {string} email - адрес электронной почты для отправки письма
- */
- router.post('/send-recovery-email', userValidator.sendRecoveryEmail, (req, res, next) => {
- var verificationHash = '';
- var email = req.body.email ? req.body.email.toLowerCase() : req.body.email;
- User.findOne({where: {email: email}}).then((userByEmail) => {
- if (!userByEmail) {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователь с таким email не существует'));
- }
- verificationHash = CommonUtil.generateConfirmLinkHash(userByEmail.email);
- var fields = {
- verificationHash: verificationHash,
- verificationExpiration: Date.now() + 86400000
- };
- var conditions = {where: {id: userByEmail.id}};
- return User.update(fields, conditions);
- }).then(() => {
- return CommonUtil.sendRecoveryEmail(email, verificationHash);
- }).then(() => {
- res.json({email: email});
- }).catch(next);
- });
- /**
- * Изменяет пароль пользователя
- *
- * @name changePassword
- * @route {POST} /change-password
- * @memberof module:controller/user
- * @bodyparam {string} hash - хэш для ссылки восстановления пароля
- * @bodyparam {string} password - новый пароль
- */
- router.post('/change-password', userValidator.changePassword, (req, res, next) => {
- var params = {where: {verificationHash: req.body.hash}};
- User.findOne(params).then((foundedUser) => {
- if (foundedUser) {
- var now = new Date();
- var exp = new Date(foundedUser.verificationExpiration);
- if ((exp.getTime() - now.getTime()) <= 0) {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Эта ссылку не актуальна, попробуйте восстановить пароль снова'));
- }
- } else {
- return Promise.reject(new ErrorUtil.ErrorBadRequest('Эта ссылку не актуальна, попробуйте восстановить пароль снова'));
- }
- var fields = {
- password: CommonUtil.generatePasswordHash(req.body.password),
- verificationHash: '',
- verificationExpiration: null
- };
- var conditions = {where: {id: foundedUser.id}};
- return User.update(fields, conditions);
- }).then(() => {
- res.json({status: 'ok'});
- }).catch(next);
- });
- /**
- * Контроллер пользователей
- * @module controller/user
- */
- module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement