node-go/server/controllers/auth.js

71 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-01-14 20:06:25 +00:00
const knex = require('../data/db')
2020-01-14 22:22:42 +00:00
2020-01-15 07:09:01 +00:00
const { hashPassword, compareHash } = require('../services/bcrypt');
const signToken = require('../services/signToken');
const { validationResult } = require('express-validator');
const checkValidationErrors = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
}
2020-01-10 01:44:58 +00:00
2020-01-15 07:09:01 +00:00
const signup = async (req, res, next) => {
checkValidationErrors(req, res);
const user = req.body;
try {
2020-01-16 04:04:55 +00:00
delete user.confirmPassword;
2020-01-14 22:22:42 +00:00
const hashedPassword = await hashPassword(user.password);
const secureUser = { ...user, password: hashedPassword }
2020-01-16 04:04:55 +00:00
2020-01-14 20:06:25 +00:00
knex('user')
.returning(['username', 'email'])
2020-01-14 22:22:42 +00:00
.insert(secureUser)
.then(queryResults => {
const newUser = queryResults[0];
2020-01-16 04:04:55 +00:00
signToken(res, newUser).send('ok').status(201);
2020-01-14 22:22:42 +00:00
})
}
catch (err) {
2020-01-16 04:04:55 +00:00
res.status(500).json(err);
}
2020-01-10 01:44:58 +00:00
}
2020-01-15 07:09:01 +00:00
const login = async (req, res, next) => {
checkValidationErrors(req, res);
2020-01-15 07:09:01 +00:00
const user = req.body;
try {
2020-01-10 01:44:58 +00:00
2020-01-15 07:09:01 +00:00
const queryResults = await knex('user')
.where({username: user.username})
.select()
2020-01-15 07:09:01 +00:00
.then(queryResults => queryResults);
const savedUser = queryResults[0] || null;
if (!savedUser) return res.status(401).json({err: 'bad credentials'});
const hashedPassword = savedUser.password;
const passwordMatch = await compareHash(user.password, hashedPassword);
if (!passwordMatch) return res.status(401).json({err: 'bad credentials'});
const authorizedUser = {...savedUser};
delete authorizedUser.password;
signToken(res, authorizedUser);
res.send('ok').status(200);
}
catch (err) {
res.status(500).json(err);
}
2020-01-10 01:44:58 +00:00
}
module.exports = {
2020-01-15 07:09:01 +00:00
signup,
2020-01-10 01:44:58 +00:00
login
}