简体   繁体   English

未通过护照连线req.user

[英]req.user not wired by Passport

As the title says, wherever I try to call the req.user it outputs me an undefined object and cause a 500 Internal Server Error. 如标题所示,无论我在哪里调用req.user,它都会向我输出一个未定义的对象,并导致500 Internal Server Error。
This is the code that I have so far (not all, just the interested part): 这是我到目前为止的代码(不是全部,只是感兴趣的部分):
app.js app.js

    app.use(cookieParser());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(session({
        secret: 'keyboard cat',
        resave: false,
        saveUninitialized: true,
        cookie: { secure: true }
      })); //This was added as a second temptative
    app.use(passport.initialize());
    app.use(passport.session());


    // config
    passport.use('local', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'pwd',
        session: false
    },
        function (username, password, done) {
            User.findOne({ email: username }, (err, usr) => {
                if (err) { return done(err); }
                // TODO: refactor for right error message handling as below!!
                if (!usr)
                    return done(null, false, { success: false, status: 403, message: 'Incorrect username.' });
                if (!usr.authenticate(password))
                    return done(null, false, { success: false, status: 403, message: 'Incorrect password.' });
                if (!usr.verified)
                    return done(null, false, { succes: false, status: 400, message: 'User not confirmed' });
                delete usr.salt;
                delete usr.password;
                return done(null, usr);
            });
        })
    );

passport.serializeUser(function (user, done) {
    const tempUser = Object.assign({}, { x: user.id, y: user.email, z: user.salt });
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    console.warn(`WE DID IT`);
    User.findById(id, function (err, user) {
        console.log(`id in input ${id}`);
        console.log(`deserializing user ${user}`);
        done(err, user);
    });
});

Controller that I use for auth : 我用于auth的控制器

exports.authenticate = (req, res) => {
  passport.authenticate('local', { session: false /*, failureCallback: failureCallback */}, (err, user, info) => {
    if (!err) {
      if (!user)
        res.json(info);
      else {
        var userCopy = Object.assign({}, user._doc);
        delete userCopy.password;
        delete userCopy.salt;
        delete userCopy.profilePicture;
        Activity.checkin.getActiveUserCheckin(userCopy._id, (err, activeCheckin) => {
          if(!err){
            if(!!activeCheckin) userCopy.activeCheckinOnStructure = activeCheckin.structureId;
            var token = jwt.sign(userCopy, require('../../secret'));
            res.send({ success: true, status: 200, token: token });
          }else{
            res.send({ success: false, status: 500, message: err });
          }
        });
      }
    }
  })(req, res);

};

Things that I tried: first of all, I tried to add an express-session (as you can see in the app.use(session) part) to add the Express' session. 我尝试过的事情:首先,我尝试添加一个Express-Session(如您在app.use(session)部分中所见)以添加Express'会话。 Then, I tried to set the user like this app.set("user", user) but it won't be good as I don't have access to the app variable in the point in which I call the method. 然后,我尝试将用户设置为类似app.set(“ user”,user),但这并不好,因为在调用方法时我无法访问app变量。
It looks to me that the configurations for the app.js part and the login part have been done in a good way and passport should automatically wire the req.user field but this, somehow, is not happening and I can't explain myself why is this happening. 在我看来,app.js部分和login部分的配置已经很好地完成了,并且护照应该自动将req.user字段连接起来,但是这并没有发生,我无法解释自己为什么这是真的吗

The problem for this specific question was that the userSerializer was never invoked. 该特定问题的问题在于从未调用过userSerializer。 Adding req.login solved the day 添加req.login解决了这一天

  passport.authenticate('local', { session: true /*, failureCallback: failureCallback */}, (err, user, info) => {
    if (!err) {
      if (!user)
        res.json(info);
      else {
        var userCopy = Object.assign({}, user._doc);
        delete userCopy.password;
        delete userCopy.salt;
        delete userCopy.profilePicture;
        Activity.checkin.getActiveUserCheckin(userCopy._id, (err, activeCheckin) => {
          if(!err){
            if(!!activeCheckin) userCopy.activeCheckinOnStructure = activeCheckin.structureId;
            var token = jwt.sign(userCopy, require('../../secret'));
            req.login(user, function(err) {
              if (err) {
                return res.status(401).json(err);
              } else {
                res.send({ success: true, status: 200, token: token });
              }
            });
          }else{
            res.send({ success: false, status: 500, message: err });
          }
        });
      }
    }
  })(req, res);

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM