fr3d0
fr3d0

Reputation: 225

Make a base route filter with hapijs

i'm new to nodejs and i'm making an api with hapijs to handle some functionalities from mi site, i want to be able to make a base url like api/* and make all others url that start with api/ pass throug some validations but only do that once, this is what i have so far:

server.route([
            {
                method: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
                path: "/api/*",
                handler: function(request, reply){
                    is_authorized = auth(request.raw.req.headers['Authorization']);
                    if(!is_authorized){
                        reply(response.generate_json(null, 'no autorizado', 'UNAUTHORIZED')).code(401);
                    }
                }
            }
        ]);

but it doesn't work, when i call any other url like api/sockets/whatever it just passes even if it's not authorized.... is there any way i can achive this in hapijs??

Upvotes: 2

Views: 442

Answers (1)

anumula narendra
anumula narendra

Reputation: 66

you have to use on prehandler hook

server.ext('onPreHandler', (request, reply) => {
if(request.path.startsWith("/api/"))
{
    is_authorized = auth(request.raw.req.headers['Authorization']);
    if(!is_authorized)
    {
        reply(response.generate_json(null, 'no autorizado', 'UNAUTHORIZED')).code(401);
    }
    else
    {
      return reply.continue();
    }
}
else
{
return reply.continue();
}
});

if you need any further info.happy to help

Upvotes: 1

Related Questions