app.js
var express=require('express');
var app=express();
var port=process.env.PORT || 3000;
var mongoose=require('mongoose');
var passport=require('passport');
var session = require('express-session');
mongoose.connect('mongodb://localhost:27017/myapp');
require('./config/passport')(passport);
var User = require('./models/user');
app.set('view engine', 'ejs');
app.use(session({ secret: '1234567' ,
saveUninitialized: true,
resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/profile/:provider', isLoggedIn, function(req, res) {
console.log(req.user);
res.render('profile.ejs', {
provider:req.params.provider,
user : req.user // get the user out of session and pass to template
});
});
app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/profile/google',
failureRedirect : '/'
}));
// route for logging out
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
app.listen(port);
passport.js
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var User = require('../models/user');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID : 'clientID',
clientSecret : 'clientSecret',
callbackURL : 'http://localhost:3000/auth/google/callback',
},
function(token, refreshToken, profile, done) {
process.nextTick(function() {
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, user);
} else {
var newUser = new User();
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value; // pull the first email
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};