Added user model; added pages to register a new account, login and logout; added middleware to process whether a user is logged in or not
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
This commit is contained in:
58
src/routes/auth.js
Normal file
58
src/routes/auth.js
Normal file
@ -0,0 +1,58 @@
|
||||
const db = require('../models');
|
||||
const User = db.users;
|
||||
const crypto = require('crypto');
|
||||
|
||||
// GET - /auth/login
|
||||
exports.getLogin = async function(req, res) {
|
||||
res.render('auth/login.twig');
|
||||
};
|
||||
|
||||
// POST - /auth/login
|
||||
exports.postLogin = async function(req, res) {
|
||||
const user = await User.findAll({
|
||||
where: {
|
||||
username: req.body.login_username,
|
||||
},
|
||||
});
|
||||
|
||||
const attemptedKey = crypto.pbkdf2Sync(req.body.login_password, user[0].salt, 10000, 64, 'sha512');
|
||||
const attemptedHash = attemptedKey.toString('hex');
|
||||
|
||||
if (attemptedHash == user[0].password) {
|
||||
req.session.user = user[0].id;
|
||||
res.redirect('/');
|
||||
} else {
|
||||
res.redirect('/auth/login');
|
||||
}
|
||||
}
|
||||
|
||||
// GET - /auth/register
|
||||
exports.getRegister = async function(req, res) {
|
||||
res.render('auth/register.twig');
|
||||
};
|
||||
|
||||
// POST - /auth/register
|
||||
exports.postRegister = async function(req, res) {
|
||||
const passwordSalt = crypto.randomBytes(32).toString('base64');
|
||||
const passwordKey = crypto.pbkdf2Sync(req.body.register_password, passwordSalt, 10000, 64, 'sha512');
|
||||
const passwordHash = passwordKey.toString('hex');
|
||||
|
||||
const user = await User.create({
|
||||
username: req.body.register_username,
|
||||
password: passwordHash,
|
||||
salt: passwordSalt,
|
||||
email: req.body.register_email,
|
||||
firstName: req.body.register_first_name,
|
||||
lastName: req.body.register_last_name,
|
||||
});
|
||||
|
||||
res.redirect('/');
|
||||
};
|
||||
|
||||
// GET - /auth/logout
|
||||
exports.getLogout = async function(req, res) {
|
||||
// destroy the user's session
|
||||
req.session.destroy();
|
||||
|
||||
res.redirect('/');
|
||||
}
|
Reference in New Issue
Block a user