Skip to content
This repository has been archived by the owner on Sep 29, 2024. It is now read-only.

Commit

Permalink
Merge pull request #903 from SE-TINF22B6/backend
Browse files Browse the repository at this point in the history
Logout user when token expires
  • Loading branch information
maxschwinghammer authored Jun 10, 2024
2 parents 3d989c4 + 3f14cab commit e288dbb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/main/web/src/organisms/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {Link, useLocation} from 'react-router-dom';
import ModalLoginContainer from '../login/ModalLoginContainer';
import {Notifications} from "./Notifications";
import SignUp from "../signup/SignUp";
import {isUserLoggedIn} from "../../services/AuthService";
import {isUserLoggedIn, isTokenValid, logout} from "../../services/AuthService";
import "./Header.css";
import {Tooltip} from "react-tooltip";
import config from "../../config/config";
Expand Down Expand Up @@ -41,6 +41,13 @@ export const Header = () => {
fetchAndSetNotifications();
}, []);

useEffect((): void => {
if (isUserLoggedIn() && !isTokenValid()) {
logout();
window.location.href = "/";
}
}, []);

useEffect((): void => {
setCurrentLocation(location.pathname);
}, [location]);
Expand Down
19 changes: 18 additions & 1 deletion src/main/web/src/services/AuthService.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import axios from "axios";
import config from "../config/config";
import {CredentialResponse} from "@react-oauth/google";
import {jwtDecode} from "jwt-decode";

export const register = (username: string, email: string, password: string) => {
return axios.post(config.apiUrl + "api/auth/signup", {
Expand Down Expand Up @@ -106,4 +108,19 @@ export const isUserLoggedIn = (): boolean => {
} else {
return false;
}
};
};

export const isTokenValid = (): boolean => {
const jwtToken: string | null = localStorage.getItem("token");

if (jwtToken) {
const decodedToken = jwtDecode(jwtToken);
if (decodedToken && decodedToken.exp) {
return decodedToken.exp * 1000 > Date.now();
} else {
return false;
}
} else {
return false;
}
};

0 comments on commit e288dbb

Please sign in to comment.