Last active
July 16, 2019 22:49
-
-
Save kirpalmakanga/a6e874ee885a82a8dfc056d5a4fcd43f to your computer and use it in GitHub Desktop.
Loading Google API and auth service
This file contains 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
const API_URL = 'https://apis.google.com/js/api.js'; | |
const GOOGLE_CLIENT_ID = ''; | |
const GOOGLE_CLIENT_SCOPE = ''; | |
function loadScript(src) { | |
return new Promise((resolve, reject) => { | |
try { | |
if (!document.querySelector(`script[src="${src}"]`)) { | |
const js = document.createElement('script'); | |
document.body.appendChild(js); | |
js.src = src; | |
js.onload = () => resolve(true); | |
} else { | |
resolve(false); | |
} | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
} | |
export const loadAPI = async () => { | |
const initServices = await loadScript(API_URL); | |
const { gapi } = window; | |
if (initServices) { | |
await new Promise((callback) => | |
gapi.load('client:auth2', { callback }) | |
); | |
} | |
return gapi; | |
}; | |
export const getAuthInstance = () => { | |
const { auth2 } = window.gapi; | |
const params = { | |
clientId: GOOGLE_CLIENT_ID, | |
scope: GOOGLE_CLIENT_SCOPE | |
}; | |
return auth2.init(params); | |
}; | |
export const loadAuth = () => { | |
const GoogleAuth = getAuthInstance(); | |
return GoogleAuth; | |
}; | |
export const getSignedInUser = () => { | |
const GoogleAuth = getAuthInstance(); | |
const isSignedIn = GoogleAuth.isSignedIn.get(); | |
const currentUser = GoogleAuth.currentUser.get(); | |
const { | |
w3: { Eea: id, Paa: picture = '', ig = '', ofa = '' } = {} | |
} = currentUser; | |
const name = ig || ofa; | |
const { | |
id_token: idToken, | |
access_token: accessToken | |
} = currentUser.getAuthResponse(true); | |
console.log('user', { idToken, accessToken }); | |
return { | |
isSignedIn, | |
idToken, | |
accessToken, | |
user: { | |
id, | |
picture, | |
name | |
} | |
}; | |
}; | |
export const signIn = async () => { | |
await getAuthInstance().signIn(); | |
return getSignedInUser(); | |
}; | |
export const signOut = () => getAuthInstance().signOut(); | |
export const listenAuth = (callback) => | |
getAuthInstance().isSignedIn.listen( | |
(isSignedIn) => isSignedIn && callback(getSignedInUser()) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment