문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top