const router = require('express-promise-router')() const parseJSON = require('body-parser').json() const db = require('../db') const ensureAdmin = require('./middleware/ensureAdmin') const ensureUser = require('./middleware/ensureUser') const email = require('../utils/email') const sendgrid = require('@sendgrid/mail') sendgrid.setApiKey(process.env.SENDGRID_KEY) const validate = require('./middleware/validators') const registerValidation = [ validate.unusedEmail('email'), validate.validPassword('password'), validate.bothPasswordsMatch, validate.handleApiError ] router.post('/', parseJSON, registerValidation, async (req, res) => { const user = await db.user.register( req.body.email, req.body.password ) if(!user){ return res.status(422).json({errors: [{ param: 'email', msg: 'Unable to complete registration' },{ param: 'password', msg: ' ' },{ param: 'password2', msg: ' ' }]}) } await db.session.create(req, user) await email.sendAccountConfirmation(user) res.json(user) }) router.post('/recover', parseJSON, validate.validEmail('email'), async (req, res) => { const user = await db.user.findByEmail(req.body.email) if(user) email.sendPasswordReset(user) else email.sendNoSuchAccount(req.body.email) res.end() }) router.post('/recover/password', parseJSON, validate.validPassword('password'), validate.bothPasswordsMatch, async (req, res) => { const {password, link_uuid, link_key} = req.body const user = await db.user.verifyPasswordReset(link_uuid, link_key) if(!user){ return res.status(422).json({errors: [{ param: 'password', msg: 'Invalid reset link' }]}) } await email.sendPasswordChanged(user) const updatedUser = await db.user.overwritePassword(user.uuid, password) await db.user.markLinkUsed(link_uuid) await db.session.create(req, updatedUser) res.json(updatedUser) }) router.get('/', ensureAdmin, async (req, res) => { const users = await db.user.findAll() res.json(users) }) router.get('/:uuid', ensureAdmin, async (req, res) => { const user = await db.user.findById(req.params.uuid) res.json(user) }) router.get('/:uuid/orders', ensureAdmin, async (req, res) => { return res.json(await db.order.findAllForUser(req.params.uuid)) }) router.put('/:uuid/admin', ensureAdmin, async (req, res) => { const user = await db.user.makeAdmin(req.params.uuid) res.json(user) }) router.delete('/:uuid/admin', ensureAdmin, async (req, res) => { const user = await db.user.removeAdmin(req.params.uuid) res.json(user) }) const changePasswordValidation = [ validate.validPassword('password'), validate.bothPasswordsMatch, validate.oldPasswordNotSame, validate.handleApiError ] router.put('/current/password', parseJSON, changePasswordValidation, ensureUser, async (req, res) => { const user = await db.user.changePassword( req.user.uuid, req.body.oldPassword, req.body.password ) if(!user){ return res.status(403).json({errors: [{ param: 'oldPassword', msg: 'Incorrect password' }]}) } await email.sendPasswordChanged(user) res.json(user) }) module.exports = router;