How to update req.user session object set by passportjs?

前端 未结 5 1292
抹茶落季
抹茶落季 2020-12-17 10:49

I\'m trying to do this since a lot of days but all my tests fails...

Users on my platform connect them by using passportjs strategies (paypal, facebook, google...).<

5条回答
  •  情深已故
    2020-12-17 11:35

    Quan Duong's answer was the most useful to me, but here is a bit more realistic scenario:

    async function foo(req, res) {
      // get some data from somewhere
      const newNickname = req.body.nickname;
    
      // update the user database somehow - e.g. mongodb 
      const users = db.getCollection('users');
      await users.updateOne({
        _id: req.user._id
      }, {
        $set: {
          nickname: newNickname
        }
      });
    
      // create a temporary copy of the user w/ the updated property
      const updatedUser = req.user;
      updatedUser.nickname = newNickname
    
      // persist the change to the session
      req.login(updatedUser, async(error) => {
        if (error) {
          res.json({
            err: 'Sorry, there was an error updating your account.'
          });
          return;
        }
    
        /* 
           maybe you need to call another function from here that uses the updated info before 
           responding to the original request
        */
        try {
          await bar(req.user);
        } catch (error) {
          res.json({
            err: 'Sorry, there was an error updating your account.'
          });
          return;
        }
    
        // done
        res.send(200);
      });
    }

提交回复
热议问题