@@ -54,21 +54,29 @@ var currentGistView = document.getElementById('currentgist');
54
54
GITHUB AUTHENTICATION
55
55
---------------------------------------------------- */
56
56
57
- // If GitHub access_token is available as a parameter, log in!
58
- // TODO: pass the token as a header instead? can client access it that way?
59
- if ( getAllUrlParams ( ) . access_token ) {
60
- console . log ( '*********** AUTHENTICATED!!! **********' ) ;
61
- console . log ( 'access_token from URL params: ' + getAllUrlParams ( ) . access_token ) ;
57
+ // If GitHub tempcode is available as a parameter, get access_token from server and log in!
58
+ if ( getAllUrlParams ( ) . tempcode ) {
59
+
60
+ let tempCode = getAllUrlParams ( ) . tempcode ;
61
+
62
+ // Remove parameter from URL, updating this entry in the client's browser history
63
+ history . replaceState ( null , '' , '/' ) ;
62
64
63
65
// TODO: show loading animation while waiting???
64
-
65
66
// TODO: refactor getAllUrlParams(), don't need it, just need ONE param!
66
-
67
- // For now, save the access token as a global variable (I'm sure this is SUPER wrong though!)
68
- currentAccessToken = getAllUrlParams ( ) . access_token ;
69
67
70
- getJSON ( 'https://api.github.com/user?access_token=' + currentAccessToken )
71
- . then ( loginUser ) . catch ( handleError ) ;
68
+ // Send tempCode to server in exchange for GitHub access token sent via headers
69
+ getTokenFromServer ( tempCode )
70
+ . then ( function ( access_token ) {
71
+
72
+ // Save the access token as a global variable for now
73
+ currentAccessToken = access_token ;
74
+
75
+ // Authenticate with GitHub!
76
+ getJSON ( 'https://api.github.com/user?access_token=' + currentAccessToken )
77
+ . then ( loginUser ) . catch ( handleError ) ;
78
+
79
+ } , handleError ) . catch ( handleError ) ;
72
80
73
81
// Otherwise, if user has not yet started the login process,
74
82
} else {
@@ -601,6 +609,27 @@ function get(url) {
601
609
} ) ;
602
610
}
603
611
612
+ function getTokenFromServer ( tempCode ) {
613
+ return new Promise ( function ( succeed , fail ) {
614
+ var req = new XMLHttpRequest ( ) ;
615
+ req . open ( "GET" , '/github-token' , true ) ;
616
+
617
+ // Set header:
618
+ req . setRequestHeader ( 'GitHub-Temp-Code' , tempCode ) ;
619
+
620
+ req . addEventListener ( "load" , function ( ) {
621
+ if ( req . status < 400 )
622
+ succeed ( req . getResponseHeader ( 'GitHub-Token' ) ) ;
623
+ else
624
+ fail ( new Error ( "Request failed: " + req . statusText ) ) ;
625
+ } ) ;
626
+ req . addEventListener ( "error" , function ( ) {
627
+ fail ( new Error ( "Network error" ) ) ;
628
+ } ) ;
629
+ req . send ( null ) ;
630
+ } ) ;
631
+ }
632
+
604
633
// Returns a promise for a POST request, similar to get() above
605
634
function postWithGitHubToken ( url , postDataObject ) {
606
635
return new Promise ( function ( succeed , fail ) {
0 commit comments