63 lines
2.1 KiB
JavaScript
63 lines
2.1 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const loginValidator = require('../validators/login');
|
|
const authMw = require('../session');
|
|
const pwMw = require('../password.js');
|
|
const database = require('../database.js');
|
|
const dbConnection = database.db;
|
|
const Sequelize = require('sequelize');
|
|
const pageTitle = 'Domain Manager | Login';
|
|
|
|
router.get('/login', authMw.AllowIfNotAuthenticated, async (req, res) => {
|
|
res.render('login', { title: pageTitle, csrfToken: req.csrfToken() });
|
|
});
|
|
|
|
router.post('/login', authMw.AllowIfNotAuthenticated, async (req, res, next) => {
|
|
const reqBody = req.body;
|
|
const validationResult = loginValidator.test(reqBody);
|
|
const validationError = validationResult.error;
|
|
let errors = [];
|
|
|
|
if(validationError !== undefined)
|
|
errors = validationError.details;
|
|
|
|
try {
|
|
if(errors.length === 0) {
|
|
const result = await dbConnection.transaction(async(t) => {
|
|
const user = database.models.User.findOne({
|
|
where: {
|
|
username: reqBody.login_username
|
|
},
|
|
transaction: t
|
|
});
|
|
|
|
return user;
|
|
});
|
|
|
|
if(result) {
|
|
const doesPasswordMatch = await pwMw.TestPassword(reqBody.login_password, result.password);
|
|
if(doesPasswordMatch === true) {
|
|
await authMw.CreateSession(req, result);
|
|
return res.redirect('/');
|
|
} else {
|
|
errors.push({message: 'Invalid username or password.'});
|
|
}
|
|
} else {
|
|
errors.push({message: 'Invalid username or password.'});
|
|
}
|
|
}
|
|
} catch(error) {
|
|
error.status = 500;
|
|
return next(error);
|
|
}
|
|
|
|
return res.render('login', {title: pageTitle, errors: errors, csrfToken: req.csrfToken(true) });
|
|
});
|
|
|
|
router.post('/logout', authMw.AllowIfAuthenticated, async (req, res, next) => {
|
|
// Just destroy the session
|
|
req.session.destroy();
|
|
return res.redirect('/');
|
|
});
|
|
|
|
module.exports = router; |