Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close #15, send GitHub access token via headers #34

Merged
merged 1 commit into from
Jul 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 40 additions & 11 deletions public/local.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,29 @@ var currentGistView = document.getElementById('currentgist');
GITHUB AUTHENTICATION
---------------------------------------------------- */

// If GitHub access_token is available as a parameter, log in!
// TODO: pass the token as a header instead? can client access it that way?
if (getAllUrlParams().access_token) {
console.log('*********** AUTHENTICATED!!! **********');
console.log('access_token from URL params: ' + getAllUrlParams().access_token);
// If GitHub tempcode is available as a parameter, get access_token from server and log in!
if (getAllUrlParams().tempcode) {

let tempCode = getAllUrlParams().tempcode;

// Remove parameter from URL, updating this entry in the client's browser history
history.replaceState(null, '', '/');

// TODO: show loading animation while waiting???

// TODO: refactor getAllUrlParams(), don't need it, just need ONE param!

// For now, save the access token as a global variable (I'm sure this is SUPER wrong though!)
currentAccessToken = getAllUrlParams().access_token;

getJSON('https://api.github.com/user?access_token=' + currentAccessToken)
.then(loginUser).catch(handleError);
// Send tempCode to server in exchange for GitHub access token sent via headers
getTokenFromServer(tempCode)
.then(function(access_token){

// Save the access token as a global variable for now
currentAccessToken = access_token;

// Authenticate with GitHub!
getJSON('https://api.github.com/user?access_token=' + currentAccessToken)
.then(loginUser).catch(handleError);

}, handleError).catch(handleError);

// Otherwise, if user has not yet started the login process,
} else {
Expand Down Expand Up @@ -601,6 +609,27 @@ function get(url) {
});
}

function getTokenFromServer(tempCode) {
return new Promise(function(succeed, fail) {
var req = new XMLHttpRequest();
req.open("GET", '/github-token', true);

// Set header:
req.setRequestHeader('GitHub-Temp-Code', tempCode);

req.addEventListener("load", function() {
if (req.status < 400)
succeed(req.getResponseHeader('GitHub-Token'));
else
fail(new Error("Request failed: " + req.statusText));
});
req.addEventListener("error", function() {
fail(new Error("Network error"));
});
req.send(null);
});
}

// Returns a promise for a POST request, similar to get() above
function postWithGitHubToken(url, postDataObject) {
return new Promise(function(succeed, fail) {
Expand Down
29 changes: 27 additions & 2 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ var port = process.env.PORT || 8000; // Set the default port number to 8000, or
// Use Express to serve everything in the "public" folder as static files
app.use(express.static('public'));

// Save table of temp codes and access tokens, for sending access tokens to the corresponding clients via headers
let clientTokens = {};

// Pass GITHUB_CLIENT_ID to client when requested (using AJAX for now)
// TODO (later): mess around with templating engines and Express .render()?
app.get('/github-client', function (req, res) {
Expand Down Expand Up @@ -48,8 +51,13 @@ function authenticateUser (req, res) {

// TODO (later): check the scopes, because users can authorize less than what my app requested!

// Redirect to home page again but now with the access token!
res.redirect('/?access_token=' + JSON.parse(githubResponseBody).access_token);
// Save received access token to clientTokens to keep it associated with this client
clientTokens[req.query.code] = JSON.parse(githubResponseBody).access_token;

// Redirect to home page again, with the temp code as a URL param
// TODO (later): can I use server-side rendering to accomplish this also???
res.redirect('/?tempcode=' + req.query.code);

});
});

Expand All @@ -58,6 +66,23 @@ function authenticateUser (req, res) {

}

// Pass GitHub access token to corresponding client, if it matches client's temp code
app.get('/github-token', function (req, res) {

let tempCode = req.header('GitHub-Temp-Code');

console.log('Request received for /github-token route for temp code: ' + tempCode);

if ( clientTokens.hasOwnProperty(tempCode) ) {
console.log('\t Temp code MATCHES! Sending access token in response header!');
res.header('GitHub-Token', clientTokens[tempCode]);
}
res.end(); // Double check: can I use res.end() with no body?

console.log("\nclientTokens:\n");
console.log(clientTokens);
});

// Activate the server and listen on our specified port number
server.listen(port, function() {
// Display this message in the server console once the server is active
Expand Down