node-go/packages/play-node-go/server/controllers/auth.js

63 lines
1.5 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');
2020-01-15 07:09:01 +00:00
const { validateSignup, validateLogin } = require('../services/userValidate');
2020-01-10 01:44:58 +00:00
2020-01-15 07:09:01 +00:00
const signup = async (req, res, next) => {
const user = req.body;
2020-01-15 07:09:01 +00:00
if (!validateSignup(user)) return;
try {
2020-01-14 22:22:42 +00:00
const hashedPassword = await hashPassword(user.password);
const secureUser = { ...user, password: hashedPassword }
2020-01-14 20:06:25 +00:00
knex('user')
2020-01-14 22:22:42 +00:00
.insert(secureUser)
.then(queryResults => {
const newUser = queryResults[0];
signToken(res, newUser);
res.send('ok').status(200);
})
}
catch (err) {
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) => {
const user = req.body;
if (!validateLogin(user)) return;
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
}