56 lines
2.0 KiB
JavaScript
56 lines
2.0 KiB
JavaScript
|
|
const express = require('express');
|
||
|
|
const router = express.Router();
|
||
|
|
const registerValidator = require('../validators/register');
|
||
|
|
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 | Register';
|
||
|
|
|
||
|
|
router.get('/register', authMw.AllowIfNotAuthenticated, async (req, res) => {
|
||
|
|
res.render('register', { title: pageTitle, csrfToken: req.csrfToken() });
|
||
|
|
});
|
||
|
|
|
||
|
|
router.post('/register', authMw.AllowIfNotAuthenticated, async (req, res, next) => {
|
||
|
|
const reqBody = req.body;
|
||
|
|
const validationResult = registerValidator.test(reqBody);
|
||
|
|
const validationError = validationResult.error;
|
||
|
|
let errors = [];
|
||
|
|
|
||
|
|
if(validationError !== undefined)
|
||
|
|
errors = validationError.details;
|
||
|
|
|
||
|
|
try {
|
||
|
|
if(errors.length === 0) {
|
||
|
|
const hashedPassword = await pwMw.HashPassword(reqBody.register_password);
|
||
|
|
const result = await dbConnection.transaction(async(t) => {
|
||
|
|
const user = await database.models.User.create({
|
||
|
|
username: reqBody.register_username,
|
||
|
|
password: hashedPassword,
|
||
|
|
}, {transaction: t});
|
||
|
|
|
||
|
|
return user;
|
||
|
|
});
|
||
|
|
|
||
|
|
if(result !== undefined) {
|
||
|
|
await authMw.CreateSession(req, result);
|
||
|
|
return res.redirect('/');
|
||
|
|
} else {
|
||
|
|
errors.push({message: 'Failed to create user.'})
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} catch(error) {
|
||
|
|
if(error instanceof Sequelize.UniqueConstraintError) {
|
||
|
|
errors.push({message: 'Username is in use.'});
|
||
|
|
} else {
|
||
|
|
error.status = 500;
|
||
|
|
return next(error);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// if we're here we failed, I specify true for csrfToken to force reset it
|
||
|
|
return res.render('register', {title: pageTitle, errors: errors, csrfToken: req.csrfToken(true) });
|
||
|
|
});
|
||
|
|
|
||
|
|
module.exports = router;
|