Repository: Sivanesh-S/react-google-authentication Branch: master Commit: dd6c77a369e4 Files: 18 Total size: 16.2 KB Directory structure: gitextract_on_cxxeo/ ├── .gitignore ├── LICENSE ├── README.md ├── package.json ├── public/ │ ├── index.html │ ├── manifest.json │ └── robots.txt └── src/ ├── App.css ├── App.js ├── components/ │ ├── Login.js │ ├── LoginHooks.js │ ├── Logout.js │ └── LogoutHooks.js ├── index.css ├── index.js ├── serviceWorker.js ├── setupTests.js └── utils/ └── refreshToken.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2021 Sivanesh Shanmugam Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ FYI: This uses the old approach as shown in the live demo. But still functional. If you prefer for the new Google Auth then this might not be the best place for you. # React Google authentication demo [Live Demo](https://sivanesh-s.github.io/react-google-authentication/) Refer this [blog](https://dev.to/sivaneshs/add-google-login-to-your-react-apps-in-10-mins-4del) for documentation. ================================================ FILE: package.json ================================================ { "name": "my-react-google-login", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-google-login": "^5.1.20", "react-scripts": "3.4.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "predeploy": "npm run build", "deploy": "gh-pages -d build" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "homepage": "https://sivanesh-s.github.io/react-google-authentication", "devDependencies": { "gh-pages": "^3.1.0" } } ================================================ FILE: public/index.html ================================================ React App
================================================ FILE: public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: src/App.css ================================================ .App { text-align: center; margin-top: 20px; } /* Hooks button */ .button { cursor: pointer; display: block; font-size: 1.3em; box-sizing: content-box; margin: 20px auto 0px; width: 70%; padding: 15px 20px; border-radius: 24px; border-color: transparent; background-color: white; /* box-shadow: 0px 16px 60px rgba(78, 79, 114, 0.1); */ box-shadow: 0px 16px 60px rgba(78, 79, 114, 0.08); position: relative; } .buttonText { color: #4285f4; font-weight: bolder; } .icon { height: 25px; width: 25px; margin-right: 0px; position: absolute; left: 30px; align-items: center; } ================================================ FILE: src/App.js ================================================ import React from 'react'; import './App.css'; import Login from './components/Login'; import Logout from './components/Logout'; import LoginHooks from './components/LoginHooks'; import LogoutHooks from './components/LogoutHooks'; function App() { return (

The Components way


The Hooks way


If it does helped you feel free to star{' '} Github Repo {' '} 😉
); } export default App; ================================================ FILE: src/components/Login.js ================================================ import React from 'react'; import { GoogleLogin } from 'react-google-login'; // refresh token import { refreshTokenSetup } from '../utils/refreshToken'; const clientId = '707788443358-u05p46nssla3l8tmn58tpo9r5sommgks.apps.googleusercontent.com'; function Login() { const onSuccess = (res) => { console.log('Login Success: currentUser:', res.profileObj); alert( `Logged in successfully welcome ${res.profileObj.name} 😍. \n See console for full profile object.` ); refreshTokenSetup(res); }; const onFailure = (res) => { console.log('Login failed: res:', res); alert( `Failed to login. 😢 Please ping this to repo owner twitter.com/sivanesh_fiz` ); }; return (
); } export default Login; ================================================ FILE: src/components/LoginHooks.js ================================================ import React from 'react'; import { useGoogleLogin } from 'react-google-login'; // refresh token import { refreshTokenSetup } from '../utils/refreshToken'; const clientId = '707788443358-u05p46nssla3l8tmn58tpo9r5sommgks.apps.googleusercontent.com'; function LoginHooks() { const onSuccess = (res) => { console.log('Login Success: currentUser:', res.profileObj); alert( `Logged in successfully welcome ${res.profileObj.name} 😍. \n See console for full profile object.` ); refreshTokenSetup(res); }; const onFailure = (res) => { console.log('Login failed: res:', res); alert( `Failed to login. 😢 Please ping this to repo owner twitter.com/sivanesh_fiz` ); }; const { signIn } = useGoogleLogin({ onSuccess, onFailure, clientId, isSignedIn: true, accessType: 'offline', // responseType: 'code', // prompt: 'consent', }); return ( ); } export default LoginHooks; ================================================ FILE: src/components/Logout.js ================================================ import React from 'react'; import { GoogleLogout } from 'react-google-login'; const clientId = '707788443358-u05p46nssla3l8tmn58tpo9r5sommgks.apps.googleusercontent.com'; function Logout() { const onSuccess = () => { console.log('Logout made successfully'); alert('Logout made successfully ✌'); }; return (
); } export default Logout; ================================================ FILE: src/components/LogoutHooks.js ================================================ import React from 'react'; import { useGoogleLogout } from 'react-google-login'; const clientId = '707788443358-u05p46nssla3l8tmn58tpo9r5sommgks.apps.googleusercontent.com'; function LogoutHooks() { const onLogoutSuccess = (res) => { console.log('Logged out Success'); alert('Logged out Successfully ✌'); }; const onFailure = () => { console.log('Handle failure cases'); }; const { signOut } = useGoogleLogout({ clientId, onLogoutSuccess, onFailure, }); return ( ); } export default LogoutHooks; ================================================ FILE: src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render( , document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); ================================================ FILE: src/serviceWorker.js ================================================ // This optional code is used to register a service worker. // register() is not called by default. // This lets the app load faster on subsequent visits in production, and gives // it offline capabilities. However, it also means that developers (and users) // will only see deployed updates on subsequent visits to a page, after all the // existing tabs open on the page have been closed, since previously cached // resources are updated in the background. // To learn more about the benefits of this model and instructions on how to // opt-in, read https://bit.ly/CRA-PWA const isLocalhost = Boolean( window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.0/8 are considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); export function register(config) { if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { // The URL constructor is available in all browsers that support SW. const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); if (publicUrl.origin !== window.location.origin) { // Our service worker won't work if PUBLIC_URL is on a different origin // from what our page is served on. This might happen if a CDN is used to // serve assets; see https://github.com/facebook/create-react-app/issues/2374 return; } window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; if (isLocalhost) { // This is running on localhost. Let's check if a service worker still exists or not. checkValidServiceWorker(swUrl, config); // Add some additional logging to localhost, pointing developers to the // service worker/PWA documentation. navigator.serviceWorker.ready.then(() => { console.log( 'This web app is being served cache-first by a service ' + 'worker. To learn more, visit https://bit.ly/CRA-PWA' ); }); } else { // Is not localhost. Just register service worker registerValidSW(swUrl, config); } }); } } function registerValidSW(swUrl, config) { navigator.serviceWorker .register(swUrl) .then(registration => { registration.onupdatefound = () => { const installingWorker = registration.installing; if (installingWorker == null) { return; } installingWorker.onstatechange = () => { if (installingWorker.state === 'installed') { if (navigator.serviceWorker.controller) { // At this point, the updated precached content has been fetched, // but the previous service worker will still serve the older // content until all client tabs are closed. console.log( 'New content is available and will be used when all ' + 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' ); // Execute callback if (config && config.onUpdate) { config.onUpdate(registration); } } else { // At this point, everything has been precached. // It's the perfect time to display a // "Content is cached for offline use." message. console.log('Content is cached for offline use.'); // Execute callback if (config && config.onSuccess) { config.onSuccess(registration); } } } }; }; }) .catch(error => { console.error('Error during service worker registration:', error); }); } function checkValidServiceWorker(swUrl, config) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl, { headers: { 'Service-Worker': 'script' }, }) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl, config); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); } export function unregister() { if ('serviceWorker' in navigator) { navigator.serviceWorker.ready .then(registration => { registration.unregister(); }) .catch(error => { console.error(error.message); }); } } ================================================ FILE: src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom/extend-expect'; ================================================ FILE: src/utils/refreshToken.js ================================================ export const refreshTokenSetup = (res) => { // Timing to renew access token let refreshTiming = (res.tokenObj.expires_in || 3600 - 5 * 60) * 1000; const refreshToken = async () => { const newAuthRes = await res.reloadAuthResponse(); refreshTiming = (newAuthRes.expires_in || 3600 - 5 * 60) * 1000; console.log('newAuthRes:', newAuthRes); // saveUserToken(newAuthRes.access_token); <-- save new token localStorage.setItem('authToken', newAuthRes.id_token); // Setup the other timer after the first one setTimeout(refreshToken, refreshTiming); }; // Setup first refresh timer setTimeout(refreshToken, refreshTiming); };