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
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
================================================
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 (
<div className="App">
<h2>The Components way</h2>
<Login />
<br />
<Logout />
<h2>The Hooks way</h2>
<LoginHooks />
<LogoutHooks />
<br />
If it does helped you feel free to star{' '}
<a href="https://github.com/Sivanesh-S/react-google-authentication">
Github Repo
</a>{' '}
😉
</div>
);
}
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 (
<div>
<GoogleLogin
clientId={clientId}
buttonText="Login"
onSuccess={onSuccess}
onFailure={onFailure}
cookiePolicy={'single_host_origin'}
style={{ marginTop: '100px' }}
isSignedIn={true}
/>
</div>
);
}
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 (
<button onClick={signIn} className="button">
<img src="icons/google.svg" alt="google login" className="icon"></img>
<span className="buttonText">Sign in with Google</span>
</button>
);
}
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 (
<div>
<GoogleLogout
clientId={clientId}
buttonText="Logout"
onLogoutSuccess={onSuccess}
></GoogleLogout>
</div>
);
}
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 (
<button onClick={signOut} className="button">
<img src="icons/google.svg" alt="google login" className="icon"></img>
<span className="buttonText">Sign out</span>
</button>
);
}
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(
<React.StrictMode>
<App />
</React.StrictMode>,
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);
};
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
SYMBOL INDEX (9 symbols across 6 files)
FILE: src/App.js
function App (line 8) | function App() {
FILE: src/components/Login.js
function Login (line 10) | function Login() {
FILE: src/components/LoginHooks.js
function LoginHooks (line 10) | function LoginHooks() {
FILE: src/components/Logout.js
function Logout (line 7) | function Logout() {
FILE: src/components/LogoutHooks.js
function LogoutHooks (line 7) | function LogoutHooks() {
FILE: src/serviceWorker.js
function register (line 23) | function register(config) {
function registerValidSW (line 57) | function registerValidSW(swUrl, config) {
function checkValidServiceWorker (line 101) | function checkValidServiceWorker(swUrl, config) {
function unregister (line 131) | function unregister() {
Condensed preview — 18 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (18K chars).
[
{
"path": ".gitignore",
"chars": 310,
"preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
},
{
"path": "LICENSE",
"chars": 1075,
"preview": "MIT License\n\nCopyright (c) 2021 Sivanesh Shanmugam\n\nPermission is hereby granted, free of charge, to any person obtainin"
},
{
"path": "README.md",
"chars": 391,
"preview": "FYI: This uses the old approach as shown in the live demo. But still functional. If you prefer for the new Google Auth t"
},
{
"path": "package.json",
"chars": 990,
"preview": "{\n \"name\": \"my-react-google-login\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"@testing-library/"
},
{
"path": "public/index.html",
"chars": 1721,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.i"
},
{
"path": "public/manifest.json",
"chars": 492,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "public/robots.txt",
"chars": 67,
"preview": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
},
{
"path": "src/App.css",
"chars": 620,
"preview": ".App {\n text-align: center;\n margin-top: 20px;\n}\n\n/* Hooks button */\n.button {\n cursor: pointer;\n display: block;\n "
},
{
"path": "src/App.js",
"chars": 660,
"preview": "import React from 'react';\nimport './App.css';\nimport Login from './components/Login';\nimport Logout from './components/"
},
{
"path": "src/components/Login.js",
"chars": 1018,
"preview": "import React from 'react';\n\nimport { GoogleLogin } from 'react-google-login';\n// refresh token\nimport { refreshTokenSetu"
},
{
"path": "src/components/LoginHooks.js",
"chars": 1154,
"preview": "import React from 'react';\nimport { useGoogleLogin } from 'react-google-login';\n\n// refresh token\nimport { refreshTokenS"
},
{
"path": "src/components/Logout.js",
"chars": 513,
"preview": "import React from 'react';\nimport { GoogleLogout } from 'react-google-login';\n\nconst clientId =\n '707788443358-u05p46ns"
},
{
"path": "src/components/LogoutHooks.js",
"chars": 737,
"preview": "import React from 'react';\nimport { useGoogleLogout } from 'react-google-login';\n\nconst clientId =\n '707788443358-u05p4"
},
{
"path": "src/index.css",
"chars": 366,
"preview": "body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Can"
},
{
"path": "src/index.js",
"chars": 503,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as "
},
{
"path": "src/serviceWorker.js",
"chars": 5086,
"preview": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the ap"
},
{
"path": "src/setupTests.js",
"chars": 255,
"preview": "// jest-dom adds custom jest matchers for asserting on DOM nodes.\n// allows you to do things like:\n// expect(element).to"
},
{
"path": "src/utils/refreshToken.js",
"chars": 662,
"preview": "export const refreshTokenSetup = (res) => {\n // Timing to renew access token\n let refreshTiming = (res.tokenObj.expire"
}
]
About this extraction
This page contains the full source code of the Sivanesh-S/react-google-authentication GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 18 files (16.2 KB), approximately 4.6k tokens, and a symbol index with 9 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.