Skip to content

Commit

Permalink
Merge pull request #40 from thisyahlen-deriv/thisyahlen/fix-isAuthori…
Browse files Browse the repository at this point in the history
…zed-flag

chore: fix isAuthorized flag
  • Loading branch information
jim-deriv authored Apr 23, 2024
2 parents 56d33b8 + 05af867 commit 9b37e44
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/context/auth-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,20 @@ export const AuthDataProvider = ({ children }: AuthDataProviderProps) => {

const { data, mutate, isSuccess, isPending } = useAuthorize();

const accountsList: Record<string, string> = JSON.parse(Cookies.get('accountsList') ?? '{}');

const isAuthorized = useMemo(
() => !!activeLoginid || !!Object.keys(accountsList).length,
[activeLoginid, accountsList]
);

const authorizeAccount = useCallback((token?: string) => {
if (token) mutate({ authorize: token });
}, []);

const switchAccount = useCallback(
(loginId: string) => {
const tradingAccounts: Record<string, string> = JSON.parse(Cookies.get('tradingAccounts') ?? '{}');

const token = tradingAccounts[loginId];
const token = accountsList[loginId];

if (!token) return;
authorizeAccount(token);
Expand All @@ -55,13 +60,13 @@ export const AuthDataProvider = ({ children }: AuthDataProviderProps) => {
if (!defaultActiveAccount) return;

setActiveLoginid(loginInfo[0].loginid);
const tradingAccounts: Record<string, string> = {};
const accountsList: Record<string, string> = {};

loginInfo.forEach(account => {
tradingAccounts[account.loginid] = account.token;
accountsList[account.loginid] = account.token;
});

Cookies.set('tradingAccounts', JSON.stringify(tradingAccounts));
Cookies.set('accountsList', JSON.stringify(accountsList));

URLUtils.filterSearchParams(paramsToDelete);
authorizeAccount(loginInfo[0].token);
Expand All @@ -75,11 +80,9 @@ export const AuthDataProvider = ({ children }: AuthDataProviderProps) => {
}, []);

const appendAccountCookie = useCallback((loginid: string, token: string) => {
const tradingAccounts: Record<string, string> = JSON.parse(Cookies.get('tradingAccounts') ?? '{}');

tradingAccounts[loginid] = token;
accountsList[loginid] = token;

Cookies.set('tradingAccounts', JSON.stringify(tradingAccounts));
Cookies.set('accountsList', JSON.stringify(accountsList));

switchAccount(loginid);
}, []);
Expand All @@ -93,11 +96,11 @@ export const AuthDataProvider = ({ children }: AuthDataProviderProps) => {
const value = useMemo(
() => ({
activeLoginid,
isAuthorized: !!activeLoginid && isSuccess,
isAuthorizing: isPending,
switchAccount,
appendAccountCookie,
logout,
isAuthorized,
}),
[activeLoginid, isSuccess]
);
Expand Down

0 comments on commit 9b37e44

Please sign in to comment.