Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Users = require('../db/models/users');
- const bcrypt = require('bcryptjs');
- const path = require('path');
- const fs = require('fs');
- module.exports = (router, db, sequelize) => {
- const Select = { type: sequelize.QueryTypes.SELECT };
- const Insert = {type: sequelize.QueryTypes.INSERT};
- const Update = {type: sequelize.QueryTypes.UPDATE};
- router.get('/getUser/:id', (req, res) => {
- Users.findById(req.params.id).then(user => {
- if(user) {
- res.send(user);
- } else {
- res.status(404).send({error: 'User not found'});
- }
- })
- });
- router.post('/updateAvatar', (req, res) => {
- if (!req.files) {
- return res.send('No files were uploaded.');
- }
- const { id, oldAvatar } = req.body;
- const upload = req.files.upload;
- const fileName = `${id}-${upload.name}`;
- const uploadPath = path.join(__dirname, '..', 'static', 'uploads', 'avatars', fileName);
- if (!fs.existsSync(path.join(`static/uploads/`))) {
- fs.mkdirSync(path.join(`static/uploads/`) , 0777);
- }
- if (!fs.existsSync(path.join(`static/uploads/avatars/`))) {
- fs.mkdirSync(path.join(`static/uploads/avatars/`), 0777);
- }
- if (oldAvatar) {
- fs.unlink(path.join(__dirname, '..', oldAvatar), (err) => {
- if (err) {
- console.log(err);
- } else {
- console.log('old avatar deleted');
- }
- });
- }
- upload.mv(uploadPath, (err) => {
- if (err) {
- console.log(err);
- return res.status(500).send(err);
- }
- db.query(`
- UPDATE users
- SET avatar = '/static/uploads/avatars/${fileName}'
- WHERE id = ${id}`,
- Update)
- .then(() => {
- Users.findById(id).then(updatedUser => {
- if (updatedUser) {
- res.send(updatedUser);
- }
- })
- });
- });
- });
- router.post('/changePassword', (req, res) => {
- const { oldPass, newPass, id } = req.body;
- Users.findById(id).then(user => {
- if(user) {
- bcrypt.compare(
- oldPass,
- `$2a${user.password.substring(3)}`,
- (error, result) => {
- // if (error) console.log(error);
- if (!result) {
- res.send({info: 'Oops! Wrong old password.', error: true})
- } else {
- db.query(`
- UPDATE users
- SET password = '${bcrypt.hashSync(newPass, 10)}'
- WHERE id = ${id}`,
- Update)
- .then(() => {
- res.send({info: 'Password has been changed'})
- });
- }
- });
- } else {
- res.status(404).send({info: 'User not found', error: true});
- }
- })
- });
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement