Pergunta

I'm working on an API using restify. There will be a dozen or more endpoints and each one requires authentication. The API will be stateless, so each API request, regardless of endpoint, will pass credentials.

What I'd like to do, if possible, is to authenticate before negotiating the route. Otherwise, if I have a route:

server.get('/activities', activities.index);

Then, within activities.index (and every other routing method), I have to duplicate the following:

var user = require('../models/user')(server);
user.authenticate(req.authorization, function(err, user) {
  ...

  // Do the real activities-related stuff.
});

This is one of those things where it feels like there must be a better way of doing it, but I don't know what it is.

Anyone have any thoughts?

Foi útil?

Solução

So you can register handlers to be ran before every route is ran.

http://mcavage.me/node-restify/#Common-handlers:-server.use()

server.use(function(req, res, next){
    //do authentication here
    if(authenticated){
        return next();
    }
    else{
        res.send({auth:false});
})

So when you use server.use when the user asks for /activites it will run all of the server.use you created in the order you created them before running the code for the route.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top