Skip to content

Commit

Permalink
Replace Deprecated request (#10352)
Browse files Browse the repository at this point in the history
Co-authored-by: rithviknishad <mail@rithviknishad.dev>
  • Loading branch information
AdityaJ2305 and rithviknishad authored Feb 6, 2025
1 parent 3e0bbc4 commit e326a78
Show file tree
Hide file tree
Showing 15 changed files with 185 additions and 255 deletions.
3 changes: 1 addition & 2 deletions public/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,6 @@
"delete_facility": "Delete Facility",
"delete_item": "Delete {{name}}",
"delete_record": "Delete Record",
"deleted_successfully": "{{name}} deleted successfully",
"deleting": "Deleting...",
"demography": "Demography",
"denied_on": "Denied On",
Expand Down Expand Up @@ -929,6 +928,7 @@
"entered_in_error_warning": "This action cannot be undone. The appointment will be marked as entered in error and removed from the system.",
"entity_count_one": "{{count}} {{entity}}",
"entity_count_other": "{{count}} {{entity}}s",
"entity_deleted_successfully": "{{name}} deleted successfully",
"environment": "Environment",
"error_404": "Error 404",
"error_deleting_shifting": "Error while deleting Shifting record",
Expand All @@ -937,7 +937,6 @@
"error_fetching_user_data": "Error while fetching user data",
"error_fetching_user_details": "Error while fetching user details: ",
"error_loading_questionnaire_response": "Error loading questionnaire response",
"error_sending_otp": "Error while sending OTP, Please try again later",
"error_updating_encounter": "Error to Updating Encounter",
"error_verifying_otp": "Error while verifying OTP, Please request a new OTP",
"error_while_deleting_record": "Error while deleting record",
Expand Down
4 changes: 2 additions & 2 deletions public/locale/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,6 @@
"delete_facility": "सुविधा हटाएं",
"delete_item": "{{name}}मिटाएँ",
"delete_record": "रिकॉर्ड मिटाएँ",
"deleted_successfully": "{{name}} सफलतापूर्वक हटा दिया गया",
"describe_why_the_asset_is_not_working": "बताएं कि परिसंपत्ति काम क्यों नहीं कर रही है",
"description": "विवरण",
"details_about_the_equipment": "उपकरण के बारे में विवरण",
Expand Down Expand Up @@ -343,6 +342,7 @@
"enter_file_name": "फ़ाइल का नाम दर्ज करें",
"enter_valid_age": "कृपया वैध आयु दर्ज करें",
"entered_in_error": "त्रुटिवश प्रविष्ट हुआ",
"entity_deleted_successfully": "{{name}} सफलतापूर्वक हटा दिया गया",
"error_404": "त्रुटि 404",
"error_deleting_shifting": "शिफ्टिंग रिकॉर्ड हटाते समय त्रुटि",
"error_while_deleting_record": "रिकॉर्ड हटाते समय त्रुटि हुई",
Expand Down Expand Up @@ -801,4 +801,4 @@
"you_need_at_least_a_location_to_create_an_assest": "संपत्ति बनाने के लिए आपको कम से कम एक स्थान की आवश्यकता होगी।",
"zoom_in": "ज़ूम इन",
"zoom_out": "ज़ूम आउट"
}
}
4 changes: 2 additions & 2 deletions public/locale/kn.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,6 @@
"delete_facility": "ಸೌಲಭ್ಯವನ್ನು ಅಳಿಸಿ",
"delete_item": "{{name}}ಅಳಿಸಿ",
"delete_record": "ದಾಖಲೆ ಅಳಿಸಿ",
"deleted_successfully": "{{name}} ಅನ್ನು ಯಶಸ್ವಿಯಾಗಿ ಅಳಿಸಲಾಗಿದೆ",
"describe_why_the_asset_is_not_working": "ಸ್ವತ್ತು ಏಕೆ ಕಾರ್ಯನಿರ್ವಹಿಸುತ್ತಿಲ್ಲ ಎಂಬುದನ್ನು ವಿವರಿಸಿ",
"description": "ವಿವರಣೆ",
"details_about_the_equipment": "ಸಲಕರಣೆಗಳ ಬಗ್ಗೆ ವಿವರಗಳು",
Expand Down Expand Up @@ -345,6 +344,7 @@
"enter_file_name": "ಫೈಲ್ ಹೆಸರನ್ನು ನಮೂದಿಸಿ",
"enter_valid_age": "ದಯವಿಟ್ಟು ಮಾನ್ಯವಾದ ವಯಸ್ಸನ್ನು ನಮೂದಿಸಿ",
"entered_in_error": "ತಪ್ಪಾಗಿ ನಮೂದಿಸಲಾಗಿದೆ",
"entity_deleted_successfully": "{{name}} ಅನ್ನು ಯಶಸ್ವಿಯಾಗಿ ಅಳಿಸಲಾಗಿದೆ",
"error_404": "ದೋಷ 404",
"error_deleting_shifting": "ಶಿಫ್ಟಿಂಗ್ ರೆಕಾರ್ಡ್ ಅನ್ನು ಅಳಿಸುವಾಗ ದೋಷ",
"error_while_deleting_record": "ದಾಖಲೆಯನ್ನು ಅಳಿಸುವಾಗ ದೋಷ",
Expand Down Expand Up @@ -802,4 +802,4 @@
"you_need_at_least_a_location_to_create_an_assest": "ಆಸ್ತಿಯನ್ನು ರಚಿಸಲು ನಿಮಗೆ ಕನಿಷ್ಠ ಸ್ಥಳದ ಅಗತ್ಯವಿದೆ.",
"zoom_in": "ಜೂಮ್ ಇನ್",
"zoom_out": "ಜೂಮ್ ಔಟ್"
}
}
4 changes: 1 addition & 3 deletions public/locale/ml.json
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,6 @@
"delete_facility": "സൗകര്യം ഇല്ലാതാക്കുക",
"delete_item": "{{name}}ഇല്ലാതാക്കുക",
"delete_record": "റെക്കോർഡ് ഇല്ലാതാക്കുക",
"deleted_successfully": "{{name}} വിജയകരമായി ഇല്ലാതാക്കി",
"demography": "ജനസംഖ്യാശാസ്ത്രം",
"denied_on": "നിരസിച്ചു",
"describe_why_the_asset_is_not_working": "അസറ്റ് പ്രവർത്തിക്കാത്തത് എന്തുകൊണ്ടെന്ന് വിവരിക്കുക",
Expand Down Expand Up @@ -901,12 +900,11 @@
"enter_valid_dob": "ഒരു സാധുവായ ജനനത്തീയതി നൽകുക",
"enter_valid_dob_age": "ദയവായി 15 വയസ്സിൽ കൂടുതലുള്ള ഒരു പ്രായം നൽകുക",
"enter_year_of_birth_to_verify": "സ്ഥിരീകരിക്കാൻ ജനന വർഷം നൽകുക",
"entered_in_error": "തെറ്റായി നൽകി",
"entered_in_error": "പിശകിൽ പ്രവേശിച്ചു",
"entity_deleted_successfully": "{{name}} വിജയകരമായി ഇല്ലാതാക്കി",
"error_404": "പിശക് 404",
"error_deleting_shifting": "ഷിഫ്റ്റിംഗ് റെക്കോർഡ് ഇല്ലാതാക്കുന്നതിൽ പിശക്",
"error_fetching_slots_data": "സ്ലോട്ടുകൾ ഡാറ്റ ലഭ്യമാക്കുന്നതിൽ പിശക്",
"error_sending_otp": "OTP അയയ്ക്കുമ്പോൾ പിശക്, ദയവായി പിന്നീട് വീണ്ടും ശ്രമിക്കുക",
"error_updating_encounter": "എൻകൗണ്ടർ അപ്‌ഡേറ്റ് ചെയ്യുന്നതിൽ പിശക്",
"error_verifying_otp": "OTP പരിശോധിക്കുന്നതിൽ പിശക്, ദയവായി ഒരു പുതിയ OTP അഭ്യർത്ഥിക്കുക",
"error_while_deleting_record": "റെക്കോർഡ് ഇല്ലാതാക്കുന്നതിൽ പിശക്",
Expand Down
4 changes: 2 additions & 2 deletions public/locale/ta.json
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,6 @@
"delete_facility": "நீக்கு வசதி",
"delete_item": "{{name}}ஐ நீக்கவும்",
"delete_record": "பதிவை நீக்கு",
"deleted_successfully": "{{name}} வெற்றிகரமாக நீக்கப்பட்டது",
"describe_why_the_asset_is_not_working": "சொத்து ஏன் வேலை செய்யவில்லை என்பதை விவரிக்கவும்",
"description": "விளக்கம்",
"details_about_the_equipment": "உபகரணங்கள் பற்றிய விவரங்கள்",
Expand Down Expand Up @@ -344,6 +343,7 @@
"enter_file_name": "கோப்பு பெயரை உள்ளிடவும்",
"enter_valid_age": "செல்லுபடியாகும் வயதை உள்ளிடவும்",
"entered_in_error": "தவறுதலாக உள்ளிடப்பட்டது",
"entity_deleted_successfully": "{{name}} வெற்றிகரமாக நீக்கப்பட்டது",
"error_404": "பிழை 404",
"error_deleting_shifting": "பதிவை மாற்றுவதில் பிழை",
"error_while_deleting_record": "பதிவை நீக்குவதில் பிழை",
Expand Down Expand Up @@ -801,4 +801,4 @@
"you_need_at_least_a_location_to_create_an_assest": "ஒரு அசெஸ்ட்டை உருவாக்க குறைந்தபட்சம் ஒரு இருப்பிடமாவது தேவை.",
"zoom_in": "பெரிதாக்கவும்",
"zoom_out": "பெரிதாக்கவும்"
}
}
99 changes: 37 additions & 62 deletions src/Providers/AuthUserProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import careConfig from "@careConfig";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { navigate } from "raviger";
import { useCallback, useEffect, useState } from "react";

Expand All @@ -9,10 +9,9 @@ import { AuthUserContext } from "@/hooks/useAuthUser";

import { LocalStorageKeys } from "@/common/constants";

import routes, { Type } from "@/Utils/request/api";
import routes, { JwtTokenObtainPair, Type } from "@/Utils/request/api";
import mutate from "@/Utils/request/mutate";
import query from "@/Utils/request/query";
import request from "@/Utils/request/request";
import { TokenData } from "@/types/auth/otpToken";

interface Props {
Expand Down Expand Up @@ -43,38 +42,44 @@ export default function AuthUserProvider({
enabled: !!localStorage.getItem(LocalStorageKeys.accessToken),
});

const refreshToken = localStorage.getItem(LocalStorageKeys.refreshToken);

const tokenRefreshQuery = useQuery({
queryKey: ["user-refresh-token"],
queryFn: query(routes.token_refresh, {
body: { refresh: refreshToken || "" },
}),
refetchInterval: careConfig.auth.tokenRefreshInterval,
enabled: !!refreshToken && !!user,
});

useEffect(() => {
if (!user) {
if (tokenRefreshQuery.isError) {
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);
return;
}

updateRefreshToken(true);
setInterval(
() => updateRefreshToken(),
careConfig.auth.tokenRefreshInterval,
);
}, [user]);

const signIn = useCallback(
async (creds: { username: string; password: string }) => {
const query = await request(routes.login, { body: creds });

if (query.res?.ok && query.data) {
setAccessToken(query.data.access);
localStorage.setItem(LocalStorageKeys.accessToken, query.data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, query.data.refresh);

await queryClient.invalidateQueries({ queryKey: ["currentUser"] });

if (location.pathname === "/" || location.pathname === "/login") {
navigate(getRedirectOr("/"));
}
if (tokenRefreshQuery.data) {
const { access, refresh } = tokenRefreshQuery.data;
localStorage.setItem(LocalStorageKeys.accessToken, access);
localStorage.setItem(LocalStorageKeys.refreshToken, refresh);
}
}, [tokenRefreshQuery.data, tokenRefreshQuery.isError]);

const { mutateAsync: signIn, isPending: isAuthenticating } = useMutation({
mutationFn: mutate(routes.login),
onSuccess: (data: JwtTokenObtainPair) => {
setAccessToken(data.access);
localStorage.setItem(LocalStorageKeys.accessToken, data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, data.refresh);
queryClient.invalidateQueries({ queryKey: ["currentUser"] });

if (location.pathname === "/" || location.pathname === "/login") {
navigate(getRedirectOr("/"));
}

return query;
},
[queryClient],
);
});

const patientLogin = (tokenData: TokenData, redirectUrl: string) => {
setPatientToken(tokenData);
Expand Down Expand Up @@ -103,6 +108,7 @@ export default function AuthUserProvider({
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);
localStorage.removeItem(LocalStorageKeys.patientTokenKey);
setAccessToken(null);
setPatientToken(null);

await queryClient.resetQueries({ queryKey: ["currentUser"] });
Expand Down Expand Up @@ -138,53 +144,22 @@ export default function AuthUserProvider({
return <Loading />;
}

const SelectedRouter = () => {
if (user) {
return children;
} else if (patientToken?.token) {
return otpAuthorized;
} else {
return unauthorized;
}
};

return (
<AuthUserContext.Provider
value={{
signIn,
signOut,
isAuthenticating,
user,
patientLogin,
patientToken,
}}
>
<SelectedRouter />
{user ? children : patientToken?.token ? otpAuthorized : unauthorized}
</AuthUserContext.Provider>
);
}

const updateRefreshToken = async (silent = false) => {
const refresh = localStorage.getItem(LocalStorageKeys.refreshToken);

if (!refresh) {
return;
}

const { res, data } = await request(routes.token_refresh, {
body: { refresh },
silent,
});

if (res?.status !== 200 || !data) {
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);
return;
}

localStorage.setItem(LocalStorageKeys.accessToken, data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, data.refresh);
};

const getRedirectURL = () => {
return new URLSearchParams(window.location.search).get("redirect");
};
Expand Down
8 changes: 5 additions & 3 deletions src/Utils/request/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,14 @@ const routes = {
path: "/api/v1/users/{username}/profile_picture/",
method: "DELETE",
TRes: Type<UserModel>(),
TBody: Type<void>(),
},

deleteUser: {
path: "/api/v1/users/{username}/",
method: "DELETE",
TRes: Type<Record<string, never>>(),
TBody: Type<void>(),
},

// Facility Endpoints
Expand Down Expand Up @@ -219,6 +221,7 @@ const routes = {
path: "/api/v1/facility/{id}/cover_image/",
method: "DELETE",
TRes: Type<Record<string, never>>(),
TBody: Type<void>(),
},

getFacilityUsers: {
Expand All @@ -241,6 +244,7 @@ const routes = {
path: "/api/v1/facility/{id}/",
method: "DELETE",
TRes: Type<Record<string, never>>(),
TBody: Type<void>(),
},

// Patient
Expand Down Expand Up @@ -622,9 +626,7 @@ const routes = {
path: "/api/v1/otp/login/",
method: "POST",
TBody: Type<{ phone_number: string; otp: string }>(),
TRes: Type<
{ access: string } | { errors: Array<Record<string, string>> }
>(),
TRes: Type<{ access: string }>(),
},
getPatient: {
path: "/api/v1/otp/patient/",
Expand Down
20 changes: 6 additions & 14 deletions src/components/Auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import FiltersCache from "@/Utils/FiltersCache";
import ViewCache from "@/Utils/ViewCache";
import routes from "@/Utils/request/api";
import mutate from "@/Utils/request/mutate";
import request from "@/Utils/request/request";
import { TokenData } from "@/types/auth/otpToken";

interface LoginFormData {
Expand Down Expand Up @@ -71,7 +70,7 @@ interface LoginProps {
}

const Login = (props: LoginProps) => {
const { signIn, patientLogin } = useAuthContext();
const { signIn, patientLogin, isAuthenticating } = useAuthContext();
const { reCaptchaSiteKey, urls, stateLogo, customLogo, customLogoAlt } =
careConfig;
const customDescriptionHtml = __CUSTOM_DESCRIPTION_HTML__;
Expand Down Expand Up @@ -103,20 +102,14 @@ const Login = (props: LoginProps) => {
FiltersCache.invaldiateAll();
return await signIn(data);
},
onSuccess: ({ res }) => {
setCaptcha(res?.status === 429);
onError: (error) => {
setCaptcha(error.status == 429);
},
});

// Send OTP Mutation
const { mutate: sendOtp, isPending: sendOtpPending } = useMutation({
mutationFn: async (phone: string) => {
const response = await request(routes.otp.sendOtp, {
body: { phone_number: phone },
silent: true,
});
return response;
},
mutationFn: mutate(routes.otp.sendOtp),
onSuccess: () => {
setIsOtpSent(true);
setOtpError("");
Expand Down Expand Up @@ -280,7 +273,7 @@ const Login = (props: LoginProps) => {

try {
if (!isOtpSent) {
await sendOtp(phone);
await sendOtp({ phone_number: phone });
setIsOtpSent(true);
} else {
await verifyOtp({ phone_number: phone, otp });
Expand All @@ -303,8 +296,7 @@ const Login = (props: LoginProps) => {
};

// Loading state derived from mutations
const isLoading =
staffLoginMutation.isPending || sendOtpPending || verifyOtpPending;
const isLoading = isAuthenticating || sendOtpPending || verifyOtpPending;

const logos = [stateLogo, customLogo].filter(
(logo) => logo?.light || logo?.dark,
Expand Down
Loading

0 comments on commit e326a78

Please sign in to comment.