Skip to content

Commit

Permalink
✨ feat: migrate gapi to gsi oauth2
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelcaxias committed Feb 20, 2023
1 parent 41e108e commit 225e2f0
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 59 deletions.
72 changes: 72 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"framer-motion": "^7.6.1",
"gapi-script": "^1.2.0",
"node-sass": "^7.0.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand All @@ -34,6 +33,7 @@
"eject": "react-scripts eject"
},
"devDependencies": {
"axios": "^1.3.3",
"cypress": "^9.5.0",
"eslint": "^8.26.0",
"eslint-plugin-react": "^7.31.10",
Expand Down
1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<meta property="twitter:description"
content="Basta copiar a sua agenda do dia no seu Slack e colar aqui, nós vamos adicionar cada momento do seu dia com um único clique!">
<meta property="twitter:image" content="https://i.imgur.com/pl7D97r.png">
<script src="https://apis.google.com/js/api.js" async defer></script>
</head>

<body>
Expand Down
2 changes: 1 addition & 1 deletion src/components/AddEventButton/AddEventButton.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Snackbar from '@mui/material/Snackbar';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

import { gapi } from 'gapi-script';
const { gapi } = window;

import Alert from '../Alert/Alert';

Expand Down
52 changes: 31 additions & 21 deletions src/components/LoginButton/LoginButton.jsx
Original file line number Diff line number Diff line change
@@ -1,52 +1,62 @@
import React, { useContext } from 'react';
import { MyContext } from '../../context/Provider';

import { Button } from '@mui/material';

import { FcGoogle } from 'react-icons/fc';
import { ImExit } from 'react-icons/im';

import { gapi } from 'gapi-script';

import { useNavigate } from 'react-router-dom';

import { MyContext } from '../../context/Provider';
import { useGoogleLogin, googleLogout } from '@react-oauth/google';
import axios from 'axios';

import './LoginButton.scss';

const blankImage = 'https://i.imgur.com/qEgz28w.png';
const SCOPES = 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.profile';

export default function LoginButton() {
const { isSignedIn, setUserImage, changeSignedInState } = useContext(MyContext);
const { isSignedIn, setUserImage, setUserName, setUserEmail, changeSignedInState } = useContext(MyContext);
const navigate = useNavigate();

const handleAuthClick = async () => {
// Faz o Login
await gapi.auth2.getAuthInstance().signIn();
const login = useGoogleLogin({
scope: SCOPES,
onSuccess: (response) => signInWorkflow(response),
onError: (error) => console.error(error),
});

// Depois verifica se o usuário está logado, e seta esse valor em isSignedIn
await gapi.auth2.getAuthInstance().isSignedIn.listen(changeSignedInState);
await changeSignedInState(gapi.auth2.getAuthInstance().isSignedIn.get());

// Agora pega a imagem do usuário e seta em userImage
const profileImage = gapi.auth2.getAuthInstance().currentUser.get()
.getBasicProfile().getImageUrl();
const signInWorkflow = async (response) => {
changeSignedInState(true);
const userInfo = await requestUserInfo(response);
updateUserInfo(userInfo.data);
navigate('/scheduler');
};

setUserImage(profileImage);
const updateUserInfo = (userInfo) => {
const { picture, name, email } = userInfo;
setUserImage(picture);
setUserName(name);
setUserEmail(email);
};

// Finalmente navega para a página de schedule
navigate('/scheduler');
const requestUserInfo = async (response) => {
const gettingUserInfo = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: {
Authorization: `Bearer ${response.access_token}`
}
});
return gettingUserInfo;
};

const handleSignoutClick = () => {
gapi.auth2.getAuthInstance().signOut();
googleLogout();
setUserImage(blankImage);
navigate('/');
};

const connectButton = (
<Button
className="login-logout login-button"
onClick={ handleAuthClick }
onClick={ login }
size="large"
>
<div className="google-icon-div">
Expand Down
5 changes: 3 additions & 2 deletions src/components/Menu/Menu.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { gapi } from 'gapi-script';
const { gapi } = window;
import { CgLogOut } from 'react-icons/cg';
import { useNavigate } from 'react-router-dom';
import { googleLogout } from '@react-oauth/google';

import {
Dialog,
Expand All @@ -28,7 +29,7 @@ const Menu = (props) => {
};

const handleLogout = () => {
gapi.auth2.getAuthInstance().signOut();
googleLogout();
changeSignedInState(false);

onClose();
Expand Down
56 changes: 25 additions & 31 deletions src/context/Provider.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import PropTypes from 'prop-types';
import React, { useState, useEffect, createContext, useRef } from 'react';
import { gapi } from 'gapi-script';
const { gapi } = window;
import usePersistedState from '../hooks/usePersistedState';

const blankImage = 'https://i.imgur.com/qEgz28w.png';
Expand Down Expand Up @@ -36,6 +36,8 @@ export function Provider({ children }) {
scheduleValue,
setMinutes,
setUserImage,
setUserName,
setUserEmail,
userImage,
userName,
userEmail,
Expand All @@ -49,38 +51,30 @@ export function Provider({ children }) {
};

useEffect(() => {
const apiKey = REACT_APP_API_KEY || '';
const clientId = REACT_APP_CLIENT_ID || '';

try {
initalizeGapi();
} catch (error) {
console.error('Error intialize: ', error);
} finally {
setLoading(false);
}
}, []);

const initalizeGapi = async () => {
gapi.load('client:auth2', async () => {
try {
await gapi.client.init({
apiKey,
clientId,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES,
});
gapi.auth2.getAuthInstance().isSignedIn.listen(changeSignedInState);
changeSignedInState(gapi.auth2.getAuthInstance().isSignedIn.get());

await gapi.client.load('calendar', 'v3');
if (isSignedIn) {
setUserImage(gapi.auth2.getAuthInstance().currentUser.get()
.getBasicProfile().getImageUrl());

setUserName(gapi.auth2.getAuthInstance().currentUser.get()
.getBasicProfile().getName());

setUserEmail(gapi.auth2.getAuthInstance().currentUser.get()
.getBasicProfile().getEmail());
}

setLoading(false);
} catch (error) {
console.log('Error intialize: ', error);
}
const apiKey = REACT_APP_API_KEY || '';
const clientId = REACT_APP_CLIENT_ID || '';

await gapi.client.init({
apiKey,
clientId,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES,
});

await gapi.client.load('calendar', 'v3');
});
}, [setUserImage, isSignedIn]);
};

return (
<MyContext.Provider value={ context }>
Expand Down
10 changes: 7 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from './context/Provider';
import App from './App';
import { GoogleOAuthProvider } from '@react-oauth/google';
const { REACT_APP_CLIENT_ID } = process.env;

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
<React.StrictMode>
<Provider>
<App />
</Provider>
<GoogleOAuthProvider clientId={REACT_APP_CLIENT_ID}>
<Provider>
<App />
</Provider>
</GoogleOAuthProvider>
</React.StrictMode>
);

0 comments on commit 225e2f0

Please sign in to comment.