Advertisement
Guest User

Untitled

a guest
Aug 31st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.84 KB | None | 0 0
  1. const fs = require('fs');
  2. const userValidator = require('../validators/userValidator');
  3. const logger = require('../utils/LoggerUtil');
  4. const router = require('express').Router();
  5. const CommonUtil = require('../utils/CommonUtil');
  6. const ErrorUtil = require('../utils/ErrorUtil');
  7. const {upload, checkPermissions} = require('../utils/MiddlewareUtil');
  8. const {Campaign, Platform, User} = require('../models').db;
  9.  
  10.  
  11. /**
  12. * Проверяет доступ к изменению пароля и в случае успеха возвращает инстанс модели User - пользователя по указанному хэшу
  13. *
  14. * @name getChangePassword-Access
  15. * @route {GET} /change-password-access
  16. * @memberof module:controller/user
  17. * @queryparam {string} hash - временный хэш для восстановления пароля
  18. */
  19. router.get('/change-password-access', userValidator.changePasswordAccess, (req, res, next) => {
  20. User.findOne({where: {verificationHash: {$eq: req.query.hash}}}).then(()=> {
  21. res.json({hash: req.query.hash});
  22. }).catch(next);
  23. });
  24.  
  25.  
  26. /**
  27. * Возвращает массив инстансов модели User
  28. *
  29. * @name getUsers
  30. * @route {GET} /
  31. * @memberof module:controller/user
  32. * @queryparam {string} searchString - строка для поиска по полям: fullName, username, email, phone, company, position
  33. * @queryparam {string} role - роль пользователя
  34. * @queryparam {string} roles - сериализованный массив ролей пользователя
  35. */
  36. router.get('/', [
  37. checkPermissions(),
  38. userValidator.getUsers
  39. ], (req, res, next) => {
  40. var whereParams = {
  41. where: {$or: [], $and: []},
  42. include: null,
  43. limit: 50,
  44. offset: 0
  45. };
  46.  
  47. if (req.query.searchString) {
  48. whereParams.where.$or.push({fullName: {$iLike: '%' + req.query.searchString + '%'}});
  49. whereParams.where.$or.push({username: {$iLike: '%' + req.query.searchString + '%'}});
  50. whereParams.where.$or.push({email: {$iLike: '%' + req.query.searchString + '%'}});
  51. whereParams.where.$or.push({phone: {$iLike: '%' + req.query.searchString + '%'}});
  52. whereParams.where.$or.push({company: {$iLike: '%' + req.query.searchString + '%'}});
  53. whereParams.where.$or.push({position: {$iLike: '%' + req.query.searchString + '%'}});
  54. }
  55.  
  56. if (req.query.role) {
  57. whereParams.where.$or.push({role: {$eq: req.query.role}});
  58. if (req.query.role === 'ofruser') {
  59. whereParams.include = Campaign;
  60. }
  61. if (req.query.role === 'publisher') {
  62. whereParams.include = Platform;
  63. }
  64. }
  65.  
  66. if (req.query.roles) {
  67. var rolesArray = JSON.parse(req.query.roles);
  68. rolesArray.map((role)=> {
  69. whereParams.where.$or.push({role: {$eq: role}});
  70. });
  71. }
  72.  
  73. if (req.query.pageNum > 1) {
  74. whereParams.offset = (parseInt(req.query.pageNum) - 1) * 50;
  75. }
  76.  
  77. if (!whereParams.where.$or.length) {
  78. delete whereParams.where.$or;
  79. }
  80.  
  81. if (!whereParams.where.$and.length) {
  82. delete whereParams.where.$and;
  83. }
  84.  
  85. User.findAll(whereParams).then((users) => {
  86. res.json({users: users});
  87. }).catch(next);
  88. });
  89.  
  90.  
  91. /**
  92. * Возвращает инстанс модели User
  93. *
  94. * @name getUser
  95. * @route {GET} /:id
  96. * @memberof module:controller/user
  97. * @routeparam {int} id - id пользователя
  98. */
  99. router.get('/:id', userValidator.getUserById, (req, res, next) => {
  100. User.findOne({where: {id: {$eq: req.params.id}}}).then((user) => {
  101. res.json({user: user});
  102. }).catch(next);
  103. });
  104.  
  105.  
  106. /**
  107. * Создает и возвращает инстанс модели User
  108. *
  109. * @name createUser
  110. * @route {POST} /
  111. * @memberof module:controller/user
  112. * @bodyparam {string} username - username
  113. * @bodyparam {string} fullName - ФИО
  114. * @bodyparam {string} password - пароль
  115. * @bodyparam {string} email - адрес электронной почты
  116. * @bodyparam {string} phone - номер телефона
  117. * @bodyparam {string} company - название компании
  118. * @bodyparam {string} position - должность
  119. * @bodyparam {string} withdrawalLimit - значение ограничения на вывод средств
  120. * @bodyparam {string} role - роль
  121. */
  122. router.post('/', [
  123. upload(process.env.COMMON_STORAGE_PATH + '/avatars').single('avatar'),
  124. userValidator.createUser,
  125. checkPermissions()
  126. ], (req, res, next) => {
  127. var params = {
  128. username: req.body.username,
  129. fullName: req.body.fullName,
  130. password: CommonUtil.generatePasswordHash(req.body.password),
  131. email: req.body.email.toLowerCase(),
  132. phone: req.body.phone,
  133. company: req.body.company || '',
  134. position: req.body.position || '',
  135. withdrawalLimit: parseFloat(req.body.withdrawalLimit).toFixed(2) || 10000,
  136. role: req.body.role,
  137. isModerator: (req.body.isModerator && (req.body.role == 'admin' || req.body.role == 'publisher')),
  138. avatar: req.file ? req.file.filename : ''
  139. };
  140.  
  141. var whereParams = {
  142. where: {
  143. $or: [
  144. {username: {$eq: req.body.username}},
  145. {email: {$eq: req.body.email.toLowerCase()}}
  146. ]
  147. }
  148. };
  149.  
  150. User.findOne(whereParams).then(foundedUser => {
  151. if (foundedUser) {
  152. if (foundedUser.username == req.body.username) {
  153. return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователь с таким Юзернеймом уже существует'));
  154. } else if (foundedUser.email == req.body.email.toLowerCase()) {
  155. return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователь с таким такой электронной почтой уже существует'));
  156. }
  157. } else {
  158. return User.create(params);
  159. }
  160. }).then(createdUser => {
  161. res.json({user: createdUser});
  162. }).catch(next);
  163. });
  164.  
  165.  
  166. /**
  167. * Изменяет и возвращает инстанс модели User
  168. *
  169. * @name updateUser
  170. * @route {PUT} /
  171. * @memberof module:controller/user
  172. * @routeparam {int} userId - id изменяемого пользователя
  173. * @bodyparam {string} fullName - ФИО
  174. * @bodyparam {string} password - пароль
  175. * @bodyparam {string} phone - номер телефона
  176. * @bodyparam {string} company - название компании
  177. * @bodyparam {string} position - должность
  178. * @bodyparam {string} withdrawalLimit - значение ограничения на вывод средств
  179. * @bodyparam {string} role - роль
  180. */
  181. router.put('/', [
  182. upload(process.env.COMMON_STORAGE_PATH + '/avatars').single('avatar'),
  183. userValidator.updateUser,
  184. checkPermissions(['ofruser', 'publisher'])
  185. ], (req, res, next) => {
  186. var user;
  187. var userQueryConditions;
  188. // if we have userId in body - use it. Else update authorised user
  189. if (req.body.userId) {
  190. userQueryConditions = {where: {id: {$eq: req.body.userId}}};
  191. } else {
  192. userQueryConditions = {where: {username: {$eq: req.body.username}}};
  193. }
  194.  
  195. User.findOne(userQueryConditions).then((foundedUser) => {
  196.  
  197. if (!foundedUser) {
  198. return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователя не существует'));
  199. }
  200.  
  201. var fieldsForUpdate = {};
  202. var filePath = 'public/uploads/avatars/' + foundedUser.avatar;
  203. user = foundedUser;
  204.  
  205. if (req.file) {
  206. fieldsForUpdate.avatar = req.file.filename;
  207. if (foundedUser.avatar && foundedUser.avatar != 'user-default-avatar.jpg') {
  208. fs.unlink(filePath, (error) => {
  209. if (error) logger.log('error', 'Trying to unlink file ' + filePath + ' with error: ' + error.message);
  210. });
  211. }
  212. } else if (req.body.avatar == 'null') {
  213. if (foundedUser.avatar && foundedUser.avatar != 'user-default-avatar.jpg') {
  214. fs.unlink(filePath, (error) => {
  215. if (error) logger.log('error', 'Trying to unlink file ' + filePath + ' with error: ' + error.message);
  216. });
  217. }
  218. fieldsForUpdate.avatar = '';
  219. }
  220.  
  221. if (req.body.fullName) {
  222. fieldsForUpdate.fullName = req.body.fullName;
  223. }
  224. if (req.body.phone) {
  225. fieldsForUpdate.phone = req.body.phone;
  226. }
  227. if (req.body.company) {
  228. fieldsForUpdate.company = req.body.company;
  229. }
  230. if (req.body.position) {
  231. fieldsForUpdate.position = req.body.position;
  232. }
  233. if (req.body.isModerator) {
  234. fieldsForUpdate.isModerator = (req.body.isModerator == 'true');
  235. }
  236. if (req.body.withdrawalLimit) {
  237. fieldsForUpdate.withdrawalLimit = parseFloat(req.body.withdrawalLimit).toFixed(2) || parseInt(req.body.withdrawalLimit);
  238. }
  239. if (req.body.password) {
  240. fieldsForUpdate.password = CommonUtil.generatePasswordHash(req.body.password);
  241. }
  242.  
  243. var whereParams = {where: {id: {$eq: foundedUser.id}}};
  244.  
  245. return User.update(fieldsForUpdate, whereParams);
  246. }).then(() => {
  247. if (req.body.password) {
  248. var emailSubject = 'Изменение пароля';
  249. var emailHtml = '<p>Ваш пароль был изменен на ' + req.body.password + '</p>';
  250. CommonUtil.sendEmail(user.email, emailSubject, emailHtml).then((result)=> {
  251. }).catch((error)=> {
  252. return Promise.reject(new ErrorUtil.ErrorBadRequest('Письмо с информацией об изменении пароля не было отпралено. ' + error.message));
  253. });
  254. }
  255. return User.findOne({where: {id: user.id}});
  256. }).then((foundedUser) => {
  257. res.json({user: foundedUser});
  258. }).catch(next);
  259. });
  260.  
  261.  
  262. /**
  263. * Авторизация. При успехе возвращает инстанс модели User
  264. *
  265. * @name signIn
  266. * @route {POST} /sign-in
  267. * @memberof module:controller/user
  268. * @bodyparam {string} username - username
  269. * @bodyparam {string} password - пароль
  270. */
  271. router.post('/sign-in', userValidator.signIn, (req, res, next) => {
  272. var user;
  273. var conditions = {
  274. where: {
  275. $and: [
  276. {username: {$eq: req.body.username}},
  277. {password: {$eq: CommonUtil.generatePasswordHash(req.body.password)}}
  278. ]
  279. }
  280. };
  281.  
  282. User.findOne(conditions).then((foundedUser) => {
  283. if (!foundedUser) {
  284. return Promise.reject(new ErrorUtil.ErrorBadRequest('Неверный логин/пароль!'));
  285. } else {
  286. user = foundedUser;
  287. return Promise.resolve(foundedUser.update({lastVisit: new Date()}, {where: {id: foundedUser.id}}));
  288. }
  289. }).then(() => {
  290. res.setHeader(process.env.COMMON_TOKEN_NAME, CommonUtil.buildJWT(user.id, user.username, user.email, user.role));
  291. res.json({user: user});
  292. }).catch(next);
  293. });
  294.  
  295.  
  296. /**
  297. * Авторизация по токену. При успехе возвращает инстанс модели User
  298. *
  299. * @name signInByToken
  300. * @route {POST} /sign-in-by-token
  301. * @memberof module:controller/user
  302. * @bodyparam {string} token - токен авторизации
  303. */
  304. router.post('/sign-in-by-token', userValidator.signInByToken, (req, res, next)=> {
  305. return new Promise((resolve, reject)=> {
  306.  
  307. var userObj = CommonUtil.decodeJWT(req.body.token);
  308. if (userObj instanceof Error) {
  309. return reject(new ErrorUtil.ErrorBadRequest('Wrong parameters'));
  310. }
  311.  
  312. var params = {
  313. where: {
  314. $and: [
  315. {username: {$eq: userObj.username}},
  316. {email: {$eq: userObj.email.toLowerCase()}}
  317. ]
  318. }
  319. };
  320.  
  321. return resolve(User.findOne(params));
  322. }).then((foundedUser)=> {
  323. if (foundedUser) {
  324. res.json({user: foundedUser});
  325. } else {
  326. return Promise.reject(new ErrorUtil.ErrorBadRequest('Wrong token or user is not verified'));
  327. }
  328. }).catch(next);
  329. });
  330.  
  331.  
  332. /**
  333. * Отправляет email для восстановления пароля
  334. *
  335. * @name sendRecoveryEmail
  336. * @route {POST} /send-recovery-email
  337. * @memberof module:controller/user
  338. * @bodyparam {string} email - адрес электронной почты для отправки письма
  339. */
  340. router.post('/send-recovery-email', userValidator.sendRecoveryEmail, (req, res, next) => {
  341. var verificationHash = '';
  342. var email = req.body.email ? req.body.email.toLowerCase() : req.body.email;
  343.  
  344. User.findOne({where: {email: email}}).then((userByEmail) => {
  345. if (!userByEmail) {
  346. return Promise.reject(new ErrorUtil.ErrorBadRequest('Пользователь с таким email не существует'));
  347. }
  348.  
  349. verificationHash = CommonUtil.generateConfirmLinkHash(userByEmail.email);
  350. var fields = {
  351. verificationHash: verificationHash,
  352. verificationExpiration: Date.now() + 86400000
  353. };
  354. var conditions = {where: {id: userByEmail.id}};
  355.  
  356. return User.update(fields, conditions);
  357. }).then(() => {
  358. return CommonUtil.sendRecoveryEmail(email, verificationHash);
  359. }).then(() => {
  360. res.json({email: email});
  361. }).catch(next);
  362. });
  363.  
  364.  
  365. /**
  366. * Изменяет пароль пользователя
  367. *
  368. * @name changePassword
  369. * @route {POST} /change-password
  370. * @memberof module:controller/user
  371. * @bodyparam {string} hash - хэш для ссылки восстановления пароля
  372. * @bodyparam {string} password - новый пароль
  373. */
  374. router.post('/change-password', userValidator.changePassword, (req, res, next) => {
  375. var params = {where: {verificationHash: req.body.hash}};
  376. User.findOne(params).then((foundedUser) => {
  377. if (foundedUser) {
  378. var now = new Date();
  379. var exp = new Date(foundedUser.verificationExpiration);
  380. if ((exp.getTime() - now.getTime()) <= 0) {
  381. return Promise.reject(new ErrorUtil.ErrorBadRequest('Эта ссылку не актуальна, попробуйте восстановить пароль снова'));
  382. }
  383. } else {
  384. return Promise.reject(new ErrorUtil.ErrorBadRequest('Эта ссылку не актуальна, попробуйте восстановить пароль снова'));
  385. }
  386.  
  387. var fields = {
  388. password: CommonUtil.generatePasswordHash(req.body.password),
  389. verificationHash: '',
  390. verificationExpiration: null
  391. };
  392. var conditions = {where: {id: foundedUser.id}};
  393.  
  394. return User.update(fields, conditions);
  395. }).then(() => {
  396. res.json({status: 'ok'});
  397. }).catch(next);
  398. });
  399.  
  400.  
  401. /**
  402. * Контроллер пользователей
  403. * @module controller/user
  404. */
  405. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement