ReferenceError: User is not defined - javascript

I've got an error while i try to auth via vkontakte (vk.com) (passport-vkontakte)
Error: ReferenceError: User is not defined
Here is my auth.js
var express = require('express');
var passport = require('passport'), VKontakteStrategy = require('passport-vkontakte').Strategy;
var router = express.Router();
var app = express();
router.get('/', function(req, res) {
res.send('Auth');
});
passport.use(new VKontakteStrategy({
clientID: 000, // VK.com docs call it 'API ID'
clientSecret: '***',
callbackURL: "http://127.0.0.1:3000/auth/vkontakte/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ vkontakteId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
router.get('/vkontakte',
passport.authenticate('vkontakte'),
function(req, res){
// The request will be redirected to vk.com for authentication, so
// this function will not be called.
});
router.get('/vkontakte/callback',
passport.authenticate('vkontakte', { failureRedirect: '/' }),
function(req, res) {
// Successful authentication, redirect home.
var User = req.User;
res.redirect('/');
});
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
module.exports = router;
Express ver: 4

Define User Model
Mongoose or Mongoskin Example
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
});
var Post = mongoose.model('ModelName', BlogPost);
Post.findOrCreate({ id: QUERY }, function (err, docs) {
});
You need to create a model so your strategy can interact with your application properly. In your case, this model will be for users so it is appropriately named User as an entity.
Boilerplate Code to Get You Started
This code was added from the strategy developers to get you started.
User.findOrCreate({ vkontakteId: profile.id }, function (err, user) {
return done(err, user);
});
It's the same concept, hope this clears things up.

Related

passport local for a node.js app with multiple route files

I've successfully followed this Tutorial and made my Node.js based app.
Now I want to add passport-local support to login for some specific routes. Every tutorial I've found regarding using Passport is for applications with only one route file. but I have my routes in multiple files (in app.js) :
var index = require('./routes/index');
var config = require('./routes/config');
var about = require('./routes/about');
var run = require('./routes/run');
var device = require('./routes/device');
var user = require('./routes/user');
For example in routes/config.js:
router.get('/', server_controller.index);
router.get('/server/create', server_controller.server_create_get);
router.post('/server/create', server_controller.server_create_post);
router.get('/server/:id/delete', server_controller.server_delete_get);
router.post('/server/:id/delete', server_controller.server_delete_post);
and in routes/device.js we have routes that need login:
router.get('/', device_controller.index);
router.get('/change-ip', device_controller.device_edit_ip_get);
router.post('/change-ip', device_controller.device_edit_ip_post);
So how should I use passport-local middle-ware in these different route files?
Update:
in routes/user.js I've defined passport local strategy.
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
router.get('/login', function(req, res, next) {
res.render('login.pug' ,{
title : "Login Page"
});
});
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('local-login' ,new LocalStrategy({
usernameField : 'uname',
passwordField : 'password'
},
function (uname , password , done) {
User.findOne({ uname : uname } , function (err , user) {
if(err) { return done(err); }
if(!user) {
return done(null,false,{});
}
if(! User.validPassword(password , user.password)) {
return done(null , false , {});
}
return done(null , user);
});
}
));
router.post('/login' , function (req ,res , next) {
var uname = req.body.uname;
var password = req.body.password;
req.checkBody('uname' , 'The user-name field is required').notEmpty();
req.checkBody('password' , 'The password field is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('login.pug' , {
title : 'Login Page',
errors : errors
});
return;
}
next();
} , passport.authenticate('local-login' ,
{ failureRedirect: '/user/login' ,
successRetrunToOrRedirect: '/device'
}), function (req, res) {
console.log('login success');
res.redirect('/device');
});
module.exports = router;
And then in other route files I've defined isLoggedIn() function and used it, for example in routes/devics.js:
router.get('/', isLoggedIn, device_controller.index);
router.get('/change-ip', isLoggedIn, device_controller.device_edit_ip_get);
router.post('/change-ip', isLoggedIn, device_controller.device_edit_ip_post);
router.get('/change-password', isLoggedIn, device_controller.device_change_pw_get);
router.post('/change-password', isLoggedIn, device_controller.device_change_pw_post);
function isLoggedIn(req , res , next) {
if(req.isAuthenticated()) {
next();
return;
}
res.redirect('/user/login');
}
or in routes/config.js again I've defined isLoggedIn() and added where ever I needed authentication:
router.get('/', isLoggedIn, server_controller.index);
router.get('/server/create', isLoggedIn, server_controller.server_create_get);
router.post('/server/create', isLoggedIn, server_controller.server_create_post);
function isLoggedIn(req , res , next) {
if(req.isAuthenticated()) {
next();
return;
}
res.redirect('/user/login');
}
It works fine, but I'm sure that it is not the right/best way to do it!

Node JS + Passport login

I'm trying to configure my first node js app to login using passport.
So first things first. I create a /app/config/express.js file to configure express stuff. So my app.js is simpler:
var app = require('./app/config/express')();
app.listen(3001, function(){
console.log("Servidor rodando");
});
Ok... that's cool. BUT! My express.js file is too big. Maybe you can give me some tips on how to refactor this?
I added some comments with some questions that I would love to make this code better.
var express = require('express');
var load = require('express-load');
var expressValidator = require('express-validator');
var bodyParser = require('body-parser');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var session = require('express-session');
var flash = require("connect-flash");
module.exports = function() {
// PLEASE READ 1
//
//
// Functions to organize code better.
// PS: if this functions are outside "module.exports", then Express
// doesnt 'inject' the 'app.infra' variable ....
// Is there a workaround to move these functions outta here?
//
//
function configureAuth(){
passport.use(new Strategy({
passReqToCallback : true
},
function(req, username, password, cb) {
var connection = app.infra.connectionFactory();
var userDao = new app.infra.dao.UserDao(connection);
userDao.login(username, password, function(err, user){
if (err) {
return cb(err);
}
if (!user) {
return cb(null, false);
}
return cb(null, user);
});
connection.end();
}));
//
//
// HERE IT IS!
//
//
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
passport.deserializeUser(function(id, cb) {
cb(null, user);
});
}
function configureExpressLibs(app){
app.set('view engine', 'ejs');
app.set('views','./app/views');
app.use('/static', express.static('./app/public'));
app.use(flash());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(session({
secret: '086this 54is 23unkowned 67',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
}
function configureErrors(app){
app.use(function(err, req, res, next) {
console.error(err.stack)
next(err)
});
app.use(function(req,res,next){
res.status(404).render('errors/404');
next();
});
app.use(function(error, req,res,next){
res.status(500).render('errors/500');
next();
});
}
// PLEASE READ 2
//
//
// I've moved this to 'LoginController.js' in my routes folder but
// I didnt work... So I moved it here. Is there a work around?
//
//
function configureLoginRoutes(app){
function redirectToIndexIfLoggedIn(req, res, next) {
if (req.isAuthenticated())
res.redirect('/');
return next();
}
app.get('/login', redirectToIndexIfLoggedIn, function(req, res){
res.render('login/login');
});
app.post('/login', passport.authenticate('local', {
successRedirect : '/',
failureRedirect : '/login',
failureFlash : 'Invalid username or password.'
}));
app.get('/logout', function(req, res){
req.logout();
req.session.destroy();
res.redirect('/');
});
}
var app = express();
configureExpressLibs(app);
configureAuth();
configureLoginRoutes(app);
load('routes',{cwd: 'app'})
.then('infra')
.into(app);
configureErrors(app);
return app;
}
So the problem now is, when I login (it doesnt matter if the user is correct or wrong), I get a:
Error: Failed to serialize user into session
I googled it and saw the the reason for this is because people forgot to implement "serializeUser". But I did. Please check the comment with "HERE IT IS" on the code above.
Thanks guys.
Sorry for the big code. But I'm learning and I hope to make things better with your help.
EDIT My deserialize method was wrong. I fixed it using:
passport.deserializeUser(function(id, cb) {
var connection = app.infra.connectionFactory();
var userDao = new app.infra.dao.UserDao(connection);
userDao.findById(id, function(err, user) {
done(err, user);
});
connection.end();
});
but the application still fails. Same error.
EDIT SOLUTION
Turns out my implementation was wrong. You see, mysql always returns an array. Thus I corrected my code like this:
function(req, username, password, cb) {
var connection = app.infra.connectionFactory();
var userDao = new app.infra.dao.UserDao(connection);
userDao.login(username, password, function(err, user){
if (err) {
return cb(err);
}
if (!user) {
return cb(null, false);
}
// HERE
return cb(null, user[0]);
});
connection.end();
}));
And here:
passport.deserializeUser(function(id, cb) {
var connection = app.infra.connectionFactory();
var userDao = new app.infra.dao.UserDao(connection);
userDao.findById(id, function(err, user) {
// HERE
cb(err, user[0]);
});
connection.end();
});
}
I think your this.user is not setting inside deserializeUser when you call cb(null,user) so create your own middleware after app.use(passport.session()) to put it in this.user like so:
app.use(function * setUserInContext (next) {
this.user = this.req.user
yield next
})
Cheers :)

post data not being recognized node js

Here is my index.js file...
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'QChat' });
});
router.post('/login', function(req, res) {
console.log("processing");
res.send('respond with a resource');
});
module.exports = router;
And here is the code I am using to stored POST data into my mongoDB database. This is located in my app.js file...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
var Schema = mongoose.Schema;
db.on('error', console.error);
db.once('open', function() {
console.log("connected");
var Schema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('emp', Schema);
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Code works fine up until it reaches the app.post, after that it does not seem to read the rest of the code.
I know my index.js file works because when I submit the form, I get to a page that displays respond with a resource (because of the send function). But for some reason, app.post is not being read, am I missing something?
Here is my jade html to show that I am implementing everything correctly...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
input(type="submit",name = "homePage" class ="loginButton" value="Log In" id="loginButton")
Please try to move the following code out of db.once('open')
db.on('error', console.error);
db.once('open', function() {});
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Another issue in your code, please make sure the first parameter of mongoose.model is User, otherwise, one error could pop up.
var UserSchema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('User', UserSchema);

passportjs local strategy not getting called

I am using express and passport to build a rest api backend and it seems that my localStrategy is not getting called on request.
The entry point of my application looks like the following:
app.js
var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/config');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({extended:true}));
app.use(passport.initialize());
//connect to mongodb
mongoose.connect(config.db, options);
//load models (shorten forEach)
...
require(__dirname + '/models/' + file)(mongoose);
//load passport config
require('./config/passport')(mongoose, passport);
//load routes
require('./config/routes')(app, passport);
//start server
var server = app.listen(3000, ....
routes.js
...
app.post('/auth', function(req, res){
console.log("reached auth endpoint");
console.log(req.body);
passport.authenticate('local', { session: false}, function(err, user, info){
console.log("Test:"+user);
if(err) {
console.log("Error1");
return next(err)}
if(!user){
console.log("Error2");
return res.json(401, {error: 'Auth Error!'});
}
console.log("Error3");
var token = jwt.encode({ username: user.email }, "hanswurst");
res.json({token: token});
}),
function(req, res){
console.log("passport user", req.user);
};
});
passport.js
...
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(email, password, done){
console.log("TEST");
User.findOne({'email': email}, function(err, user){
if(err){
console.log("Unknown error");
return done(err);
}
if(!user){
console.log("No User found");
return done(null, false);
}
if(!user.validPassword(password)){
console.log("Password was incorrect");
return done(null, false);
}
console.log("User was found");
return done(null, user);
});
}
));
The only result i get on form request is
reached auth endpoint
{ email: 'test#mail.com', password: 'secret' }
POST /auth - - ms - -
For me the request body looks fine and it should enter my LocalStrategy. I am bit helpless as i am not getting any other console output from this point.
First off, you have some basic javascript syntax errors in routes.js. This part right here (lots of code removed for clarity) is broken:
passport.authenticate(/*...*/), function(req, res) {/*..*/};
It might have been that you just added some console.log calls in the wrong place. To clear up the confusion, passport.authenticate() does not perform the authentication right away, what it does is return a middleware for you. You would use it like this for example :
var middleware = passport.authenticate(...);
app.post('/auth', middleware);
So to fix your problem, try invoking the middleware returned by authenticate right away, like this:
app.post('/auth', function(req, res, next) {
console.log("reached auth endpoint");
console.log(req.body);
passport.authenticate('local', {
session: false
}, function(err, user, info) {
console.log("Test:" + user);
if (err) {
console.log("Error1");
return next(err);
}
if (!user) {
console.log("Error2");
return res.json(401, {
error: 'Auth Error!'
});
}
console.log("Error3");
var token = jwt.encode({
username: user.email
}, "hanswurst");
res.json({
token: token
});
})(req, res, next);
});
Also, I have to tell you that require caches modules. To make config/passport.js aware of mongoose and passport, you should not feed them as parameters like this:
require('./config/passport')(mongoose, passport);
Simply require them again inside config/passport.js like so:
// (in config/passport.js)
// Both of these vars point to the same thing you require'd in app.js
var mongoose = require('mongoose');
var passport = require('passport');
[Edit] I Found the problem. Because Express is no longer supporting subpackages like body-parser etc, you need to set those separately. All would be well had I done that in the first place, but I only activated:
app.use(bodyParser.urlencoded({extended:true}));
You also need to set
app.use(bodyParser.json());
To get it to work properly. Stupid oversight but still, got me stumped for 3 days.
I Have the same problem, but nothing seems to work for me though.
I'll drop the code from the top down in execution order
jade template
.navbar-right(ng-controller="mvNavBarLoginCtrl")
form.navbar-form
.form-group
input.form-control(placeholder='Email', ng-model='username')
.form-group
input.form-control(type='password', placeholder='password', ng-model='password')
button.btn.btn-primary(ng-click="signIn(username,password)") Sign In
Next step Login controller
angular.module('app').controller('mvNavBarLoginCtrl',function($scope, $http){
$scope.signIn = function (username, password){
console.log('un = ' + username); // Prints fine in the console
console.log('pw = ' + password); // Prints fine in the console
$http.post('/login', {username: username, password: password}).then(function(response){
if(response.data.success){
console.log('Logged in!!');
}
else{
console.log('Failed to log in!!');
}
});
}
});
Next step Route handler
app.post('/login', function(req, res, next){
console.log(req.username); // Already empty
console.log(req.password); // Already empty
console.log(req.body); // Already empty
// Because of the use of AngularJS we can not call passport directly,
// missing req and res will break the code
var auth = passport.authenticate('local', function(err, user){
console.log(user); // prints undefined
if(err){return next(err);}
if(!user){res.send({success:false});}
req.logIn(user, function(err){
if(err){return next(err);}
res.send({success: true, user: user});
});
});
// call the auth function to start authenticate
auth(req, res, next);
});
Next step passport authentication handler
var User = mongoose.model('User');
passport.use(new LocalStrategy({
username: 'username',
password: 'password'
},
function(username, password, done){
console.log("called"); // never printed
// find user based in mongoose schema see 'var User'
User.findOne({userName:username}).exec(function (err,user){
console.log(user) // never printed
if(err){return done(err);}
if(user){
return done(null, user);
}
else{
return done(null, false);
}
});
}
));
passport.serializeUser(function(user, done){
if(user) {
done(null, user._id);
}
});
passport.deserializeUser(function(id, done){
user.findOne({_id:id}).exec(function(err, user){
if(user) {
done(null, user);
}
else{
done(null, false);
}
});
});
There are no errors not in the console and not as node output. I am stumped and read about 5 or so other thread with similar issues, nothing worked.
If somebody could give me the golden tip, I would be eternally gratefull.

Node.js passing parameters to my require function in express.js/passport.js? understanding why?

Hi guys I need some help understanding node.js syntax. The application has put parameters on a require function that requires a path to another file ( not a module). let me give you an example of the syntax that I am talking about which is located on the main javascript file called server.js.
require('./config/passport')(passport);
and
require('./app/routes.js')(app, passport);
I need to know why these "app" and "passport" parameters are passed to my require function. app is express and passport is the passport module.
the full relevant files are below. Cheers
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
require('./app/models/user');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
app.use(morgan('dev')); //http request logger
app.use(cookieParser()); //reads cookies (needed for authentication)
app.use(bodyParser()); //gets information from html forms
app.set('view engine', 'ejs');
//required for passport
app.use(session({secret: 'jonathanisawesome'}));
app.use(passport.initialize());
app.use(passport.session()); //persistent login sessions
app.use(flash()); //connect-flash for flash messages stored in sessions
//routes
require('./app/routes.js')(app, passport); //loads our routes and passes in our app and fully configured passport
app.listen(port);
console.log('the magix happens on port ' + port);
app.get('/logout', function(req,res){
req.logout();
res.redirect('/');
});
//processing of the form
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash : true
}));
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash : true
}));
// route for facebook authentication and login
app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/profile',
failureRedirect : '/'
}));
app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
// the callback after google has authenticated the user
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/profile',
failureRedirect : '/'
}));
};
//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 are not, redirect them to the homepage
res.redirect('/');
};
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var User = require('mongoose').model('User');
var configAuth = require('./auth');
var crypto = require('crypto');
module.exports = function(passport){
//passport session setup
//persistent login sessions
//passport needs ability to serialize and unserialize users out of sessions
//use to serialize the user for the session
passport.serializeUser(function(user,done){
done(null, user.id);
});
//deserialize user
passport.deserializeUser(function(id,done){
User.findById(id, function(err, user){
done(err, user);
});
});
//local signup
//using named strategies one for login and one for signup
//by default if there was no name it would be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// create the user
var newUser = new User();
// set the user's local credentials
newUser.email = email;
newUser.password = password; //password is hashed on the model layer
// save the user
newUser.save(function(err,user) {
if(err || !user){
//error handling
if(err.code===11000){ //email taken
return done(null, false, req.flash('signupMessage', 'Sorry, the email '+newUser.email+' has been taken'));
}else{ //its a hacker
return done(null, false, req.flash('signupMessage', JSON.stringify(err)));
}
}else{
return done(null, newUser);
}
});
});
}));
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.authenticate(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}));
//facebook
passport.use(new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function(){
User.findOne({'facebook.id': profile.id}, function(err, user){
if(err)
return done(err);
if(user)
return done(null, user);
else {
var newUser = new User();
newUser.email = profile.emails[0].value;
newUser.password = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
newUser.socialLogin.facebook.id = profile.id;
newUser.socialLogin.facebook.token = accessToken;
newUser.socialLogin.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
newUser.socialLogin.facebook.email = profile.emails[0].value;
newUser.save(function(err){
if(err) console.log(err)
return done(null, newUser);
})
console.log(profile);
}
});
});
}
));
passport.use(new GoogleStrategy({
clientID : configAuth.googleAuth.clientID,
clientSecret : configAuth.googleAuth.clientSecret,
callbackURL : configAuth.googleAuth.callbackURL,
},
function(token, refreshToken, profile, done) {
// make the code asynchronous
// User.findOne won't fire until we have all our data back from Google
process.nextTick(function() {
// try to find the user based on their google id
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if a user is found, log them in
return done(null, user);
} else {
// if the user isnt in our database, create a new user
var newUser = new User();
newUser.email = profile.emails[0].value;
newUser.password = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
newUser.socialLogin.google.id = profile.id;
newUser.socialLogin.google.token = token;
newUser.socialLogin.google.name = profile.displayName;
newUser.socialLogin.google.email = profile.emails[0].value; // pull the first email
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
This:
require('./config/passport')(passport);
is roughly equivalent to this:
var pp = require('./config/passport');
pp(passport);
To explain, require('./config/passport') returns a function that expects one argument. You can call that function directly in the first form above or you can assign it to a variable and then call it.
Take this example:
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
app.use(session({
secret: 'foo',
store: new MongoStore(options)
}));
As you can see MongoStore is meant to be used alongside session, so it depends on that module.
require('./config/passport') returns a function which expects passport as its parameter.
I faced the problem using require('./config/passport')(passport) so I got solution as:
const passConfig = () => {
return require('./config/passport')
}
passConfig(passport)

Categories

Resources