christmas/routes/profile/index.js

50 lines
1.6 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
2021-09-14 23:41:44 -07:00
module.exports = ({ db, ensurePfp }) => {
2020-11-08 13:54:08 -08:00
const router = express.Router()
2018-11-20 11:19:58 -08:00
2021-09-14 23:41:44 -07:00
router.get('/', verifyAuth(), async (req, res) => {
await ensurePfp(req.user._id)
res.render('profile', { title: `Profile Settings - ${req.user._id}` })
})
router.post('/pfp', verifyAuth(), async (req, res) => {
req.user.pfp = req.body.image
await db.put(req.user)
if (!req.user.pfp) await ensurePfp(req.user._id)
req.flash('success', 'Saved profile picture!')
res.redirect(`${_CC.config.base}profile`)
})
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
}