node-go/server/controllers/auth.js

70 lines
1.9 KiB
JavaScript
Raw Normal View History

const { validationResult } = require('express-validator');
const userQueries = require('../data/queries/user');
2020-01-15 07:09:01 +00:00
const { hashPassword, compareHash } = require('../services/bcrypt');
const signToken = require('../services/signToken');
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;
const existingUser = await userQueries.findUserByNameOrEmail(user);
2020-01-14 22:22:42 +00:00
const hashedPassword = await hashPassword(user.password);
const secureUser = { ...user, password: hashedPassword };
if (existingUser.length) {
return res.status(409).json({errors: [{auth: 'User already exists!'}]})
}
2020-01-16 04:04:55 +00:00
const newUser = await userQueries.insertUser(secureUser);
signToken(res, newUser)
res.status(201).json({...newUser});
}
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;
2020-01-15 07:09:01 +00:00
try {
const queryResults = await userQueries.findUserByNameOrEmail(user);
2020-01-15 07:09:01 +00:00
const savedUser = queryResults[0] || null;
if (!savedUser) {
2020-01-18 08:18:51 +00:00
return res.status(401).send({errors: 'bad credentials'});
}
2020-01-15 07:09:01 +00:00
const hashedPassword = savedUser.password;
const passwordMatch = await compareHash(user.password, hashedPassword);
if (!passwordMatch) {
2020-01-18 08:18:51 +00:00
return res.status(401).send({errors: 'bad credentials'});
}
2020-01-15 07:09:01 +00:00
const authorizedUser = {...savedUser};
delete authorizedUser.password;
signToken(res, authorizedUser);
2020-01-18 08:18:51 +00:00
res.send({...authorizedUser}).status(200);
2020-01-15 07:09:01 +00:00
}
2020-01-15 07:09:01 +00:00
catch (err) {
2020-01-18 08:18:51 +00:00
res.status(500).send({errors: err});
2020-01-15 07:09:01 +00:00
}
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
}