0

I need to create authentication function named "access" for my restful API and i want it to look like below for each time user wants be in interaction with server :

access(id , token ,function(err){
   if(err){
            res.send(err)
          }else {
            res.send('you have all permissions')
          }
})

how can i write this function to use in each authentication step?

1
  • mb it's better to user express middleware? Commented Jul 15, 2019 at 9:45

2 Answers 2

1

For authentication you would typically have some middleware:

function isAuthenticated(req, res, next) {
  // determine here if user is authenticated (and/or authorized)
  if (user) {
    next(); // user is authorized, call next
  } else {
    const error = new Error('unauthorized');
    error.status = 400;
    return next(err);
  }
}

app.get('/authenticated/route', isAuthenticated, function(req, res) {
  res.send('secret information');
});

I would recommend using something like Passport.js. It removes a lot of the authentication middleware, and especially makes it easy to integrate with providers like Google and Facebook.

Sign up to request clarification or add additional context in comments.

Comments

0

Better to use is as middleware, if this is for all your entries


function access(req, res, next) {
  // verify token
  if (isNotVerified) { return next('You are not verified') }

  // otherwise do what you want to do
  return next()
}

and add it to all your routes where you want the user to be verified, someting like this:


route.get('/api/private/reports', access, function (req, res) {
  // do some stuff only when user is verified
})

route.get('/api/sensitive/information', access, function (req, res) {
  // do some stuff only when user is verified
})

Hope it will help you!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.