|
@@ -1,3 +1,4 @@
|
|
|
+let bcrypt = require('bcryptjs')
|
|
|
let express = require('express')
|
|
|
let router = express.Router()
|
|
|
|
|
@@ -5,7 +6,7 @@ const Errors = require('../lib/errors.js')
|
|
|
let User = require('../models').User
|
|
|
|
|
|
router.post('/', async (req, res) => {
|
|
|
- let user, validationErrors = [];
|
|
|
+ let user, hash, validationErrors = [];
|
|
|
|
|
|
try {
|
|
|
//Validations
|
|
@@ -35,9 +36,11 @@ router.post('/', async (req, res) => {
|
|
|
|
|
|
if(validationErrors.length) throw Errors.VALIDATION_ERROR
|
|
|
|
|
|
+ hash = await bcrypt.hash(req.body.password, 12)
|
|
|
+
|
|
|
user = await User.create({
|
|
|
username: req.body.username,
|
|
|
- hash: req.body.password
|
|
|
+ hash: hash
|
|
|
})
|
|
|
|
|
|
res.json(user.toJSON())
|
|
@@ -61,4 +64,74 @@ router.post('/', async (req, res) => {
|
|
|
}
|
|
|
})
|
|
|
|
|
|
+router.post('/login', async (req, res) => {
|
|
|
+ let user, bcryptRes, validationErrors = []
|
|
|
+
|
|
|
+ try {
|
|
|
+ //Validations
|
|
|
+ if(req.body.username === undefined) {
|
|
|
+ validationErrors.push(Errors.missingParameter('username'))
|
|
|
+ } else if(typeof req.body.username !== 'string') {
|
|
|
+ validationErrors.push(Errors.invalidParameterType('username', 'string'))
|
|
|
+ }
|
|
|
+
|
|
|
+ if(req.body.password === undefined) {
|
|
|
+ validationErrors.push(Errors.missingParameter('password'))
|
|
|
+ } else if(typeof req.body.password !== 'string') {
|
|
|
+ validationErrors.push(Errors.invalidParameterType('password', 'string'))
|
|
|
+ }
|
|
|
+
|
|
|
+ if(validationErrors.length) throw Errors.VALIDATION_ERROR
|
|
|
+
|
|
|
+ user = await User.findOne({
|
|
|
+ where: {
|
|
|
+ username: req.body.username,
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ if(user) {
|
|
|
+ bcryptRes = await bcrypt.compare(req.body.password, user.hash)
|
|
|
+
|
|
|
+ if(bcryptRes) {
|
|
|
+ req.session.loggedIn = true;
|
|
|
+ res.json({
|
|
|
+ username: user.username,
|
|
|
+ success: true
|
|
|
+ })
|
|
|
+ } else {
|
|
|
+ res.status(401)
|
|
|
+ res.json({
|
|
|
+ errors: [Errors.invalidLoginCredentials]
|
|
|
+ })
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ res.status(401)
|
|
|
+ res.json({
|
|
|
+ errors: [Errors.invalidLoginCredentials]
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ } catch (err) {
|
|
|
+ if(err === Errors.VALIDATION_ERROR) {
|
|
|
+ res.status(400)
|
|
|
+ res.json({
|
|
|
+ errors: validationErrors
|
|
|
+ })
|
|
|
+ } else {
|
|
|
+ console.log(err)
|
|
|
+ res.status(500)
|
|
|
+ res.json({
|
|
|
+ errors: [Errors.unknown]
|
|
|
+ })
|
|
|
+ }
|
|
|
+ }
|
|
|
+})
|
|
|
+
|
|
|
+router.post('/logout', async (req, res) => {
|
|
|
+ req.session.loggedIn = false;
|
|
|
+ res.json({
|
|
|
+ success: true
|
|
|
+ })
|
|
|
+})
|
|
|
+
|
|
|
module.exports = router
|