Advertisement
Guest User

Untitled

a guest
Mar 15th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. const Users = require('../db/models/users');
  2. const bcrypt = require('bcryptjs');
  3. const path = require('path');
  4. const fs = require('fs');
  5.  
  6. module.exports = (router, db, sequelize) => {
  7. const Select = { type: sequelize.QueryTypes.SELECT };
  8. const Insert = {type: sequelize.QueryTypes.INSERT};
  9. const Update = {type: sequelize.QueryTypes.UPDATE};
  10.  
  11. router.get('/getUser/:id', (req, res) => {
  12. Users.findById(req.params.id).then(user => {
  13. if(user) {
  14. res.send(user);
  15. } else {
  16. res.status(404).send({error: 'User not found'});
  17. }
  18. })
  19. });
  20.  
  21. router.post('/updateAvatar', (req, res) => {
  22. if (!req.files) {
  23. return res.send('No files were uploaded.');
  24. }
  25.  
  26. const { id, oldAvatar } = req.body;
  27. const upload = req.files.upload;
  28. const fileName = `${id}-${upload.name}`;
  29. const uploadPath = path.join(__dirname, '..', 'static', 'uploads', 'avatars', fileName);
  30.  
  31. if (!fs.existsSync(path.join(`static/uploads/`))) {
  32. fs.mkdirSync(path.join(`static/uploads/`) , 0777);
  33. }
  34.  
  35. if (!fs.existsSync(path.join(`static/uploads/avatars/`))) {
  36. fs.mkdirSync(path.join(`static/uploads/avatars/`), 0777);
  37. }
  38.  
  39. if (oldAvatar) {
  40. fs.unlink(path.join(__dirname, '..', oldAvatar), (err) => {
  41. if (err) {
  42. console.log(err);
  43. } else {
  44. console.log('old avatar deleted');
  45. }
  46. });
  47. }
  48. upload.mv(uploadPath, (err) => {
  49. if (err) {
  50. console.log(err);
  51. return res.status(500).send(err);
  52. }
  53. db.query(`
  54. UPDATE users
  55. SET avatar = '/static/uploads/avatars/${fileName}'
  56. WHERE id = ${id}`,
  57. Update)
  58. .then(() => {
  59. Users.findById(id).then(updatedUser => {
  60. if (updatedUser) {
  61. res.send(updatedUser);
  62. }
  63. })
  64. });
  65. });
  66. });
  67.  
  68. router.post('/changePassword', (req, res) => {
  69. const { oldPass, newPass, id } = req.body;
  70. Users.findById(id).then(user => {
  71. if(user) {
  72. bcrypt.compare(
  73. oldPass,
  74. `$2a${user.password.substring(3)}`,
  75. (error, result) => {
  76. // if (error) console.log(error);
  77. if (!result) {
  78. res.send({info: 'Oops! Wrong old password.', error: true})
  79. } else {
  80. db.query(`
  81. UPDATE users
  82. SET password = '${bcrypt.hashSync(newPass, 10)}'
  83. WHERE id = ${id}`,
  84. Update)
  85. .then(() => {
  86. res.send({info: 'Password has been changed'})
  87. });
  88. }
  89. });
  90. } else {
  91. res.status(404).send({info: 'User not found', error: true});
  92. }
  93. })
  94. });
  95. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement