Giter VIP home page Giter VIP logo

Comments (13)

LovikaJain avatar LovikaJain commented on July 17, 2024

I placed strategy in server.js

var validationFunction = Authorization.auth;
console.log(validationFunction);

server.register(
    [{
        register: bearerSimple
    }], function(err){
 if(err){
     console.log("Failed to log the plugin",err);
     throw err;
 }

 server.auth.strategy('bearer', 'bearerAuth', {
    validationFunction : validationFunction
 });
});

and in Authorization file looks like this

function rauth(accessToken, cb) {
    var criteria = {accessToken: accessToken};
    var projection = {};
    var options = {limit: 1};
    Service.AdminService.getadmin(criteria, projection, options, function (err, data) {
        if (err) {
            cb(err);
        } else if (data && data.length > 0 && data[0]._id) {
            console.log(data);
            console.log(data.length);
            adminId = data[0]._id;
            cb()
        } else {
            cb(UniversalFunctions.CONFIG.APP_CONSTANTS.STATUS_MSG.ERROR.INVALID_ACCESS_TOKEN);
        }
    });

Now I am getting this error:

Error: options.validateFunc must be a valid function in bearerAuthentication scheme

from hapi-auth-bearer-simple.

AdriVanHoudt avatar AdriVanHoudt commented on July 17, 2024

Can you console.log(typeof Authorization.auth)? Also in your example the function is called rauth not auth so maybe a typo?

from hapi-auth-bearer-simple.

LovikaJain avatar LovikaJain commented on July 17, 2024

I added validateFunction in server file now it looks like:

var validationFunction = function (accessToken, cb) {
    var criteria = {accessToken: accessToken};
    var projection = {};
    var options = {limit: 1};
    Service.AdminService.getAdmin(criteria, projection, options, function (err, data) {
        if (err) {
            cb(err);
        } else if (data && data.length > 0 && data[0]._id) {
            console.log(data);
            console.log(data.length);
            adminId = data[0]._id;
            cb()
        } else {
            cb(UniversalFunctions.CONFIG.APP_CONSTANTS.STATUS_MSG.ERROR.INVALID_ACCESS_TOKEN);
        }
    });
}	

console.log(typeof(validationFunction));

server.register(
    [{
        register: bearerSimple
    }], function(err){
 if(err){
     console.log("Failed to log the plugin",err);
     throw err;
 }

 server.auth.strategy('bearer', 'bearerAuth', {
    validationFunction : validationFunction
 });
});


-------- Environment: LOCAL ------
function
getting this error: Exception has occurred: Error
Error: options.validateFunc must be a valid function in bearerAuthentication scheme
    at Object.exports.assert (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi-auth-bearer-simple\node_modules\hoek\lib\index.js:736:11)

it seems to be failing at this point (options.validateFunction===function) but I checked console.log(typeof validationFunction); 

This is the ouput: 
Debugger listening on [::]:9041
-------- Environment: LOCAL ------
function

from hapi-auth-bearer-simple.

AdriVanHoudt avatar AdriVanHoudt commented on July 17, 2024

I don't see the difference between what you have and the default test case :/

it('authenticates a request with Authorization header', (done) => {
const validFunc = (token, callback) => {
expect(token).to.exist();
return callback(null, token === internals.token, internals.validUser);
};
const server = new Hapi.Server();
server.connection();
server.register(require('../lib/'), (err) => {
expect(err).to.not.exist();
server.auth.strategy('default', 'bearerAuth', true, { validateFunction: validFunc });
server.route({
method: 'POST',
path: '/login/{user}',
config: {
auth: 'default',
handler: (request, reply) => {
return reply(request.auth.credentials);
}
}
});
const request = { method: 'POST', url: '/login/testuser', headers: { Authorization: internals.authorizationHeader } };
server.inject(request, (res) => {
expect(res.statusCode).to.equal(200);
expect(res.result).to.exist();
expect(res.result).to.equal(internals.validCredentials);
done();
});
});
});

Could you make a gist or something that errors with you that I can easily test?

from hapi-auth-bearer-simple.

LovikaJain avatar LovikaJain commented on July 17, 2024

I found the problem it was with the function name I was using validationFunction : validationFunction in strategy. Changed it to validateFunction : validationFunction and now no errors but it is not reading the accessToken and not even going to the function while executing it.
It is not even reading the functions created to get the data

171005/202050.614, [response], http://DESKTOP-02KCUJ9:3000: [1;32mget /api/orders/595fbf63ddb918253f4bd7e3/vehicles {} 401 (216ms)

Could I mail you the file with the endpoint which I am trying?

from hapi-auth-bearer-simple.

AdriVanHoudt avatar AdriVanHoudt commented on July 17, 2024

Oh totally missed that 😱
Your validation function needs to callback like callback(/*error, isValid, credential*/)
As far as I can see you never callback with callback(null, true, admin) so it will never registers as authenticated.

from hapi-auth-bearer-simple.

LovikaJain avatar LovikaJain commented on July 17, 2024

Thanks that worked. and Will it create any conflict if create multiple strategies ?

from hapi-auth-bearer-simple.

AdriVanHoudt avatar AdriVanHoudt commented on July 17, 2024

Just create not, if you want to chain them read https://hapijs.com/api#serverauthschemename-scheme

from hapi-auth-bearer-simple.

LovikaJain avatar LovikaJain commented on July 17, 2024

Can I get the user details who is logged in while I am passing the accesstoken? I want to display the user details

from hapi-auth-bearer-simple.

AdriVanHoudt avatar AdriVanHoudt commented on July 17, 2024

so when you callback using callback(null, true, { id: 1, name: 'Doe' }) You will get access to the user credentials via request.auth.credentials. In this case request.auth.credentials will be { id: 1, name: 'Doe' }

from hapi-auth-bearer-simple.

LovikaJain avatar LovikaJain commented on July 17, 2024

But I am not passing the credentials to the callback function. I am returning an object data which contains user details along with id and name.

from hapi-auth-bearer-simple.

LovikaJain avatar LovikaJain commented on July 17, 2024

Thanks pulled the credentials from the data itself :)

from hapi-auth-bearer-simple.

AdriVanHoudt avatar AdriVanHoudt commented on July 17, 2024

Glad you figured it out! 👍

from hapi-auth-bearer-simple.

Related Issues (12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.