christmas/routes/resetpw/index.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-11-08 13:54:08 -08:00
const bcrypt = require('bcrypt-nodejs')
const express = require('express')
2020-10-30 08:15:00 -07:00
module.exports = (db) => {
2020-11-08 13:54:08 -08:00
const router = express.Router()
2020-10-30 08:15:00 -07:00
router.get('/:code', async (req, res) => {
const row = (await db.allDocs({ include_docs: true }))
.rows
.find(({ doc }) => doc.pwToken === req.params.code)
res.render('resetpw', { doc: row ? row.doc : undefined })
2020-11-08 13:54:08 -08:00
})
2020-10-30 08:15:00 -07:00
router.post('/:code', async (req, res) => {
const { doc } = (await db.allDocs({ include_docs: true }))
.rows
.find(({ doc }) => doc.pwToken === req.params.code)
if (doc.expiry < new Date().getTime()) return res.redirect(`/resetpw/${req.params.code}`)
bcrypt.hash(req.body.password, null, null, async (err, passwordHash) => {
2020-11-08 13:54:08 -08:00
if (err) throw err
2020-10-30 08:15:00 -07:00
doc.password = passwordHash
delete doc.pwToken
delete doc.pwExpiry
await db.put(doc)
req.login({ _id: doc._id }, err => {
if (err) {
console.log(err)
req.flash('error', err.message)
return res.redirect('/')
}
2021-12-03 08:13:43 -08:00
req.flash('success', _CC.lang('RESET_PASSWORD_SUCCESS'))
2020-11-08 13:54:08 -08:00
res.redirect('/')
2020-10-30 08:15:00 -07:00
})
2020-11-08 13:54:08 -08:00
})
})
2020-10-30 08:15:00 -07:00
2020-11-08 13:54:08 -08:00
return router
}