Skip to content

Instantly share code, notes, and snippets.

@tfogo
Forked from SeraphimSerapis/liwpp.js
Last active December 25, 2015 09:59
Show Gist options
  • Save tfogo/6957747 to your computer and use it in GitHub Desktop.
Save tfogo/6957747 to your computer and use it in GitHub Desktop.
'use strict';
var request = require('request');
var querystring = require('querystring');
/*
* CLIENT DETAILS
*/
var CLIENT_ID = "CLIENT_ID_HERE";
var CLIENT_SECRET = "CLIENT_SECRET_HERE";
var REDIRECT_URI = "http://yourAwesomeSite:3000/myCallback";
var SCOPE = "openid profile email address";
/*
* ENDPOINTS LOG IN WITH PAYPAL
*/
var base_webapps = 'https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1';
var base_api = 'https://api.sandbox.paypal.com/v1/identity/openidconnect';
var endpoint_authorize = base_webapps + '/authorize';
var endpoint_endsession = base_webapps + '/endsession';
var endpoint_tokenservice = base_api + '/tokenservice';
var endpoint_userinfo = base_api + '/userinfo';
/*
* PLACEHOLDERS & CONSTANTS
*/
var TYPE_JSON = 'json';
var TYPE_FORM = 'form';
var user = {};
var token = {
access_token: "",
refresh_token: "",
id_token: ""
};
var headers = {
"Accept": "application/json",
"Content-type": "application/json;charset=UTF-8",
"Authorization": "Bearer " + token.access_token
};
exports.login = function (req, res) {
var data = {
client_id: CLIENT_ID,
response_type: "code",
scope: SCOPE,
redirect_uri: REDIRECT_URI
};
res.redirect(endpoint_authorize + "?" + querystring.stringify(data));
};
exports.auth = function (req, res) {
var data = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: "authorization_code",
code: req.query.code
};
doPost(endpoint_tokenservice, data, TYPE_FORM, function (error, response, body) {
if (!error) {
token = JSON.parse(body);
headers.Authorization = "Bearer " + token.access_token;
res.redirect("/profile");
}
});
};
exports.profile = function (req, res) {
var data = {
schema: "openid",
access_token: token.access_token
};
doPost(endpoint_userinfo, data, TYPE_FORM, function (error, response, body) {
if (!error && response.statusCode === 200) {
user = JSON.parse(body);
// do amazing stuff here
}
});
};
function doPost(url, data, type, callback) {
if (type === 'json') {
request.post({url: url, json: data, headers: headers }, callback);
} else {
request.post({url: url, form: data, headers: headers }, callback);
}
}
function doGet(url, callback) {
request.get({url: url, headers: headers }, callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment