christmas/routes/profile/index.js

40 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-11-08 13:54:08 -08:00
const verifyAuth = require('../../middlewares/verifyAuth')
const bcrypt = require('bcrypt-nodejs')
const express = require('express')
2018-11-20 11:19:58 -08:00
module.exports = (db) => {
2020-11-08 13:54:08 -08:00
const router = express.Router()
2018-11-20 11:19:58 -08:00
2020-11-08 13:54:08 -08:00
router.get('/', verifyAuth(), (req, res) => res.render('profile', { title: `Profile Settings - ${req.user._id}` }))
2018-11-20 11:19:58 -08:00
router.post('/', verifyAuth(), (req, res) => {
if (req.body.oldPassword && req.body.newPassword) {
bcrypt.compare(req.body.oldPassword, req.user.password, (err, correct) => {
2020-11-08 13:54:08 -08:00
if (err) throw err
2018-11-20 11:19:58 -08:00
if (correct) {
bcrypt.hash(req.body.newPassword, null, null, (err, hash) => {
2020-11-08 13:54:08 -08:00
if (err) throw err
2018-11-20 11:19:58 -08:00
db.get(req.user._id)
.then(doc => {
2020-11-08 13:54:08 -08:00
doc.password = hash
2018-11-20 11:19:58 -08:00
db.put(doc)
.then(() => {
2020-11-08 13:54:08 -08:00
req.flash('success', 'Changes saved successfully!')
res.redirect('/profile')
2018-11-20 11:19:58 -08:00
})
2020-11-08 13:54:08 -08:00
.catch(err => { throw err })
2018-11-20 11:19:58 -08:00
})
2020-11-08 13:54:08 -08:00
.catch(err => { throw err })
})
2018-11-20 11:19:58 -08:00
} else {
2020-11-08 13:54:08 -08:00
req.flash('error', 'Incorrect old password')
res.redirect('/profile')
2018-11-20 11:19:58 -08:00
}
2020-11-08 13:54:08 -08:00
})
2018-11-20 11:19:58 -08:00
} else {
2020-11-08 13:54:08 -08:00
res.redirect('/profile')
2018-11-20 11:19:58 -08:00
}
2020-11-08 13:54:08 -08:00
})
2018-11-20 11:19:58 -08:00
2020-11-08 13:54:08 -08:00
return router
}