forked from jjNford/chrome-ex-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth2.js
91 lines (81 loc) · 3.31 KB
/
oauth2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
(function() {
window.oauth2 = {
access_token_url: "https://github.com/login/oauth/access_token",
authorization_url: "https://github.com/login/oauth/authorize",
client_id: "911fa741a8b8dac7d28c",
client_secret: "e13f2f8ba4d9892eb231b4fcf3257013736327d1",
redirect_url: "https://github.com/robots.txt",
scopes: [],
key: "oauth2_token",
/**
* Starts the authorization process.
*/
start: function() {
window.close();
var url = this.authorization_url + "?client_id=" + this.client_id + "&redirect_uri=" + this.redirect_url + "&scopes=";
for(var i in this.scopes) {
url += this.scopes[i];
}
chrome.tabs.create({url: url, active: true});
},
/**
* Finishes the oauth2 process by exchanging the given authorization code for an
* authorization token. The authroiztion token is saved to the browsers local storage.
* If the redirect page does not return an authorization code or an error occures when
* exchanging the authorization code for an authorization token then the oauth2 process dies
* and the authorization tab is closed.
*
* @param url The url of the redirect page specified in the authorization request.
*/
finish: function(url) {
function removeTab() {
chrome.tabs.getCurrent(function(tab) {
chrome.tabs.remove(tab.id);
});
};
if(url.match(/\?error=(.+)/)) {
removeTab();
} else {
var code = url.match(/\?code=([\w\/\-]+)/)[1];
var that = this;
var data = new FormData();
data.append('client_id', this.client_id);
data.append('client_secret', this.client_secret);
data.append('code', code);
// Send request for authorization token.
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function(event) {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
if(xhr.responseText.match(/error=/)) {
removeTab();
} else {
var token = xhr.responseText.match(/access_token=([^&]*)/)[1];
window.localStorage.setItem(that.key, token);
removeTab();
}
} else {
removeTab();
}
}
});
xhr.open('POST', this.access_token_url, true);
xhr.send(data);
}
},
/**
* Retreives the authorization token from local storage.
*
* @return Authorization token if it exists, null if not.
*/
getToken: function() {
return window.localStorage.getItem(this.key);
},
/**
* Clears the authorization token from the local storage.
*/
clearToken: function() {
delete window.localStorage.removeItem(this.key);
}
}
})();