Search code examples
hapi.jshttp-authentication

How to redirect after http basic auth to same url


I am able to bring a username and password pop up whenever i hit the url but i am able to verify the details with the one's present in database but not redirect it to same handler. It is stucking in else loop. How to do that ? After verifying if the logged in person has the right scope then it will give you response data.

My Server.js -

const simple_validate = function (request, reply, next) {
var credentials = auth(request);
if (!credentials || credentials.name !== 'john' || credentials.pass !== 'secret') {
    reply('Not authorized').code(401);
    reply().header('WWW-Authenticate', 'Basic realm="example"').hold();
    reply('success');
} else {
    next();
    reply('Access granted');
}
}
server.register(Basic, (err) => {
server.auth.strategy('simple', 'basic', { validateFunc: simple_validate });

});

Solution

  • This is the right way of doing it.

    const validate = function (request, email, password, callback) {
        // validate your email and password here 
        User.findUser(email,password,function(err,result){
            if(err)
                callback(null,false);
            else
                //do whatever you wanna do
        });
    }
    
    server.register(require('hapi-auth-basic'), (err) => {
           server.auth.strategy('simple', 'basic', { 
                  validateFunc: validateApi
           });
    });