Created
August 14, 2012 23:58
-
-
Save timsavery/3354026 to your computer and use it in GitHub Desktop.
Salesforce Chatter OAuth 2.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request') | |
, querystring = require('querystring'); | |
module.exports = function ChatterAuth() { | |
this.environment = process.env.SALESFORCE_ENV; | |
this.client_id = process.env.SALESFORCE_CLIENT_ID; | |
this.client_secret = process.env.SALESFORCE_CLIENT_SECRET; | |
this.oauth_callback_uri = process.env.SALESFORCE_OAUTH_CALLBACK_URI; | |
this.redirectToLogin = function(req, res) { | |
if (process.env.BYPASS_SALESFORCE_AUTH) { | |
res.redirect(this.oauth_callback_uri); | |
} else { | |
var qs = querystring.stringify({ | |
response_type: 'code', | |
client_id: this.client_id, | |
redirect_uri: encodeURI(this.oauth_callback_uri) | |
}); | |
req.session.auth_service = 'chatter'; | |
res.redirect(this.environment + '/services/oauth2/authorize?' + qs); | |
} | |
}; | |
this.oauthcallback = function(req, callback) { | |
var options = { | |
url: this.environment + '/services/oauth2/token', | |
form: { | |
code: req.param('code'), | |
grant_type: 'authorization_code', | |
client_id: this.client_id, | |
client_secret: this.client_secret, | |
redirect_uri: this.oauth_callback_uri | |
} | |
}; | |
request.post(options, function(error, response, body) { | |
var parsed_body = JSON.parse(body) | |
, auth_params = { | |
instance_url: parsed_body.instance_url, | |
issued_at: parsed_body.issued_at, | |
refresh_token: parsed_body.refresh_token, | |
scope: parsed_body.scope, | |
signature: parsed_body.signature, | |
access_token: parsed_body.access_token | |
}; | |
var options = { | |
url: auth_params.instance_url + '/services/data/v23.0/chatter/users/me', | |
headers: { 'Authorization': 'OAuth ' + auth_params.access_token } | |
}; | |
request.get(options, function(error, response, body) { | |
callback(auth_params, JSON.parse(body)); | |
}); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment