Skip to content

Commit

Permalink
Login/Logout logic
Browse files Browse the repository at this point in the history
  • Loading branch information
wmazoni committed May 1, 2024
1 parent 36c634c commit 4737ab4
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
52 changes: 50 additions & 2 deletions frontend/src/components/Navbar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,49 @@
import './styles.css';
import 'bootstrap/js/src/collapse.js';
import { useEffect, useState } from 'react';

import { Link, NavLink } from 'react-router-dom';
import history from 'util/history';
import {
TokenData,
getTokenData,
isAuthenticated,
removeAuthData,
} from 'util/requests';

type AuthData = {
authenticated: boolean;
tokenData?: TokenData;
};

const Navbar = () => {
const [authData, setAuthData] = useState<AuthData>({ authenticated: false });

useEffect(() => {
if (isAuthenticated()) {
setAuthData({
authenticated: true,
tokenData: getTokenData(),
});
} else {
setAuthData({
authenticated: false,
});
}
}, []);

const handleLogoutClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
removeAuthData();
setAuthData({
authenticated: false,
});
history.replace('/');
};

return (
<nav className="navbar navbar-expand-md navbar-dark bg-primary main-nav">
<div className="container-fluid">
{' '}
{/* previne quebra de linha entre logo e itens */}
<Link to="/" className="nav-logo-text">
<h4>DS Catalog</h4>
</Link>
Expand Down Expand Up @@ -42,6 +77,19 @@ const Navbar = () => {
</li>
</ul>
</div>

<div>
{authData.authenticated ? (
<>
<span>{authData.tokenData?.user_name}</span>
<Link to="#logout" onClick={handleLogoutClick}>
LOGOUT
</Link>
</>
) : (
<Link to="/admin/auth">LOGIN</Link>
)}
</div>
</div>
</nav>
);
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/util/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import jwtDecode from 'jwt-decode';

type Role = 'ROLE_OPERATOR' | 'ROLE_ADMIN';

type TokenData = {
export type TokenData = {
exp: number,
user_name: string,
authorities: Role[]
Expand Down Expand Up @@ -50,6 +50,10 @@ export const getAuthData = () => {
return JSON.parse(str) as LoginResponse
}

export const removeAuthData = () => {
localStorage.removeItem(tokenKey);
}

export const requestBackend = (config: AxiosRequestConfig) => {
const headers = config.withCredentials ? {
...config.headers,
Expand Down

0 comments on commit 4737ab4

Please sign in to comment.