oneblink / hapi-oauth2orize

A bridge between hapi and OAuth2orize
BSD 3-Clause "New" or "Revised" License
27 stars 17 forks source link

oauth2orize is not working with hapijs #16

Open AmayraRajput opened 8 years ago

AmayraRajput commented 8 years ago

How do I implement oauth2orize in hapijs. Please suggest. I did this code but it's not working when I am hitting the API. I am new in hapijs and oauth2orize. Also hapi-oauth2orize is not working as I am using hapi 13.4.1 which is not compatible with hapi-oauth2orize 1.3.0, throwing error 'Invalid plugin options {}' .Please suggest me a way to implement oauth2orize in hapijs.

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);
                          });
                        }));

                    }
                  }
                },
            ]);
});
lutfor3737 commented 8 years ago

I would suggest you to study oauth2 to understand the flow, grant types and their use cases. If you don't understand the flow, it will be difficult to write code. you can play in this example to understand the flow. https://github.com/jaredhanson/oauth2orize/tree/master/examples/all-grants