From b4c37340fa8adca7bcecaf924c380bcb0bee2504 Mon Sep 17 00:00:00 2001 From: lcross2002 <liamdcross@outlook.com> Date: Sat, 6 Apr 2024 23:41:37 +0100 Subject: [PATCH] fix login infinite loop bug --- UserMicroservice/Controllers/UserController.cs | 2 +- client/src/components/Login/Login.tsx | 12 ++++++++---- client/src/helpers/Api.ts | 12 ++++++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/UserMicroservice/Controllers/UserController.cs b/UserMicroservice/Controllers/UserController.cs index 889e1a3..27706ab 100644 --- a/UserMicroservice/Controllers/UserController.cs +++ b/UserMicroservice/Controllers/UserController.cs @@ -47,7 +47,7 @@ namespace UserMicroservice.Controllers { string? refreshToken = Request.Cookies["RefreshToken"]; if (string.IsNullOrEmpty(refreshToken)) - return BadRequest("Refresh token is missing."); + return Unauthorized("Refresh token is missing."); if (!_authService.ValidateRefreshToken(refreshToken)) return Unauthorized("Invalid or expired refresh token."); diff --git a/client/src/components/Login/Login.tsx b/client/src/components/Login/Login.tsx index 2171829..10f6e48 100644 --- a/client/src/components/Login/Login.tsx +++ b/client/src/components/Login/Login.tsx @@ -23,16 +23,20 @@ export function Login() { try { const result = await loginUser(formValue); - giveAuth(); - updateUser(result.data); - navigate(`/${userToDashboard(result.data)}`); + if (result) { + giveAuth(); + updateUser(result.data); + navigate(`/${userToDashboard(result.data)}`); + } else { + throw new Error(); + } } catch (error) { const errorMessage = (error as AxiosError).response?.data; if (typeof errorMessage == 'string') { setError(errorMessage); } else { - setError('An unexpected error has occurred'); + setError('An unexpected error has occurred, most likely incorrect credentials'); } } }; diff --git a/client/src/helpers/Api.ts b/client/src/helpers/Api.ts index 5eee650..eecd4ae 100644 --- a/client/src/helpers/Api.ts +++ b/client/src/helpers/Api.ts @@ -6,11 +6,19 @@ const Api = axios.create({ baseURL: 'http://localhost:5267/api/' }); +const isAlreadyAuthUrl = (error: AxiosError) => { + const full = error.request.responseURL as string; + return full.endsWith('User/authorize'); +}; + Api.interceptors.response.use( (response) => response, // Normal success logic (error: AxiosError) => { - if (error.request.status === 401) { // If 401 (Unauthorized) - AuthoriseUser().then(() => { // Re-auth + if (error.request.status === 401 && !isAlreadyAuthUrl(error)) { // If 401 (Unauthorized) + AuthoriseUser().then((response: any) => { // Re-auth + if (!response) // If no response then just return + return; + return Api.request(error.config as AxiosRequestConfig); // Redo the request }); } else { -- GitLab