Permalink
Browse files

Update OAuth 3&2 Legged providers for connect 2

  • Loading branch information...
1 parent 52c794f commit 476fb45d8c1423b13414ce730c05897c780ce29a @ciaranj committed Feb 29, 2012
View
@@ -3,20 +3,6 @@ var connect = require('connect');
var auth= require('../lib');
var url= require('url');
var OAuthDataProvider= require('./in_memory_oauth_data_provider').OAuthDataProvider;
-function routes(app) {
- app.get ('/fetch/unicorns', function(req, res, params) {
- req.authenticate(['oauth'], function(error, authenticated) {
- if( authenticated ) {
- res.writeHead(200, {'Content-Type': 'text/plain'})
- res.end('The unicorns fly free tonight');
- }
- else {
- res.writeHead(401, {'Content-Type': 'text/plain'})
- res.end('Doubt you\'ll ever see this.');
- }
- });
- });
-}
var renderAuthenticationForm= function(res, token, flash) {
res.writeHead(200, {'Content-Type':'text/html'})
@@ -41,7 +27,7 @@ var renderAuthenticationForm= function(res, token, flash) {
};
var authenticateProvider= function(req, res) {
- var parsedUrl= url.parse(req.url, true);
+ var parsedUrl= url.parse(req.originalUrl, true);
renderAuthenticationForm(res, parsedUrl.query.oauth_token );
};
@@ -92,15 +78,29 @@ var authorizationFinishedProvider = function(err, req, res, result) {
</html>');
}
-var server= connect.createServer(
- connect.bodyParser(),
- auth( [
- auth.Oauth({oauth_provider: new OAuthDataProvider({ applications:[{title:'Test', description:'Test App', consumer_key:"JiYmll7CX3AXDgasnnIDeg",secret:"mWPBRK5kG2Tkthuf5zRV1jYWOEwnjI6xs3QVRqOOg"}]
- , users:[{username:'foo', password:'bar'}] }),
- authenticate_provider: authenticateProvider,
- authorize_provider: authorizeProvider,
- authorization_finished_provider: authorizationFinishedProvider
- })
- ]),
- connect.router(routes));
-server.listen(3000);
+var app= connect();
+app.use(connect.bodyParser())
+ .use(connect.logger())
+ .use(auth({strategies: [
+ auth.Oauth({oauth_provider: new OAuthDataProvider({ applications:[{title:'Test', description:'Test App', consumer_key:"JiYmll7CX3AXDgasnnIDeg",secret:"mWPBRK5kG2Tkthuf5zRV1jYWOEwnjI6xs3QVRqOOg"}]
+ , users:[{username:'foo', password:'bar'}] }),
+ authenticate_provider: authenticateProvider,
+ authorize_provider: authorizeProvider,
+ authorization_finished_provider: authorizationFinishedProvider
+ })
+ ],
+ trace: true
+ }))
+ .use('/fetch/unicorns', function(req, res, params) {
+ req.authenticate(['oauth'], function(error, authenticated) {
+ if( authenticated ) {
+ res.writeHead(200, {'Content-Type': 'text/plain'})
+ res.end('The unicorns fly free tonight');
+ }
+ else {
+ res.writeHead(401, {'Content-Type': 'text/plain'})
+ res.end('Doubt you\'ll ever see this.');
+ }
+ });
+ })
+ .listen(3000);
@@ -2,29 +2,27 @@ var connect = require('connect');
var auth= require('../lib');
var url= require('url');
var OAuthDataProvider= require('./in_memory_oauth_data_provider').OAuthDataProvider;
-function routes(app) {
- app.get ('/fetch/unicorns', function(req, res, params) {
- req.authenticate(['oauth'], function(error, authenticated) {
- if( authenticated ) {
- res.writeHead(200, {'Content-Type': 'text/plain'})
- res.end('The unicorns fly free tonight');
- }
- else {
- res.writeHead(401, {'Content-Type': 'text/plain'})
- res.end('Doubt you\'ll ever see this.');
- }
- });
- });
-}
-var server= connect.createServer(
- connect.bodyParser(),
- auth( [
- auth.Oauth({oauth_provider: new OAuthDataProvider({ applications:[{title:'Test', description:'Test App', consumer_key:"JiYmll7CX3AXDgasnnIDeg",secret:"mWPBRK5kG2Tkthuf5zRV1jYWOEwnjI6xs3QVRqOOg"}]}),
- authenticate_provider: null,
- authorize_provider: null,
- authorization_finished_provider: null
- })
- ]),
- connect.router(routes));
-server.listen(3000);
+var app= connect();
+app.use(connect.bodyParser())
+ .use(connect.logger())
+ .use(auth( [
+ auth.Oauth({oauth_provider: new OAuthDataProvider({ applications:[{title:'Test', description:'Test App', consumer_key:"JiYmll7CX3AXDgasnnIDeg",secret:"mWPBRK5kG2Tkthuf5zRV1jYWOEwnjI6xs3QVRqOOg"}]}),
+ authenticate_provider: null,
+ authorize_provider: null,
+ authorization_finished_provider: null
+ })
+ ]))
+ .use ('/fetch/unicorns', function(req, res, params) {
+ req.authenticate(['oauth'], function(error, authenticated) {
+ if( authenticated ) {
+ res.writeHead(200, {'Content-Type': 'text/plain'})
+ res.end('The unicorns fly free tonight');
+ }
+ else {
+ res.writeHead(401, {'Content-Type': 'text/plain'})
+ res.end('Doubt you\'ll ever see this.');
+ }
+ });
+ })
+ .listen( 3000 );
View
@@ -1,6 +1,5 @@
var connect = require('connect');
var url= require('url')
-//var MemoryStore = require('connect/middleware/session/memory');
// We let the example run without npm, by setting up the require paths
// so the node-oauth submodule inside of git is used. You do *NOT*
@@ -12,33 +11,29 @@ var oa= new OAuth("http://localhost:3000/oauth/request_token",
"JiYmll7CX3AXDgasnnIDeg", "mWPBRK5kG2Tkthuf5zRV1jYWOEwnjI6xs3QVRqOOg",
"1.0A", "http://localhost:4000/oauth/callback", "HMAC-SHA1");
-function routes(app) {
-
- app.get ('/', function(req, res, params) {
- oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
- req.session.oauth_token_secret= oauth_token_secret;
- console.log(require('sys').inspect(req.session))
-
- res.writeHead(303, { 'Location': "http://localhost:3000/oauth/authorize?oauth_token=" + oauth_token });
- res.end('');
- });
- });
- app.get ('/oauth/callback', function(req, res, params) {
- var parsedUrl= url.parse(req.url, true);
- console.log(require('sys').inspect(req.session))
- oa.getOAuthAccessToken(parsedUrl.query.oauth_token, req.session.oauth_token_secret, parsedUrl.query.oauth_verifier,
- function(error, oauth_access_token, oauth_access_token_secret, results) {
- oa.getProtectedResource("http://localhost:3000/fetch/unicorns", "GET", oauth_access_token, oauth_access_token_secret, function(error, data){
- res.writeHead(200, {'Content-type': 'text/html'})
- res.end(data);
- })
- })
- });
-}
+var app= connect();
+app.use(connect.logger())
+ .use(connect.cookieParser("secret"))
+ .use(connect.session())
+ .use ('/oauth/callback', function(req, res, params) {
+ var parsedUrl= url.parse(req.originalUrl, true);
+ console.log(require('sys').inspect(req.session))
+ oa.getOAuthAccessToken(parsedUrl.query.oauth_token, req.session.oauth_token_secret, parsedUrl.query.oauth_verifier,
+ function(error, oauth_access_token, oauth_access_token_secret, results) {
+ oa.getProtectedResource("http://localhost:3000/fetch/unicorns", "GET", oauth_access_token, oauth_access_token_secret, function(error, data){
+ res.writeHead(200, {'Content-type': 'text/html'})
+ res.end(data);
+ })
+ })
+ })
+ .use ('/', function(req, res, params) {
+ oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
+ console.log( error )
+ req.session.oauth_token_secret= oauth_token_secret;
+ console.log(require('util').inspect(req.session))
-var server= connect.createServer(
- connect.cookieParser(),
- connect.session({secret:'consumer'}),
-/* connect.session({ store: new MemoryStore({ reapInterval: -1 }) }), */
- connect.router(routes));
-server.listen(4000);
+ res.writeHead(303, { 'Location': "http://localhost:3000/oauth/authorize?oauth_token=" + oauth_token });
+ res.end('');
+ });
+ })
+ .listen(4000);
@@ -60,7 +60,7 @@ exports.OAuthServices= function(provider, legs) {
};
exports.OAuthServices.prototype.accessToken= function(request, protocol, callback) {
- var parsedUrl= url.parse(request.url, true);
+ var parsedUrl= url.parse(request.originalUrl, true);
var method= request.method;
var headers= request.headers;
var host= headers['host'];
@@ -150,7 +150,7 @@ exports.OAuthServices.prototype.authenticateUser = function(username, password,
}
exports.OAuthServices.prototype.authorize= function(request, protocol, callback) {
- var parsedUrl= url.parse(request.url, true);
+ var parsedUrl= url.parse(request.originalUrl, true);
var method= request.method;
var headers= request.headers;
var host= headers['host'];
@@ -272,7 +272,7 @@ exports.OAuthServices.prototype.fetchAuthorizationInformation = function(usernam
}
exports.OAuthServices.prototype.requestToken= function(request, protocol, callback) {
- var parsedUrl= url.parse(request.url, true);
+ var parsedUrl= url.parse(request.originalUrl, true);
var method= request.method;
var headers= request.headers;
var host= headers['host'];
@@ -292,7 +292,6 @@ exports.OAuthServices.prototype.requestToken= function(request, protocol, callba
// Make a note of this as it will screw stuff up later if we leave it in the parameters bag
var oauth_signature= requestParameters['oauth_signature'];
delete requestParameters['oauth_signature'];
-
// Reject non-HMAC-SHA1 and non-PLAINTEXT signature_methods
if (requestParameters['oauth_signature_method'] != 'HMAC-SHA1' &&
requestParameters['oauth_signature_method'] != 'PLAINTEXT') {
@@ -111,60 +111,62 @@ module.exports= function(options) {
});
}
- // Build the authentication routes required
- that.setupRoutes= function(server) {
- server.use('/', connect.router(function routes(app){
- app.post(my['request_token_url'], requestTokenMethod);
- app.get(my['request_token_url'], requestTokenMethod);
- app.post(my['access_token_url'], accessTokenMethod);
- app.get(my['access_token_url'], accessTokenMethod);
-
+ var authorizeUrlMethod= function( req, res ) {
+ if( req.method == 'GET' ) {
// Should render the form that allows users to authenticate themselves
- app.get(my['authorize_url'], my['authenticate_provider'] );
-
+ my['authenticate_provider'](req, res);
+ }
+ else if( req.method == 'POST' ) {
// Handles the post from the authentication form.
- app.post(my['authorize_url'], function(req, res) {
- var self = this;
+ var self = this;
+
+ if(req.body['verifier'] == null) {
+ my['oauth_service'].authenticateUser(req.body['username'], req.body['password'], req.body['oauth_token'], function(err, result) {
+ if(err) {
+ // Delegate to the function of the user
+ my.authorize_provider.call(self, err, req, res, false, {token:req.body['oauth_token']});
+ } else {
+ // Fetch the needed data
+ my['oauth_service'].fetchAuthorizationInformation(req.body['username'], result.token, function(err, application, user) {
+ // Signal callback about finish authorization
+ my.authorize_provider.call(self, null, req, res, true, result, application, user);
+ });
+ }
+ });
+ } else {
+ var oauth_token= req.body['oauth_token'];
+ var verifier= req.body['verifier'];
- if(req.body['verifier'] == null) {
- my['oauth_service'].authenticateUser(req.body['username'], req.body['password'], req.body['oauth_token'], function(err, result) {
- if(err) {
- // Delegate to the function of the user
- my.authorize_provider.call(self, err, req, res, false, {token:req.body['oauth_token']});
- } else {
- // Fetch the needed data
- my['oauth_service'].fetchAuthorizationInformation(req.body['username'], result.token, function(err, application, user) {
- // Signal callback about finish authorization
- my.authorize_provider.call(self, null, req, res, true, result, application, user);
- });
- }
- });
- } else {
- var oauth_token= req.body['oauth_token'];
- var verifier= req.body['verifier'];
-
- // Check if there is an entry for this token and verifier
- my['oauth_service'].verifyToken(oauth_token, verifier, function(err, result) {
- if(err) {
- // Delegate to the function of the user
- my.authorize_provider.call(self, err, req, res, false, {token:oauth_token});
+ // Check if there is an entry for this token and verifier
+ my['oauth_service'].verifyToken(oauth_token, verifier, function(err, result) {
+ if(err) {
+ // Delegate to the function of the user
+ my.authorize_provider.call(self, err, req, res, false, {token:oauth_token});
+ } else {
+ if(result.callback != null && result.callback != "oob") {
+ var callback = result.callback;
+ // Correctly add the tokens if the callback has a ? allready
+ var redirect_url = callback.match(/\?/) != null ? "&oauth_token=" + result.token + "&oauth_verifier=" + result.verifier : "?oauth_token=" + result.token + "&oauth_verifier=" + result.verifier;
+ // Signal that a redirect is in order after finished process
+ res.writeHead(303, { 'Location': result.callback + redirect_url });
+ res.end('');
+
} else {
- if(result.callback != null && result.callback != "oob") {
- var callback = result.callback;
- // Correctly add the tokens if the callback has a ? allready
- var redirect_url = callback.match(/\?/) != null ? "&oauth_token=" + result.token + "&oauth_verifier=" + result.verifier : "?oauth_token=" + result.token + "&oauth_verifier=" + result.verifier;
- // Signal that a redirect is in order after finished process
- res.writeHead(303, { 'Location': result.callback + redirect_url });
- res.end('');
-
- } else {
- my.authorization_finished_provider.call(self, err, req, res, result);
- }
- }
- });
- }
- });
- }));
+ my.authorization_finished_provider.call(self, err, req, res, result);
+ }
+ }
+ });
+ }
+ }
+ else
+ throw new Error("Unknown HTTP method "+ req.method );
+ }
+
+ // Build the authentication routes required
+ that.setupRoutes= function( app ) {
+ app.use(my['request_token_url'], requestTokenMethod);
+ app.use(my['access_token_url'], accessTokenMethod);
+ app.use(my['authorize_url'], authorizeUrlMethod);
}
}
return that;
View
@@ -59,7 +59,7 @@ module.exports.authenticate= function(strategy, opts, callback, strategyExecutor
scope= req.getAuthDetails().__originalScope;
}
- trace( "Authenticating ("+this.headers.host + this.url+")", scope, ">>>" );
+ trace( "Authenticating ("+this.headers.host + this.originalUrl+")", scope, ">>>" );
if( req.isAuthenticated(scope) ) {
delete req.getAuthDetails().__performingAuthentication;
delete req.getAuthDetails().__originalUrl;
@@ -76,7 +76,7 @@ module.exports.authenticate= function(strategy, opts, callback, strategyExecutor
if( req.getAuthDetails().__originalUrl ) {
executionResult.originalUrl= req.getAuthDetails().__originalUrl;
} else {
- executionResult.originalUrl= req.url;
+ executionResult.originalUrl= req.originalUrl;
}
}
if(error) {
@@ -126,7 +126,7 @@ module.exports.authenticate= function(strategy, opts, callback, strategyExecutor
}
else {
req.getAuthDetails().__performingAuthentication= true;
- req.getAuthDetails().__originalUrl= req.url;
+ req.getAuthDetails().__originalUrl= req.originalUrl;
req.getAuthDetails().__originalScope= scope;
trace( "Authentication ongoing (Requires browser interaction)", scope, "<<<" );
callback(null, executionResult.authenticated)

0 comments on commit 476fb45

Please sign in to comment.