Verifying roles & authentication with Passport.js

前端 未结 3 1143
慢半拍i
慢半拍i 2021-02-01 22:58

So I\'d like to make some routes in an API that will show different data based on the user role, defined in MongoDB. Here\'s a sampling of what I have right now, it works...

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 23:38

    The solution I've found to my answer is to use an adaptation of the Passportjs.org documentation.

    In the routes I need to return data, whether a user is logged in or not I can use something like:

    // Test to check for authentication
    app.get('/login', function(req, res, next) {
      passport.authenticate('bearer', function(err, user, info) {
        if (user)
            // check user's role for premium or not
            if (user.role == "premium")
                return res.send('user is premium')
            else
                return res.send('user is not premium');
        else
            // return items even if no authentication is present, instead of 401 response
                return res.send('not logged in');
      })(req, res, next);
    });
    

提交回复
热议问题