p5.js-web-editor/server/config/passport.js

147 lines
4.6 KiB
JavaScript
Raw Normal View History

import User from '../models/user';
const lodash = require('lodash');
const passport = require('passport');
const GitHubStrategy = require('passport-github').Strategy;
const LocalStrategy = require('passport-local').Strategy;
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
/**
* Sign in using Email/Username and Password.
*/
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findByMailOrName(email.toLowerCase())
2018-05-05 00:22:39 +00:00
.then((user) => { // eslint-disable-line consistent-return
if (!user) {
return done(null, false, { msg: `Email ${email} not found.` });
}
2018-05-05 00:22:39 +00:00
user.comparePassword(password, (innerErr, isMatch) => {
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: 'Invalid email or password.' });
});
})
.catch(err => done(null, false, { msg: err }));
}));
/*
Input:
[
{ value: 'email@example.com', primary: false, verified: true },
{ value: 'unverified@example.com', primary: false, verified: false }
]
Output:
['email@example.com']
*/
const getVerifiedEmails = githubEmails => (
(githubEmails || [])
.filter(item => item.verified === true)
.map(item => item.value)
);
const getPrimaryEmail = githubEmails => (
(
lodash.find(githubEmails, { primary: true }) || {}
).value
);
/**
* Sign in with GitHub.
*/
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
callbackURL: '/auth/github/callback',
passReqToCallback: true,
scope: ['user:email'],
}, (req, accessToken, refreshToken, profile, done) => {
User.findOne({ github: profile.id }, (findByGithubErr, existingUser) => {
if (existingUser) {
done(null, existingUser);
return;
}
const emails = getVerifiedEmails(profile.emails);
const primaryEmail = getPrimaryEmail(profile.emails);
User.findOne({
email: { $in: emails },
}, (findByEmailErr, existingEmailUser) => {
if (existingEmailUser) {
existingEmailUser.email = existingEmailUser.email || primaryEmail;
existingEmailUser.github = profile.id;
existingEmailUser.username = existingEmailUser.username || profile.username;
existingEmailUser.tokens.push({ kind: 'github', accessToken });
existingEmailUser.name = existingEmailUser.name || profile.displayName;
Email verification (#369) * Re-introduce Email Verification code Revert "Revert "Email verification"" This reverts commit d154d8bff259350523a0f139e844db96c43d2ee1. * Uses MJML to generate Reset Password email * Sends Password Reset and Email Confirmation emails using MJML template * Sends verified status along with user data * API endpoint for resending email verification confirmation * Displays verification status on Account page and allows resending * Send back error string * Passes email address through to sign/verify helper * Uses enum-style object to set verified state * Sends minimal info when user verifies since it can be done without login * Provides /verify UI and sends confirmation token to API * Better name for JWT secret token env var * Adds mail config variables to Readme * Encrypts email address in JWT The JWT sent as the token in the Confirm Password URL can be unencoded by anyone, although it's signature can only be verified by us. To ensure that no passwords are leaked, we encrypt the email address before creating the token. * Removes unused mail templates * Resets verified flag when email is changed and sends another email * Moves email confirmation functions next to each other * Extracts random token generator to helper * Moves email confirmation actions into Redux - updates the AccountForm label with a message to check inbox - show status when verifying email token * Uses generated token stored in DB for email confirmation * Sets email confirmation status to verified if logging in from Github * Sends email using new method on account creation * Fixes linting errors * Removes replyTo config
2017-06-26 16:48:28 +00:00
existingEmailUser.verified = User.EmailConfirmation.Verified;
existingEmailUser.save(saveErr => done(null, existingEmailUser));
} else {
const user = new User();
user.email = primaryEmail;
user.github = profile.id;
user.username = profile.username;
user.tokens.push({ kind: 'github', accessToken });
user.name = profile.displayName;
Email verification (#369) * Re-introduce Email Verification code Revert "Revert "Email verification"" This reverts commit d154d8bff259350523a0f139e844db96c43d2ee1. * Uses MJML to generate Reset Password email * Sends Password Reset and Email Confirmation emails using MJML template * Sends verified status along with user data * API endpoint for resending email verification confirmation * Displays verification status on Account page and allows resending * Send back error string * Passes email address through to sign/verify helper * Uses enum-style object to set verified state * Sends minimal info when user verifies since it can be done without login * Provides /verify UI and sends confirmation token to API * Better name for JWT secret token env var * Adds mail config variables to Readme * Encrypts email address in JWT The JWT sent as the token in the Confirm Password URL can be unencoded by anyone, although it's signature can only be verified by us. To ensure that no passwords are leaked, we encrypt the email address before creating the token. * Removes unused mail templates * Resets verified flag when email is changed and sends another email * Moves email confirmation functions next to each other * Extracts random token generator to helper * Moves email confirmation actions into Redux - updates the AccountForm label with a message to check inbox - show status when verifying email token * Uses generated token stored in DB for email confirmation * Sets email confirmation status to verified if logging in from Github * Sends email using new method on account creation * Fixes linting errors * Removes replyTo config
2017-06-26 16:48:28 +00:00
user.verified = User.EmailConfirmation.Verified;
user.save(saveErr => done(null, user));
}
});
});
}));
/**
* Sign in with Google.
*/
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: '/auth/google/callback',
passReqToCallback: true,
scope: ['email'],
}, (req, accessToken, refreshToken, profile, done) => {
User.findOne({ google: profile._json.emails[0].value }, (findByGoogleErr, existingUser) => {
if (existingUser) {
done(null, existingUser);
return;
}
const primaryEmail = profile._json.emails[0].value;
User.findOne({
email: primaryEmail,
}, (findByEmailErr, existingEmailUser) => {
if (existingEmailUser) {
existingEmailUser.email = existingEmailUser.email || primaryEmail;
existingEmailUser.google = profile._json.emails[0].value;
existingEmailUser.username = existingEmailUser.username || profile._json.emails[0].value;
existingEmailUser.tokens.push({ kind: 'google', accessToken });
existingEmailUser.name = existingEmailUser.name || profile._json.displayName;
existingEmailUser.verified = User.EmailConfirmation.Verified;
existingEmailUser.save(saveErr => done(null, existingEmailUser));
} else {
const user = new User();
user.email = primaryEmail;
user.google = profile._json.emails[0].value;
user.username = profile._json.emails[0].value;
user.tokens.push({ kind: 'google', accessToken });
user.name = profile._json.displayName;
user.verified = User.EmailConfirmation.Verified;
user.save(saveErr => done(null, user));
}
});
});
}));