Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const GoogleStrategy = require('passport-google-oauth20').Strategy
const User = require('../db/models/user')
const strategy = new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
},
function(token, refreshToken, profile, done) {
// testing
console.log('===== GOOGLE PROFILE =======')
console.log(profile)
console.log('======== END ===========')
// code
const { id, name, email } = profile
User.findOne({ googleId: id }, (err, userMatch) => {
// handle errors here:
if (err) {
console.log('Error!! trying to find user with googleId')
return {
id: profile.id,
displayName: profile.displayName,
image: imageUrl
};
}
// Configure the Google strategy for use by Passport.js.
//
// OAuth 2-based strategies require a `verify` function which receives the
// credential (`accessToken`) for accessing the Google API on the user's behalf,
// along with the user's profile. The function must invoke `cb` with a user
// object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(new GoogleStrategy({
clientID: config.OAUTH2_CLIENT_ID,
clientSecret: config.OAUTH2_CLIENT_SECRET,
callbackURL: config.OAUTH2_CALLBACK,
accessType: 'offline'
}, (accessToken, refreshToken, profile, cb) => {
// Extract the minimal profile information we need from the profile object
// provided by Google
console.log('oauth2.js: passport.use cb', accessToken, refreshToken, profile);
cb(null, extractProfile(profile));
}));
passport.serializeUser((user, cb) => {
console.log('oauth2.js: serializeUser');
cb(null, user);
});
if (err) {
return done(err)
}
if (isMatch) {
debug('passport: Login isMatch')
return done(null, user)
} else {
debug('passport: Invalid Email or Password')
return done(null, false, { message: 'Invalid email or password.' })
}
})
})
})
if (googleOauth2Enabled) {
// Sign in using google oauth2
exports.googleStrategy = new GoogleStrategy({
clientID: env.google.clientId,
clientSecret: env.google.clientSecret,
callbackURL: env.google.redirectUrl
}, function (accessToken, refreshToken, profile, cb) {
var User = mongoose.model('users')
var email = profile.emails[0].value
User.findOne({
email: email
}, function (err, user) {
if (err) {
debug('passport: Error ' + err)
return cb(err)
}
if (!user) {
User.create({
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const config = require('../lib/config');
passport.use(
new GoogleStrategy(
{
clientID: config.get('OAUTH2_CLIENT_ID'),
clientSecret: config.get('OAUTH2_CLIENT_SECRET'),
callbackURL: '/auth/google/callback',
accessType: 'offline',
},
(request, accessToken, refreshToken, profile, done) => {
const { email } = profile._json; // eslint-disable-line no-underscore-dangle
done(null, email);
},
),
);
passport.serializeUser((email, done) => {
done(null, email);
});
return {
id: profile.id,
displayName: profile.displayName,
image: imageUrl,
};
}
// Configure the Google strategy for use by Passport.js.
//
// OAuth 2-based strategies require a `verify` function which receives the
// credential (`accessToken`) for accessing the Google API on the user's behalf,
// along with the user's profile. The function must invoke `cb` with a user
// object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(
new GoogleStrategy(
{
clientID: config.get('OAUTH2_CLIENT_ID'),
clientSecret: config.get('OAUTH2_CLIENT_SECRET'),
callbackURL: config.get('OAUTH2_CALLBACK'),
accessType: 'offline',
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
},
(accessToken, refreshToken, profile, cb) => {
// Extract the minimal profile information we need from the profile object
// provided by Google
cb(null, extractProfile(profile));
}
)
);
passport.serializeUser((user, cb) => {
this.authMethodConfig = authMethodConfig;
// Verify configuration
if (!authMethodConfig.clientId)
throw new Error(`Google auth method "${authMethodId}": In auth method configuration, property "config", the property "clientId" is missing.`);
if (!authMethodConfig.clientSecret)
throw new Error(`Google auth method "${authMethodId}": In auth-server configuration, property "config", the property "clientSecret" is missing.`);
// Assemble the callback URL
const callbackUrl = `${options.externalUrlBase}/${authMethodId}/callback`;
info(`Google Authentication: Expected callback URL: ${callbackUrl}`);
this.baseAuthenticateSettings = {
session: false,
scope: ['profile', 'email']
};
const googleStrategy = new GoogleStrategy({
clientID: authMethodConfig.clientId,
clientSecret: authMethodConfig.clientSecret,
callbackURL: callbackUrl
}, this.verifyProfile);
googleStrategy.authorizationParams = this.authorizationParams;
// Configure passport
passport.use(authMethodId, googleStrategy);
// this.authenticateWithGoogle = passport.authenticate(authMethodId, authenticateSettings);
// this.authenticateCallback = passport.authenticate(authMethodId, authenticateSettings);
this.genericFlow.initIdP(this);
}
email: data.email,
lastLogin: Date.now(),
[providerName]: {
id: data.id,
accessToken: data.accessToken
}
})
// init the passport junk
const strategyConfig = {
clientID: config[providerName].id,
clientSecret: config[providerName].secret,
callbackURL: `/auth/${providerName}/callback`
}
const strategy = new Strategy(strategyConfig, findOrCreateUser(dataToUser))
passport.use(strategy)
// init the router
const start = passport.authenticate(providerName, {
scope: config[providerName].scope
})
const callback = passport.authenticate(providerName, {
failureRedirect: '/login'
})
const router = Router({ mergeParams: true })
router.get(`/auth/${providerName}/start`, redirect.pre, start)
router.get(`/auth/${providerName}/callback`, callback, redirect.post)
export default router
var auth = (request, callback) => {
var host = request.headers.host[0].value;
var query = querystring.parse(request.querystring);
var opts = {
clientID: Params.OAuthClientId,
clientSecret: Params.OAuthClientSecret,
callbackURL: `https://${host}/auth`,
};
var s = new GoogleStrategy(opts, (token, tokenSecret, profile, done) => {
profile.emails.forEach((email) => {
if (email.value.endsWith(Params.AuthDomainName)) {
return done(null, profile); // call success with profile
}
});
// call fail with warning
done(null, false, {
name: "UserError",
message: "Email is not a member of the domain",
status: "401",
});
});
s.error = (err) => {
callback(null, responseError(err));
static GoogleStrategy({clientID, clientSecret, callbackURL}) {
const googleStrategy = new GoogleStrategy(
{clientID, clientSecret, callbackURL},
(accessToken, refreshToken, profile, next) => {
// @todo this might not working yet..
User.findOrCreate({googleId: profile.id}, (err, user) => next(err, user));
}
);
passport.use(googleStrategy);
}
}
module.exports = (passport) => {
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
passport.use(new GoogleOAuthStrategy(
{
clientID: config.oAuthClientID,
clientSecret: config.oAuthclientSecret,
callbackURL: config.oAuthCallbackUrl,
// Set the correct profile URL that does not require any additional APIs
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo'
},
(token, refreshToken, profile, done) => done(null, {profile, token})));
};