|
| 1 | +/* exported getAccessToken */ |
| 2 | + |
| 3 | +const REDIRECT_URL = browser.identity.getRedirectURL(); |
| 4 | +const CLIENT_ID = "12428"; |
| 5 | +const KEY = "f26RUH3uoCiokrEYNeDf9Q((" |
| 6 | +const SCOPES = ["read_inbox", "noexpire"]; |
| 7 | +const AUTH_URL = |
| 8 | +`https://stackoverflow.com/oauth/dialog? |
| 9 | +client_id=${CLIENT_ID}&key=${KEY}&redirect_uri=${encodeURIComponent(REDIRECT_URL)} |
| 10 | +&scope=${encodeURIComponent(SCOPES.join(' '))}`; |
| 11 | + |
| 12 | +const VALIDATION_BASE_URL="https://api.stackexchange.com/2.2/"; |
| 13 | + |
| 14 | +function extractAccessToken(redirectUri) { |
| 15 | + let m = redirectUri.match(/[#?](.*)/); |
| 16 | + if (!m || m.length < 1) |
| 17 | + return null; |
| 18 | + let params = new URLSearchParams(m[1].split("#")[0]); |
| 19 | + return params.get("access_token"); |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | +Validate the token contained in redirectURL. |
| 24 | +This follows essentially the process here: |
| 25 | +https://developers.google.com/identity/protocols/OAuth2UserAgent#tokeninfo-validation |
| 26 | +- make a GET request to the validation URL, including the access token |
| 27 | +- if the response is 200, and contains an "aud" property, and that property |
| 28 | +matches the clientID, then the response is valid |
| 29 | +- otherwise it is not valid |
| 30 | +
|
| 31 | +Note that the Google page talks about an "audience" property, but in fact |
| 32 | +it seems to be "aud". |
| 33 | +*/ |
| 34 | +function validate(redirectURL) { |
| 35 | + const accessToken = extractAccessToken(redirectURL); |
| 36 | + console.log(accessToken+ "access") |
| 37 | + if (!accessToken) { |
| 38 | + throw "Authorization failure"; |
| 39 | + } |
| 40 | + const validationURL = `${VALIDATION_BASE_URL}access_tokens/${accessToken}`; |
| 41 | + const validationRequest = new Request(validationURL, { |
| 42 | + method: "GET" |
| 43 | + }); |
| 44 | + |
| 45 | + function checkResponse(response) { |
| 46 | + return new Promise((resolve, reject) => { |
| 47 | + if (response.status != 200) { |
| 48 | + reject("Token validation error"); |
| 49 | + } |
| 50 | + response.json().then((json) => { |
| 51 | + if (json.items) { |
| 52 | + resolve(accessToken); |
| 53 | + } else { |
| 54 | + reject("Token validation error"); |
| 55 | + } |
| 56 | + }); |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + return fetch(validationRequest).then(checkResponse); |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | +Authenticate and authorize using browser.identity.launchWebAuthFlow(). |
| 65 | +If successful, this resolves with a redirectURL string that contains |
| 66 | +an access token. |
| 67 | +*/ |
| 68 | +function authorize() { |
| 69 | + console.log(AUTH_URL) |
| 70 | + return browser.identity.launchWebAuthFlow({ |
| 71 | + interactive: true, |
| 72 | + url: AUTH_URL |
| 73 | + }); |
| 74 | +} |
| 75 | + |
| 76 | +function getAccessToken() { |
| 77 | + return authorize() |
| 78 | +} |
0 commit comments