forked from bro-students/multy-stub
35 lines
1.3 KiB
JavaScript
35 lines
1.3 KiB
JavaScript
|
const router = require('express').Router()
|
||
|
const checkPwd = require('pbkdf2-password')()
|
||
|
const jwt = require('jsonwebtoken')
|
||
|
const { BASKET_JWT_TOKEN } = require('./key')
|
||
|
|
||
|
const { getResponse, signUp, getUser, _idToId, requiredFields } = require('./controller')
|
||
|
|
||
|
router.post('/sign-in', requiredFields(['email', 'password']), async (req, res) => {
|
||
|
try {
|
||
|
const user = await getUser(req.body)
|
||
|
// eslint-disable-next-line max-len
|
||
|
checkPwd({ password: req.body.password, salt: user.salt }, async (err, pass, salt, hash) => {
|
||
|
if (err) throw new Error(err)
|
||
|
|
||
|
if (user.pwd === hash) {
|
||
|
const { pwd, salt: _salt, ...rest } = user
|
||
|
const token = jwt.sign(_idToId(rest), BASKET_JWT_TOKEN)
|
||
|
res.send(getResponse(null, { token, user: _idToId(rest) }))
|
||
|
} else {
|
||
|
res.status(400).send(getResponse('Неправильный email или пароль'))
|
||
|
}
|
||
|
})
|
||
|
} catch (e) {
|
||
|
res.status(400).send(getResponse(e.message))
|
||
|
}
|
||
|
})
|
||
|
|
||
|
router.post('/sign-up', requiredFields(['email', 'login', 'password']), async (req, res) => {
|
||
|
let error = null
|
||
|
const data = await signUp(req.body).catch((e) => error = e.message)
|
||
|
res.status(error ? 400 : 200).send(getResponse(error, data))
|
||
|
})
|
||
|
|
||
|
module.exports = router
|