How to save user login? Is this possible with ExpressJS and Passport?

I have a server in node.js using express and passport using passport-local strategy.

I have users in the database and through the passport, I can authenticate them, unfortunately, when the second request comes from the same client, the req.isAuthenticated() method returns false . There is also no user in the request ( req.user = undefined ).

I also checked and authenticated, although I am returning the user from passport.authenticate('local'... then I do not get req.user . If I try to configure it manually, it just does not apply to the following requests.

I do not understand what I am doing wrong, here is my code.

server.js

 var express = require('express'), compass = require('node-compass'), routes = require('./server/routes') http = require('http'), path = require('path'), passport = require('passport'), LocalStrategy = require('passport-local').Strategy, Database = require('./server/repositories/database'), Configuration = require('./server/config').Config, crypto = require('crypto'); var app = express(); app.enable("jsonp callback"); passport.use(new LocalStrategy( function(email, password, done) { process.nextTick(function () { var userService = new UserService(); userService.login(email, crypto.createHash('md5').update(password).digest("hex"), function(error, user) { if (error) done(error, user); else if (!user) return done(null, false, { message: 'wrong credentials'}); return done(null, user); }); }); } )); passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(id, done) { var userService = new UserService(); userService.findById(id, function(err, user) { done(err, user); }); }); app.configure(function(){ app.set('port', Configuration.Port); app.set('views', __dirname + '/app/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(compass({ project: path.join(__dirname, 'app'), sass: 'styles' })); app.use(express.session({ secret: 'keyboard cat' })); app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'app'))); }); routes.configure(app); Database.open(function() { app.listen(Configuration.Port, function() { console.log("Express server listening on port " + Configuration.Port); }); }); 

routes.js

 var Configuration = require('./config').Config; var ApiResult = require('../model/apiResult').ApiResult; var ApiErrorResult = require('../model/apiErrorResult').ApiErrorResult; var ApiReturnCodes = require('../model/apiReturnCodes').ApiReturnCodes; var passport = require('passport'); var usersController = require('./controllers/usersController'); exports.configure = function(app) { function ensureAuthenticated(req, res, next) { console.log(req.isAuthenticated()); if (req.isAuthenticated()) { return next(); } else {res.send(new ApiErrorResult(ApiReturnCodes.NOT_LOGGED_IN, null));} } app.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err || !user) { console.log(info); res.send(new ApiErrorResult(ApiReturnCodes.ENTITY_NOT_FOUND, null)); } // If this function gets called, authentication was successful. // `req.user` contains the authenticated user else res.send(new ApiResult(user)); })(req,res,next); }); app.get('/anotherLink', ensureAuthenticated, function(req, res, next) { res.json({Code:0}); }); } 

When I hit the /anotherLink link after authentication, I get res.isAuthenticated() as false.

Also, when I see req.session after the ensureAuthenticated call, I get:

 { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, passport: {} } 

What am I missing to save information that is authenticated by this user? On the client side, I use Angular, simply doing simple access with a URL without parameters.

If I forgot to say something, just tell me, I will update it. Any help would be appreciated. Thanks

+4
source share
1 answer

So, I found out what is wrong with my code.

My passport.deserializeUser method used the userService.findById method

And this is called the repository ... like this:

 userRepository.findUnique({"_id": id}, callback); 

since id was generated using MongoDB , the correct call should be:

 userRepository.findUnique({"_id": new ObjectID(id)}, callback); 

Hope this saves some time for the next person with the same problem.

With this detail, this code should work well for anyone who wants to use LocalStrategy in the Passport infrastructure.

+6
source

Source: https://habr.com/ru/post/1501703/


All Articles