Last active
May 14, 2019 11:23
-
-
Save Salamit/f38c7bd32fc5aa2e086f7e8d3d6591eb to your computer and use it in GitHub Desktop.
Authenticate your React, Meteor, Vulcanjs App using OAuth2 for Google Spreadsheets (May 2019)
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
import React, { useState, useEffect, PropTypes, Component, useContext } from 'react'; | |
import { registerComponent, Components } from 'meteor/vulcan:core'; | |
import { withRouter } from 'react-router'; | |
import AppContext from '../common/AppContext'; | |
//credits: http://www.gethugames.in/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html | |
function popUpAuth(url) { | |
const win = window.open(url, "Authentication", 'width=500,height=600'); | |
const REDIRECT = "http://localhost:3000"; | |
var pollTimer = window.setInterval(function() { | |
try { | |
if (win.document.URL.indexOf(REDIRECT) != -1 ){ | |
window.clearInterval(pollTimer); | |
var url = win.document.URL; | |
const array = url.split('&'); | |
const code = array[0].split('='); | |
const codeValue = code[1]; | |
} | |
} catch(e) { | |
} | |
}, 100) | |
} | |
function App (props) { | |
const [auth, setAuth] = useState(false); | |
const [authUrl, setAuthUrl] = useState(); | |
//Run GoogleAuth | |
const getGoogleAuth = () => { | |
//calls GoogleAuth on the server file main.js | |
const url = Meteor.call('googleAuth', (error, url) => { | |
if (error) { | |
throw new Meteor.Error('Error', 'Authentication failed'); | |
} else { | |
setAuth(true) | |
setAuthUrl(url) | |
popUpAuth(url) | |
} | |
}); | |
} | |
return ( | |
<AppContext.Provider value={authUrl}> | |
<div> | |
<button onClick={() => {getGoogleAuth()}}>Google Auth</button> | |
{/* <NewWindow/> */} | |
</div> | |
</AppContext.Provider> | |
); | |
} | |
export default withRouter(App); | |
registerComponent({name: 'App', component: App, hocs: [withRouter]}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment