Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix to authManager and statistics frontend support #145

Merged
merged 18 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion webapp/jsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"baseUrl": "./src",
"checkJs": true,
"jsx": "react",
"resolveJsonModule": true
"resolveJsonModule": true,
"target": "ES2022",
"moduleResolution": "node"
}
}
423 changes: 72 additions & 351 deletions webapp/package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@
"@testing-library/react": "^14.1.2",
"@testing-library/user-event": "^14.5.2",
"axios": "^1.6.5",
"chart.js": "^4.4.2",
"dotenv": "^16.4.1",
"framer-motion": "^11.0.6",
"i18next": "^23.8.2",
"i18next-browser-languagedetector": "^7.2.0",
"i18next-http-backend": "^2.4.3",
"jest-when": "^3.6.0",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-confetti": "^6.1.0",
"react-dom": "^18.2.0",
"react-i18next": "^14.0.5",
Expand Down
15 changes: 14 additions & 1 deletion webapp/public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"statistics": {
"title": "Statistics",
"personal": "My statistics",
"general": "General statistics"
"general": "Leaderboard"
},
"play": "Play",
"login": "Log in",
Expand Down Expand Up @@ -48,5 +48,18 @@
"type": "Authorization Error: ",
"message": "Incorrect password"
}
},
"statistics": {
"position": "Position",
"username": "Username",
"rightAnswers": "Correct answers",
"wrongAnswers": "Wrong answers",
"totalAnswers": "Total answers",
"percentage": "Correct answer rate",
"texts": {
"personalRight": "{{right, number}} correct answers",
"personalWrong": "{{wrong, number}} wrong answers",
"personalRate": "{{rate, number}} %"
}
}
}
15 changes: 14 additions & 1 deletion webapp/public/locales/es/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"statistics": {
"title": "Estadísticas",
"personal": "Mis estadísticas",
"general": "Estadísticas generales"
"general": "Clasificación"
},
"play": "Jugar",
"login": "Iniciar sesión",
Expand Down Expand Up @@ -48,5 +48,18 @@
"type": "Error de Autorización: ",
"message": "Contraseña incorrecta"
}
},
"statistics": {
"position": "Posición",
"username": "Nombre de usuario",
"rightAnswers": "Respuestas correctas",
"wrongAnswers": "Respuestas erróneas",
"totalAnswers": "Respuestas totales",
"percentage": "Porcentaje de acierto",
"texts": {
"personalRight": "{{right, number}} respuestas correctas",
"personalWrong": "{{wrong, number}} respuestas incorrectas",
"personalRate": "{{rate, number}} %"
}
}
}
14 changes: 14 additions & 0 deletions webapp/src/components/GoBack.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Button, Flex } from "@chakra-ui/react";
import React from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router";

export default function GoBack() {
const {t} = useTranslation();
const navigate = useNavigate();
return <Flex direction="row" justifyContent="center" alignItems="center">
<Button data-testid={"GoBack"} type="submit" colorScheme="blue" margin={"10px"} className={"custom-button effect1"} onClick={() => navigate("/dashboard")} w="100%">
{t("common.goBack")}
</Button>
</Flex>
}
4 changes: 4 additions & 0 deletions webapp/src/components/Router.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import Rules from "../pages/Rules";
import Signup from "../pages/Signup";
import Game from "../pages/Game";
import Results from "../pages/Results";
import Statistics from "pages/Statistics";
import ProtectedRoute from "./utils/ProtectedRoute";
import Logout from "pages/Logout";


export default createRoutesFromElements(
Expand All @@ -21,6 +23,8 @@ export default createRoutesFromElements(
<Route path="/dashboard/rules" element={<Rules />}/>
<Route path="/dashboard/game" element={<Game />}/>
<Route path="/dashboard/game/results" element={<Results />}/>
<Route path="/dashboard/statistics" element={<Statistics />} />
<Route path="/logout" element={<Logout />} />
</Route>
</Route>
)
121 changes: 121 additions & 0 deletions webapp/src/components/auth/AuthManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import axios, { HttpStatusCode } from "axios";

export default class AuthManager {

static #instance = null;
#isLoggedIn = false;
#axiosInstance = null;

constructor() {
if (!AuthManager.#instance) {
AuthManager.#instance = this;
AuthManager.#instance.#axiosInstance = axios.create();
}
}

getAxiosInstance() {
return AuthManager.#instance.#axiosInstance;
}

setLoggedIn(value) {
AuthManager.#instance.#isLoggedIn = value;
}

isLoggedIn() {
console.log(this.#isLoggedIn);
console.log(sessionStorage.getItem("jwtRefreshToken"))
if (!AuthManager.#instance.#isLoggedIn) {
if (sessionStorage.getItem("jwtRefreshToken")) {
this.#refresh();
}
}
return AuthManager.#instance.#isLoggedIn;
}

static getInstance() {
return AuthManager.#instance;
}

async login(loginData, onSuccess, onError) {
try {
let requestAnswer = await this.getAxiosInstance().post(process.env.REACT_APP_API_ENDPOINT + "/auth/login", loginData);
if (HttpStatusCode.Ok === requestAnswer.status) {
this.#saveToken(requestAnswer);
AuthManager.#instance.setLoggedIn(true);
onSuccess();
} else {
throw requestAnswer;
}
} catch (error) {
let errorType;
switch (error.response ? error.response.status : null) {
case 400:
errorType = { type: "error.validation.type", message: "error.validation.message"};
break;
case 401:
errorType = { type: "error.authorized.type", message: "error.authorized.message"};
break;
default:
errorType = { type: "error.unknown.type", message: "error.unknown.message"};
break;
}
onError(errorType);
}
}

reset() {
AuthManager.#instance = null;
AuthManager.#instance = new AuthManager();
}

async logout() {
try {
await this.getAxiosInstance().get(process.env.REACT_APP_API_ENDPOINT + "/auth/logout");
AuthManager.#instance.setLoggedIn(false);
} catch (error) {
console.error("Error logging out user: ", error);
}
}

#saveToken(requestAnswer) {
sessionStorage.setItem("jwtRefreshToken", requestAnswer.data.refresh_token);
}

async #refresh() {
try {
let response = await this.getAxiosInstance().post(process.env.REACT_APP_API_ENDPOINT + "/auth/refresh-token", {
"refreshToken": sessionStorage.getItem("jwtRefreshToken")
});
this.#saveToken(response);
AuthManager.#instance.setLoggedIn(true);
} catch (error) {
console.error("Error refreshing token: ", error);
}
}

async register(registerData, onSuccess, onError) {
try {
let requestAnswer = await this.getAxiosInstance().post(process.env.REACT_APP_API_ENDPOINT + "/auth/register", registerData);
if (HttpStatusCode.Ok === requestAnswer.status) {
this.#saveToken(requestAnswer);
onSuccess();
} else {
throw requestAnswer;
}
} catch (error) {
let errorType;
switch (error.response ? error.response.status : null) {
case 400:
errorType = { type: "error.validation.type", message: "error.validation.message"};
break;
case 409:
errorType = { type: "error.conflict.type", message: "error.conflict.message"};
break;
default:
errorType = { type: "error.unknown.type", message: "error.unknown.message"};
break;
}
onError(errorType);
}
}
}
72 changes: 0 additions & 72 deletions webapp/src/components/auth/AuthUtils.js

This file was deleted.

11 changes: 0 additions & 11 deletions webapp/src/components/game/Logout.js

This file was deleted.

36 changes: 0 additions & 36 deletions webapp/src/components/utils/AuthManager.js

This file was deleted.

2 changes: 1 addition & 1 deletion webapp/src/components/utils/ProtectedRoute.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react";
import { Outlet, Navigate } from "react-router-dom";
import AuthManager from "./AuthManager";
import AuthManager from "../auth/AuthManager";

const authManager = new AuthManager();

Expand Down
Loading
Loading