const testPassword = require('model').PasswordField.testSync; const User = require('./models.js'); const getUrl = require('create-url').getUrl; const mail = require('mail'); const pug = require('pug'); const config = require('settings/config'); module.exports.redirectIfNotLogged = function(redirectionPage, toDecorate) { return function(req, res, render) { if (req.session.user === undefined) { req.session.redirectAfterLog = redirectionPage; req.session.save(); res.redirect(getUrl('login')); return; } return toDecorate(...arguments); }; } module.exports.login = function(req, res, render) { render('login.pug'); } module.exports.signup = function(req, res, render) { render('signup.pug'); } module.exports.logout = function(req, res, render) { req.session.user = undefined; req.session.save(); res.redirect(getUrl("index")); } module.exports.loginTarget = function(req, res, render) { User.getByUsername(req.body.username, (err, user) => { if (user === undefined || !user.active) { res.redirect(getUrl('login')); } else { if (testPassword(req.body.password, user.password)) { req.session.user = user; let redirection = req.session.redirectAfterLog || 'index'; req.session.redirectAfterLog = undefined; req.session.save(); res.redirect(getUrl(redirection)); } else { res.redirect(getUrl('login')); } } }); } module.exports.signupTarget = function(req, res, render) { let user = new User(); user.username = req.body.username; user.email = req.body.email; user.password = req.body.password; require('crypto').randomBytes(48, function(err, buffer) { user.activationKey = buffer.toString('hex'); user.save((err) => { res.locals.user = user; let baseUrl = req.headers.referer.split('/').slice(0, 3).join('/') + '/' res.locals.activationUrl = baseUrl + 'activate/' + user.activationKey; let html = pug.renderFile( __dirname + '/templates/validation-mail.pug', res.locals, ); mail({ from: config.MAIL.FROM, to: user.username + ' <' + user.email + '>', subject: 'Welcome on ADEjs!', text:'', attachment: [ {data: html, alternative: true} ] }, (err, result) => { res.redirect(getUrl('mailWasSent')); }); }); }); } module.exports.mailWasSent = function(req, res, render) { render('mailWasSent.pug'); } module.exports.activate = function(req, res, render, next) { User.getByActivationKey(req.params.activationKey, (err, user) => { if (user === undefined) { return next(); } user.active = true; user.activationKey = undefined; user.save((err, user) => { req.session.user = user; req.session.save(); res.redirect(getUrl('index')); }); }); }