|
|
|
const router = require('express-promise-router')()
|
|
|
|
const parseJSON = require('body-parser').json()
|
|
|
|
const db = require('../db')
|
|
|
|
|
|
|
|
const {validationResult} = require('express-validator')
|
|
|
|
const validate = require('./middleware/validators')
|
|
|
|
|
|
|
|
const loginValidation = [validate.emailRestrictions, validate.passwordRestrictions]
|
|
|
|
router.post('/', parseJSON, loginValidation, async (req, res) => {
|
|
|
|
const errors = validationResult(req)
|
|
|
|
|
|
|
|
if(!errors.isEmpty())
|
|
|
|
return res.status(422).json({errors: errors.array()})
|
|
|
|
|
|
|
|
const user = await db.user.login(
|
|
|
|
req.body.email,
|
|
|
|
req.body.password
|
|
|
|
)
|
|
|
|
|
|
|
|
if(!user){
|
|
|
|
return res.status(422).json({errors: [{
|
|
|
|
param: 'email',
|
|
|
|
msg: 'Invalid login'
|
|
|
|
},{
|
|
|
|
param: 'password',
|
|
|
|
msg: ' '
|
|
|
|
}]})
|
|
|
|
}
|
|
|
|
|
|
|
|
await db.session.create(req, user)
|
|
|
|
|
|
|
|
const {password_hash, ...result} = user
|
|
|
|
|
|
|
|
res.json(result)
|
|
|
|
})
|
|
|
|
|
|
|
|
// TODO: Login link stuff
|
|
|
|
|
|
|
|
router.get('/', async (req, res) => {
|
|
|
|
res.json(req.user)
|
|
|
|
})
|
|
|
|
|
|
|
|
router.get('/logout', async (req, res) => {
|
|
|
|
await db.session.end(req.session.uuid);
|
|
|
|
|
|
|
|
req.session = null
|
|
|
|
res.redirect('/')
|
|
|
|
})
|
|
|
|
|
|
|
|
module.exports = router;
|