Search code examples
javascriptnode.jshapi.js

HAPI + hapi-auth-basic: Is it possible to implement our own login page instead of the sign in pop up window?


We're currently using HAPI and HAPI-AUTH-BASIC for authentication.

When configuring a route, is it possible to check if a user is authenticated and if they're not, redirect them to a custom login page?

Anytime we set auth as 'simple', the routed page displays an in browser sign in popup window which is something that we do not want.

I've checked the docs and it's very lacking atm :(

server.route({
    method: 'GET',
    path: '/profile',
    config: {
        auth: 'simple',
        handler: function (request, reply) {
            reply('hello, ' + request.auth.credentials.name);
        }
    }
});


Solution

  • Make use of schemes and strategies of hapi to achieve what you want. Below code will check if user is logged in or not else it will throw a error. You can redirect to login page with proper settings. It also checks if the route is authenticated or not with mode as required. More Info

    server.route({
    method: 'GET',
    path: '/profile',
    handler: function (request, reply) {
        reply('hello, ' + request.auth.credentials.name);
    },
    auth: {
        mode:'required',
        strategy:'session'
    }
    });