Garima
Garima

Reputation: 1666

How to implement oauth2orize in hapijs

I implemented oauth2orize in hapijs. But when I am calling the api, nothing happen. The function goes inside code.js file of oauth2orize module and hangs in between. Please suggest me how to implement oauth2orize in hapjs. hapi-oauth2orize is also not working as immigration & hapi-oauth2orize plugin throws option error.

const Hapi = require('hapi');
const server = new Hapi.Server();
const oauth2orize = require('oauth2orize');
var oauth = oauth2orize.createServer();

server.connection({ 
    host: 'localhost', 
    port: 8000 
});

    server.register([{
        register: require('hapi-mongodb'),
        options: dbOpts
    }], function (err) {
        if (err) {
            console.error(err);
            throw err;
        }
        server.start();

        server.route([
                    {
                      method: 'GET',
                      path: '/oauth/authorizegrant',
                      config: {
                        auth: false,
                        handler: function(request, reply) {
                            var clientId = request.query.client_id,
                                redirectUrl = request.query.redirect_uri,
                                resType = request.query.response_type,
                                state = request.query.state;
                            oauth.grant(oauth2orize.grant.code(function(clientId,redirectUrl,resType,state,callback) {
                              // Create a new authorization code
                                  console.log('client', client);
                                  var db = request.server.plugins['hapi-mongodb'].db;
                                  var code = new Code({
                                    value: uid(16),
                                    clientId: client._id,
                                    redirectUri: redirectUri,
                                    userId: user._id
                                  });

                              // Save the auth code and check for errors
                            db.collection('codes').insert(code, function(err) {
                                if (err) { console.log('err*********', err); return callback(err); }

                                callback(null, code.value);
                              });
                            }));

                        }
                      }
                    },
                ]);
    });

Upvotes: 1

Views: 531

Answers (1)

simon-p-r
simon-p-r

Reputation: 3751

You need to change parameters passed to oauth.grant function, the callback should be removed and replaced by hapi's reply function. A simple snippet would be

if (err) {
    return reply(err);
}
return reply(code.value);

I would file an issue in the plugin repo as this is the best way to interface between hapi and oauth2orize.

Upvotes: 0

Related Questions