Created
August 10, 2016 19:50
-
-
Save ashlinchak/ea385bd649f0f8e2d8bd800f936f1194 to your computer and use it in GitHub Desktop.
Background page for authentication flow in the chrome extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
do -> | |
BM = window.BM | |
storage = chrome.storage.local | |
authBaseUrl = BM.serverURL + '/oauth/authorize' | |
onTokenSet = (token) -> | |
console.debug 'token set to', token | |
return | |
onLoginFailed = (err) -> | |
console.error 'login failed:', err and err.message, err | |
return | |
authParams = -> | |
{ | |
client_id: BM.clientId | |
response_type: 'token' | |
redirect_uri: chrome.identity.getRedirectURL('provider_cb') | |
} | |
getAuthUrl = -> | |
url = authBaseUrl | |
params = authParams() | |
Object.keys(params).forEach (key, index) -> | |
url += (if index == 0 then '?' else '&') + key + '=' + params[key] | |
return | |
url | |
login = (cb) -> | |
chrome.identity.launchWebAuthFlow { | |
url: getAuthUrl() | |
interactive: true | |
}, (resp) -> | |
err = chrome.runtime.lastError | |
token = resp and resp.match(/\#(?:access_token)\=([\S\s]*?)\&/)[1] | |
if token | |
storage.set { token: token }, -> | |
cb and cb(null, token) | |
onTokenSet token | |
return | |
else | |
cb and cb(err) | |
onLoginFailed err | |
return | |
return | |
window.login = login | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment