patch signup post for existing user to return 409

This commit is contained in:
Sorrel Bri 2020-01-17 00:23:18 -08:00
parent df110d187a
commit 196b5e884b
4 changed files with 71 additions and 25 deletions

View file

@ -1,10 +1,10 @@
const knex = require('../data/db')
const { hashPassword, compareHash } = require('../services/bcrypt');
const signToken = require('../services/signToken');
const { validationResult } = require('express-validator'); const { validationResult } = require('express-validator');
const userQueries = require('../data/queries/user');
const { hashPassword, compareHash } = require('../services/bcrypt');
const signToken = require('../services/signToken');
const checkValidationErrors = (req, res) => { const checkValidationErrors = (req, res) => {
const errors = validationResult(req); const errors = validationResult(req);
if (!errors.isEmpty()) { if (!errors.isEmpty()) {
@ -14,21 +14,22 @@ const checkValidationErrors = (req, res) => {
const signup = async (req, res, next) => { const signup = async (req, res, next) => {
checkValidationErrors(req, res); checkValidationErrors(req, res);
const user = req.body; const user = req.body;
try { try {
delete user.confirmPassword; delete user.confirmPassword;
const hashedPassword = await hashPassword(user.password); const hashedPassword = await hashPassword(user.password);
const secureUser = { ...user, password: hashedPassword } const secureUser = { ...user, password: hashedPassword };
const existingUser = await userQueries.findUserByNameOrEmail(secureUser);
knex('user') if (existingUser.length) {
.returning(['username', 'email']) return res.status(409).json({errors: [{auth: 'User already exists!'}]})
.insert(secureUser)
.then(queryResults => {
const newUser = queryResults[0];
signToken(res, newUser).send('ok').status(201);
})
} }
const newUser = await userQueries.insertUser(secureUser)
signToken(res, newUser).status(201).json({...newUser});
}
catch (err) { catch (err) {
res.status(500).json(err); res.status(500).json(err);
} }
@ -37,22 +38,22 @@ const signup = async (req, res, next) => {
const login = async (req, res, next) => { const login = async (req, res, next) => {
checkValidationErrors(req, res); checkValidationErrors(req, res);
const user = req.body; const user = req.body;
try { try {
const queryResults = await userQueries.findUserByNameOrEmail(user);
const queryResults = await knex('user')
.where({username: user.username})
.select()
.then(queryResults => queryResults);
const savedUser = queryResults[0] || null; const savedUser = queryResults[0] || null;
if (!savedUser) return res.status(401).json({err: 'bad credentials'});
if (!savedUser) {
return res.status(401).json({err: 'bad credentials'});
}
const hashedPassword = savedUser.password; const hashedPassword = savedUser.password;
const passwordMatch = await compareHash(user.password, hashedPassword); const passwordMatch = await compareHash(user.password, hashedPassword);
if (!passwordMatch) return res.status(401).json({err: 'bad credentials'});
if (!passwordMatch) {
return res.status(401).json({err: 'bad credentials'});
}
const authorizedUser = {...savedUser}; const authorizedUser = {...savedUser};
delete authorizedUser.password; delete authorizedUser.password;
@ -60,6 +61,7 @@ const login = async (req, res, next) => {
signToken(res, authorizedUser); signToken(res, authorizedUser);
res.send('ok').status(200); res.send('ok').status(200);
} }
catch (err) { catch (err) {
res.status(500).json(err); res.status(500).json(err);
} }

View file

@ -0,0 +1,27 @@
const knex = require('../db')
const insertUser = async (user) => {
return await knex('user')
.returning(['username', 'email'])
.insert(user)
.then(queryResults => {
newUser = queryResults[0];
return newUser
});
}
const findUserByNameOrEmail = async (user) => {
if (! user.email && !user.username) return [];
if (!user.email) user.email = '';
if (!user.username) user.username = '';
return await knex('user')
.where({'username': user.username})
.orWhere({'email': user.email})
.select(['username', 'email', 'password'])
}
module.exports = {
insertUser,
findUserByNameOrEmail
}

View file

@ -6,7 +6,6 @@ const saltRounds = process.env.NODE_ENV === 'test' ? 5 : parseInt(process.env.SA
const hashPassword = async (password) => { const hashPassword = async (password) => {
const hashedPassword = await new Promise((resolve, reject) => { const hashedPassword = await new Promise((resolve, reject) => {
bcrypt.hash(password, saltRounds, (err, hash) => { bcrypt.hash(password, saltRounds, (err, hash) => {
console.log(err)
if (err) reject(err) if (err) reject(err)
resolve(hash) resolve(hash)
}); });

View file

@ -26,14 +26,14 @@ const authSignupSpec = (chai, knex, server) => {
'email':'user@example.com' 'email':'user@example.com'
} }
it('post to /signup should return 200 status', done => { it('post to /signup should return 201 status', done => {
chai.request(server) chai.request(server)
.post('/auth/signup') .post('/auth/signup')
.type('form') .type('form')
.send(newUserFormData) .send(newUserFormData)
.end((err, res) => { .end((err, res) => {
if (err) done(err); if (err) done(err);
res.should.status(200); res.should.status(201);
done(); done();
}); });
}); });
@ -142,7 +142,25 @@ const authSignupSpec = (chai, knex, server) => {
}) })
}) })
it('post to /signup with already registered user should return 409 error', done => {
chai.request(server)
.post('/auth/signup')
.type('form')
.send(newUserFormData)
.end((err, res) => {
if (err) done(err);
chai.request(server)
.post('/auth/signup')
.type('form')
.send(newUserFormData)
.end((err, res) => {
if(err) done(err);
res.should.status(409);
done();
})
})
})
} }
module.exports = authSignupSpec; module.exports = authSignupSpec;