Skip to content

Commit

Permalink
Merge pull request #74 from michaelcaxias/fix/login-validation
Browse files Browse the repository at this point in the history
fix: check if user is logged in validation
  • Loading branch information
michaelcaxias authored Mar 6, 2023
2 parents 070fbe0 + 54ae2dc commit f521d06
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 50 deletions.
26 changes: 18 additions & 8 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,30 @@ import Home from './pages/Home/Home';
import PrivacyPolicy from './pages/PrivacyPolicy/PrivacyPolicy';
import TermsAndConditions from './pages/TermsAndConditions/TermsAndConditions';
import PrivateRoute from './context/PrivateRoute';
import LoginWrap from './wrapper/LoginWrap';

import './App.scss';

export default function App() {
return (
<Router>
<Routes>
<Route path="/" element={ <Home /> } />
<Route path="/scheduler" element={ <PrivateRoute><Scheduler /></PrivateRoute> } />
<Route path="/login" element={ <Login /> } />
<Route path="/privacy-policy" element={ <PrivacyPolicy /> } />
<Route path="/terms-and-conditions" element={ <TermsAndConditions /> } />
<Route path="*" element={ <Page404 /> } />
</Routes>
<LoginWrap>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/scheduler"
element={
<PrivateRoute>
<Scheduler />
</PrivateRoute>
}
/>
<Route path="/login" element={<Login />} />
<Route path="/privacy-policy" element={<PrivacyPolicy />} />
<Route path="/terms-and-conditions" element={<TermsAndConditions />} />
<Route path="*" element={<Page404 />} />
</Routes>
</LoginWrap>
</Router>
);
}
35 changes: 19 additions & 16 deletions src/components/Header/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { useNavigate } from 'react-router';
import './Header.scss';

const Header = () => {
const { userImage, userName, userEmail, isSignedIn } = useContext(MyContext);
const { userInfo, isSignedIn } = useContext(MyContext);
const [open, setOpen] = React.useState(false);
const navigate = useNavigate();

Expand All @@ -30,30 +30,33 @@ const Header = () => {
onClick={() => navigate('/')}
tabIndex={0}
role="link"
aria-label="Voltar para página inicial"
aria-label="Voltar para página inicial"
>
<img src={images.logo} draggable={false}/>
<img src={images.logo} draggable={false} />
<h1>Trybe Scheduler</h1>
</div>

<div
className="app__flex login__user-info"
tabIndex={0}
role="button"
>
<div className="app__flex login__user-info" tabIndex={0} role="button">
{isSignedIn ? (
<>
<div className="app__flex login__user-logged" onClick={handleClickOpen}>
<div className="app__flex login__user-info-google">
<h4>{userName}</h4>
<h5>{userEmail}</h5>
</div>
<div className="app__flex login__user-logged" onClick={handleClickOpen}>
<div className="app__flex login__user-info-google">
<h4>{userInfo.name}</h4>
<h5>{userInfo.email}</h5>
</div>

<Avatar alt="Usuário Google" src={userImage} style={{pointerEvents: 'none'}}/>
</div>
<Avatar
alt="Usuário Google"
src={userInfo.picture}
style={{ pointerEvents: 'none' }}
/>
</div>
</>
) : (
<div className="app__flex login__user-logout" onClick={() => navigate('/login')}>
<div
className="app__flex login__user-logout"
onClick={() => navigate('/login')}
>
<h4>Entrar</h4>
<FiLogIn className="icon" />
</div>
Expand Down
7 changes: 2 additions & 5 deletions src/components/LoginButton/LoginButton.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import './LoginButton.scss';
const SCOPES = 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.profile';

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

const login = useGoogleLogin({
Expand All @@ -31,10 +31,7 @@ export default function LoginButton() {
};

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

const requestUserInfo = async (response) => {
Expand Down
2 changes: 1 addition & 1 deletion src/context/PrivateRoute.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const PrivateRoute = ({ children }) => {

function validateWorkflow() {
if (!isSignedIn) {
return <Navigate to="/login" />;
return <Navigate to="/" />;
}
return children;
}
Expand Down
32 changes: 19 additions & 13 deletions src/context/Provider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,19 @@ export function Provider({ children }) {
const [scheduleValue, changeScheduleValue] = useState('');
const [links, setLinks] = useState([]);

const [userImage, setUserImage] = usePersistedState('userImage', blankImage);
const [userName, setUserName] = usePersistedState('userName', 'Carregando...');
const [userEmail, setUserEmail] = usePersistedState('userEmail', 'Carregando...');
const [userInfo, setUserInfo] = useState({ picture: blankImage, name: 'Carregando...', email: 'Carregando...' });

const [loading, setLoading] = useState(false);
const [loading, setLoading] = useState(true);

const scheduleElementRef = useRef(null);

const context = useMemo(() => ({
const context = useMemo(
() => ({
minutes,
isSignedIn,
colorId,
scheduleValue,
setMinutes,
setUserImage,
setUserName,
setUserEmail,
userImage,
userName,
userEmail,
changeSignedInState,
setColorId,
changeScheduleValue,
Expand All @@ -45,8 +38,21 @@ export function Provider({ children }) {
loading,
setLoading,
accessToken,
setAccessToken
}), [accessToken, minutes, isSignedIn, colorId, scheduleValue, userImage, userName, userEmail, links, loading]);
setAccessToken,
userInfo,
setUserInfo,
}),
[
accessToken,
minutes,
isSignedIn,
colorId,
scheduleValue,
links,
loading,
userInfo,
]
);

return (
<MyContext.Provider value={ context }>
Expand Down
12 changes: 5 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@ const { REACT_APP_CLIENT_ID } = process.env;
const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
<React.StrictMode>
<GoogleOAuthProvider clientId={REACT_APP_CLIENT_ID}>
<Provider>
<App />
</Provider>
</GoogleOAuthProvider>
</React.StrictMode>
<GoogleOAuthProvider clientId={REACT_APP_CLIENT_ID}>
<Provider>
<App />
</Provider>
</GoogleOAuthProvider>
);
51 changes: 51 additions & 0 deletions src/wrapper/LoginWrap.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React, { useContext, useEffect } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import { MyContext } from '../context/Provider';
import { useNavigate } from 'react-router';
import Loading from '../components/Loading/Loading';

export default function LoginWrap({ children }) {
const { setUserInfo, changeSignedInState, loading, setLoading } = useContext(MyContext);
const navigate = useNavigate();

const requestUserInfo = async () => {
const accessToken = localStorage.getItem('accessToken');

try {
const userInfo = await axios.get(
'https://www.googleapis.com/oauth2/v3/userinfo',
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);

setUserInfo(userInfo.data);
changeSignedInState(true);

} catch (error) {
if (error.response.status === 401) {
changeSignedInState(false);
navigate('/');
}
} finally {
setLoading(false);
}
};

useEffect(() => {
requestUserInfo();
}, []);

if (loading) return <Loading />;

return (
<div>{children}</div>
);
}

LoginWrap.propTypes = {
children: PropTypes.node.isRequired,
};

1 comment on commit f521d06

@vercel
Copy link

@vercel vercel bot commented on f521d06 Mar 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.