Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

998 Passwordless login #1253

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,12 @@ app.use((req, res, next) => {
res.locals.user = req.user;
next();
});
app.use((req, res, next) => {
app.use((req, _res, next) => {
// After successful login, redirect back to the intended page
if (!req.user
&& req.path !== '/login'
&& req.path !== '/signup'
&& !req.path.startsWith('/login/magic-link')
&& !req.path.match(/^\/auth/)
&& !req.path.match(/\./)) {
req.session.returnTo = req.originalUrl;
Expand All @@ -141,6 +142,8 @@ app.use('/webfonts', express.static(path.join(__dirname, 'node_modules/@fortawes
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.post('/login/magic-link', userController.postLoginMagicLink);
app.get('/login/magic-link/:token', userController.getLoginMagicLink);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
Expand Down
121 changes: 119 additions & 2 deletions controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ exports.postSignup = async (req, res, next) => {
* GET /account
* Profile page.
*/
exports.getAccount = (req, res) => {
exports.getAccount = (_req, res) => {
res.render('account/profile', {
title: 'Account Management'
});
Expand Down Expand Up @@ -311,7 +311,7 @@ exports.getReset = async (req, res, next) => {
* GET /account/verify/:token
* Verify email address
*/
exports.getVerifyEmailToken = (req, res, next) => {
exports.getVerifyEmailToken = (req, res) => {
if (req.user.emailVerified) {
req.flash('info', { msg: 'The email address has been verified.' });
return res.redirect('/account');
Expand Down Expand Up @@ -407,6 +407,123 @@ exports.getVerifyEmail = (req, res, next) => {
.catch(next);
};

/**
* POST /login/magic-link
* Sends user a magic link
*/
exports.postLoginMagicLink = async (req, res, next) => {
const { magicLinkEmail } = req.body;
const validationErrors = [];
if (!validator.isEmail(magicLinkEmail)) {
validationErrors.push({ msg: 'Please enter a valid email address.' });
}

const email = validator.normalizeEmail(magicLinkEmail, { gmail_remove_dots: false });

if (validationErrors.length) {
req.flash('errors', validationErrors);
return res.redirect('back');
}

try {
// sends the magic link email
const sendMagicLinkEmail = (user) => {
if (!user) {
return;
}
const token = user.magicLinkToken;
const mailOptions = {
to: user.email,
from: process.env.SITE_CONTACT_EMAIL,
subject: 'Password-less Login Link',
text: `You are receiving this email because you (or someone else) have requested a password-less link to login.\n\n
You can access your account securely by clicking on the following link:\n\n
http://${req.headers.host}/login/magic-link/${token}\n\n
If you did not request this, please ignore this email and your account will remain unchanged.\n`
};
// It is helpful to log the contents of the email in development
const isLocalhost = req.headers.host.includes('localhost');
if (isLocalhost) {
console.log(mailOptions.text);
}
const mailSettings = {
successfulType: 'info',
successfulMsg: 'If the email address you entered exists, you will receive a magic link shortly.',
loggingError: 'ERROR: Could not send magic link email after security downgrade.\n',
errorType: 'errors',
errorMsg: 'Error sending the magic link message. Please try again shortly.',
mailOptions,
req
};
return sendMail(mailSettings);
};

const user = await User.findOne({ email });
if (user) {
const token = await (randomBytesAsync(16).then((buf) => buf.toString('hex')));
user.magicLinkToken = token;
user.magicLinkExpires = Date.now() + 300000; // expires in 5 minutes
await user.save();
await sendMagicLinkEmail(user);
}

return res.redirect('back');
} catch (err) {
return next(err);
}
};

/**
* GET /login/magic-link/:token
* Process token from magic link email and log user in
*/
exports.getLoginMagicLink = async (req, res, next) => {
const { token } = req.params;

if (req.isAuthenticated()) {
req.flash('info', { msg: 'You are already logged in.' });
return res.redirect('/');
}

const validationErrors = [];
if (!validator.isHexadecimal(token)) validationErrors.push({ msg: 'Invalid Token. Please retry.' });

if (validationErrors.length) {
req.flash('errors', validationErrors);
return res.redirect('back');
}

try {
const user = await User.findOne({
magicLinkToken: token,
magicLinkExpires: { $gt: Date.now() }
});

if (!user) {
req.flash('errors', { msg: 'Magic link is invalid or has expired.' });
return res.redirect('/login');
}

user.magicLinkToken = undefined;
user.magicLinkExpires = undefined;
if (!user.emailVerified) {
user.emailVerificationToken = '';
user.emailVerified = true;
}
await user.save();

req.logIn(user, (err) => {
if (err) {
return next(err);
}
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect(req.session.returnTo || '/');
});
} catch (err) {
return next(err);
}
};

/**
* POST /reset/:token
* Process the reset password request.
Expand Down
2 changes: 2 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: { type: String, unique: true },
password: String,
magicLinkToken: String,
magicLinkExpires: Date,
passwordResetToken: String,
passwordResetExpires: Date,
emailVerificationToken: String,
Expand Down
18 changes: 18 additions & 0 deletions views/account/login.pug
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@ block content
i.far.fa-user.fa-sm.iconpadding
| Login
a.btn.btn-link(href='/forgot') Forgot your password?
.form-group
.offset-md-3.col-md-7.pl-2
.pt-2.pb-2 OR
form(method='POST', action='/login/magic-link')
input(type='hidden', name='_csrf', value=_csrf)
.form-group.mb-3
.offset-md-3.col-md-7.pl-2
.help-block.text-muted.small
| We'll email you a link if an account is found for a password-less login.
.form-group.row.mb-3
label.col-md-3.col-form-label.font-weight-bold.text-right.hidden(for='magicLinkEmail')  
.col-md-7
input.form-control(type='email', name='magicLinkEmail', id='magic-email', placeholder='Email', autofocus, autocomplete='email', required)
.form-group
.offset-md-3.col-md-7.pl-2
button.btn.btn-primary(type='submit')
i.far.fa-sm.fa-envelope.iconpadding
| Send Magic Link
.form-group
.offset-md-3.col-md-7.pl-2
hr
Expand Down