Skip to content

Commit

Permalink
Improve sign out flow
Browse files Browse the repository at this point in the history
  • Loading branch information
rithviknishad committed Dec 8, 2023
1 parent acc43e6 commit f64151f
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 76 deletions.
10 changes: 8 additions & 2 deletions src/Common/hooks/useAuthUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@ export const AuthUserContext = createContext<AuthContextType | null>(null);
export const useAuthContext = () => {
const ctx = useContext(AuthUserContext);
if (!ctx) {
throw new Error("useAuthUser must be used within an AuthUserProvider");
throw new Error(
"'useAuthContext' must be used within 'AuthUserProvider' only"
);
}
return ctx;
};

export default function useAuthUser() {
return useAuthContext().user;
const user = useAuthContext().user;
if (!user) {
throw new Error("'useAuthUser' must be used within 'AppRouter' only");
}
return user;
}
15 changes: 6 additions & 9 deletions src/Components/Common/Sidebar/SidebarUserCard.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Link } from "raviger";
import { useTranslation } from "react-i18next";
import CareIcon from "../../../CAREUI/icons/CareIcon";
import { handleSignOut } from "../../../Utils/utils";
import useAuthUser from "../../../Common/hooks/useAuthUser";
import { formatName } from "../../../Utils/utils";
import useAuthUser, { useAuthContext } from "../../../Common/hooks/useAuthUser";

const SidebarUserCard = ({ shrinked }: { shrinked: boolean }) => {
const { t } = useTranslation();
const user = useAuthUser();
const profileName = `${user.first_name ?? ""} ${user.last_name ?? ""}`.trim();
const { signOut } = useAuthContext();

return (
<div
Expand All @@ -18,10 +18,7 @@ const SidebarUserCard = ({ shrinked }: { shrinked: boolean }) => {
<Link href="/user/profile" className="flex-none py-3">
<CareIcon className="care-l-user-circle text-3xl text-white" />
</Link>
<div
className="flex cursor-pointer justify-center"
onClick={() => handleSignOut(true)}
>
<div className="flex cursor-pointer justify-center" onClick={signOut}>
<CareIcon
className={`care-l-sign-out-alt text-2xl text-gray-400 ${
shrinked ? "visible" : "hidden"
Expand All @@ -39,12 +36,12 @@ const SidebarUserCard = ({ shrinked }: { shrinked: boolean }) => {
className="flex-nowrap overflow-hidden break-words font-semibold text-white"
id="profilenamelink"
>
{profileName}
{formatName(user)}
</Link>
</div>
<div
className="min-h-6 flex cursor-pointer items-center"
onClick={() => handleSignOut(true)}
onClick={signOut}
>
<CareIcon
className={`care-l-sign-out-alt ${
Expand Down
12 changes: 5 additions & 7 deletions src/Components/ErrorPages/SessionExpired.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as Notification from "../../Utils/Notifications";
import { useNavigate } from "raviger";
import { useContext, useEffect } from "react";
import { handleSignOut } from "../../Utils/utils";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { AuthUserContext } from "../../Common/hooks/useAuthUser";
import { useAuthContext } from "../../Common/hooks/useAuthUser";

export default function SessionExpired() {
const isAuthenticated = !!useContext(AuthUserContext);
const { signOut, user } = useAuthContext();
const isAuthenticated = !!user;
const navigate = useNavigate();
const { t } = useTranslation();

Expand All @@ -32,9 +32,7 @@ export default function SessionExpired() {
<br />
<br />
<div
onClick={() => {
handleSignOut(false);
}}
onClick={signOut}
className="hover:bg-primary- inline-block cursor-pointer rounded-lg bg-primary-600 px-4 py-2 text-white hover:text-white"
>
{t("return_to_login")}
Expand Down
7 changes: 4 additions & 3 deletions src/Components/Users/UserProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import * as Notification from "../../Utils/Notifications.js";
import LanguageSelector from "../../Components/Common/LanguageSelector";
import TextFormField from "../Form/FormFields/TextFormField";
import ButtonV2, { Submit } from "../Common/components/ButtonV2";
import { classNames, handleSignOut, parsePhoneNumber } from "../../Utils/utils";
import { classNames, parsePhoneNumber } from "../../Utils/utils";
import CareIcon from "../../CAREUI/icons/CareIcon";
import PhoneNumberFormField from "../Form/FormFields/PhoneNumberFormField";
import { FieldChangeEvent } from "../Form/FormFields/Utils";
import { SelectFormField } from "../Form/FormFields/SelectFormField";
import { GenderType, SkillModel, UpdatePasswordForm } from "../Users/models";
import UpdatableApp, { checkForUpdate } from "../Common/UpdatableApp";
import dayjs from "../../Utils/dayjs";
import useAuthUser from "../../Common/hooks/useAuthUser";
import useAuthUser, { useAuthContext } from "../../Common/hooks/useAuthUser";
import { PhoneNumberValidator } from "../Form/FieldValidators";
import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";
Expand Down Expand Up @@ -100,6 +100,7 @@ const editFormReducer = (state: State, action: Action) => {
};

export default function UserProfile() {
const { signOut } = useAuthContext();
const [states, dispatch] = useReducer(editFormReducer, initialState);
const [updateStatus, setUpdateStatus] = useState({
isChecking: false,
Expand Down Expand Up @@ -413,7 +414,7 @@ export default function UserProfile() {
>
{showEdit ? "Cancel" : "Edit User Profile"}
</ButtonV2>
<ButtonV2 variant="danger" onClick={(_) => handleSignOut(true)}>
<ButtonV2 variant="danger" onClick={signOut}>
<CareIcon className="care-l-sign-out-alt" />
Sign out
</ButtonV2>
Expand Down
59 changes: 40 additions & 19 deletions src/Providers/AuthUserProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from "react";
import { useCallback, useEffect } from "react";
import { AuthUserContext } from "../Common/hooks/useAuthUser";
import Loading from "../Components/Common/Loading";
import routes from "../Redux/api";
Expand Down Expand Up @@ -33,34 +33,55 @@ export default function AuthUserProvider({ children, unauthorized }: Props) {
setInterval(() => updateRefreshToken(), tokenRefreshInterval);
}, [user, tokenRefreshInterval]);

if (loading || !res) {
return <Loading />;
}
const signIn = useCallback(
async (creds: { username: string; password: string }) => {
const query = await request(routes.login, { body: creds });

const signIn = async (creds: { username: string; password: string }) => {
const query = await request(routes.login, { body: creds });
if (query.res?.ok && query.data) {
localStorage.setItem(LocalStorageKeys.accessToken, query.data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, query.data.refresh);

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

await refetch();
navigate(getRedirectOr("/"));
}
await refetch();
navigate(getRedirectOr("/"));
}

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

const signOut = async () => {
const signOut = useCallback(async () => {
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);

const redirectURL = getRedirectURL();

await refetch();

const redirectURL = getRedirectURL();
navigate(redirectURL ? `/?redirect=${redirectURL}` : "/");
};
}, [refetch]);

// Handles signout from current tab, if signed out from another tab.
useEffect(() => {
const listener = (event: any) => {
if (
!event.newValue &&
(LocalStorageKeys.accessToken === event.key ||
LocalStorageKeys.refreshToken === event.key)
) {
signOut();
}
};

addEventListener("storage", listener);

return () => {
removeEventListener("storage", listener);
};
}, [signOut]);

if (loading || !res) {
return <Loading />;
}

return (
<AuthUserContext.Provider value={{ signIn, signOut, user }}>
Expand Down
16 changes: 1 addition & 15 deletions src/Routers/AppRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import {
SIDEBAR_SHRINK_PREFERENCE_KEY,
SidebarShrinkContext,
} from "../Components/Common/Sidebar/Sidebar";
import { BLACKLISTED_PATHS, LocalStorageKeys } from "../Common/constants";
import { BLACKLISTED_PATHS } from "../Common/constants";
import useConfig from "../Common/hooks/useConfig";
import { handleSignOut } from "../Utils/utils";
import SessionExpired from "../Components/ErrorPages/SessionExpired";

import UserRoutes from "./routes/UserRoutes";
Expand Down Expand Up @@ -63,19 +62,6 @@ export default function AppRouter() {
const path = usePath();
const [sidebarOpen, setSidebarOpen] = useState(false);

useEffect(() => {
addEventListener("storage", (event: any) => {
if (
[LocalStorageKeys.accessToken, LocalStorageKeys.refreshToken].includes(
event.key
) &&
!event.newValue
) {
handleSignOut(true);
}
});
}, []);

useEffect(() => {
setSidebarOpen(false);
let flag = false;
Expand Down
22 changes: 1 addition & 21 deletions src/Utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import { navigate } from "raviger";
import {
AREACODES,
IN_LANDLINE_AREA_CODES,
LocalStorageKeys,
} from "../Common/constants";
import { AREACODES, IN_LANDLINE_AREA_CODES } from "../Common/constants";
import phoneCodesJson from "../Common/static/countryPhoneAndFlags.json";
import dayjs from "./dayjs";

Expand Down Expand Up @@ -119,21 +114,6 @@ export const dateQueryString = (date: DateLike) => {

export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export const handleSignOut = (forceReload: boolean) => {
Object.values(LocalStorageKeys).forEach((key) =>
localStorage.removeItem(key)
);
const redirectURL = new URLSearchParams(window.location.search).get(
"redirect"
);
const url = redirectURL ? `/?redirect=${redirectURL}` : "/";
if (forceReload) {
window.location.href = url;
} else {
navigate(url);
}
};

/**
* Referred from: https://stackoverflow.com/a/9039885/7887936
* @returns `true` if device is iOS, else `false`
Expand Down

0 comments on commit f64151f

Please sign in to comment.