Muhammad Ali
Muhammad Ali

Reputation: 369

check if current user is logged In

I have a profile section in my angular app and right now i have 5 users let's say.

I have a route where users have to change the password. I want to verify if users are correctly logged in and has passed authentication and they cannot change password for any other users.

router.get('/change-password/:username', (req, res) => {
  User.findOne({
    username: req.params.username
  }).then(user => {
    if (user) {
      res.status(200).json(user);
    } else if (!user) {
      res.status(404).json({
        message: 'user not found'
      });
    }
  });
});

what if user A is logged in and he change the parameter to B and then change the password ? is there any way I dont pass parameter and get current user who is logged In

Upvotes: 2

Views: 2057

Answers (1)

Gaspar
Gaspar

Reputation: 1591

Basically is like this, when you log the user in from back end, you send a response with a token to the front end. You save this token to the local storage to have it in every request to the back end. Them, you use a middleware function to check if the token is provided in the header of the request like a bearer. So the answer is: you don't have to check the auth every request, you just check if the token is provided by middleware and if it is correct. If you are using express, the most apps use a middleware in the auth service class like this:

module.exports.isAuthorized  = function(req, res, next) {

    User.findById(req.session.userId).exec(function (error, user) {
        if (error) {
            return next(error);
        } else {      
            if (user === null) {     
                var err = new Error('Not authorized! Go back!');
                err.status = 400;
                return next(err);
            } else {
                return next();
            }
        }
    });
}

At the node.js routes:

var auth = require('./auth');

// GET route after registering
router.get('/clientPage', auth.isAuthorized, function (req, res, next) {console.log("1114");
    res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
});

As you can see, the second param says that before make the request, it will execute the middleware function auth.isAuthorized.

Upvotes: 2

Related Questions