Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/dev' into dev-deploy
Browse files Browse the repository at this point in the history
  • Loading branch information
KartVen committed Dec 2, 2024
2 parents 228e058 + 8d26939 commit ad0a0e9
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 57 deletions.
16 changes: 7 additions & 9 deletions src/components/layout/navbar/right/UserActionBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@ import { useRouter } from 'next/navigation';
import UserActionBtns from '@/components/layout/navbar/right/UserActionBtns';

export default function UserActionBlock() {
const { session, isSessionLoading } = useSessionContext();
const [state, setState] = useState<number>(() => {
return isSessionLoading ? 0 : (session != undefined ? 1 : -1);
});
const { session, sessionStatus } = useSessionContext();
const [stateStatus, setStateStatus] = useState(sessionStatus);
const router = useRouter();

useEffect(() => {
setState(isSessionLoading ? 0 : (session != undefined ? 1 : -1));
}, [session, isSessionLoading]);
setStateStatus(sessionStatus);
}, [sessionStatus]);

return (
<>
{state == -1 && (
{stateStatus === 'UNAUTHENTICATED' && (
<div className="pr-2">
<button
className="flex h-[2.5rem] cursor-pointer items-center rounded-md bg-primary px-4 py-2 text-sm font-semibold text-textOnPrimary hover:bg-primaryHover"
Expand All @@ -29,7 +27,7 @@ export default function UserActionBlock() {
</div>
)}

{state == 1 && <UserActionBtns />}
{stateStatus === 'AUTHENTICATED' && <UserActionBtns />}
</>
);
}
}
6 changes: 3 additions & 3 deletions src/components/users/by_id_page/UserByIdPageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import UserMaterialsSection from '@/components/users/by_id_page/page_content/Use

export default function UserByIdPageContent({ id: userId, title }: MetadataProps & { id: number }) {
const { data: user, status, fetch: fetchUser } = useFetchState<User>();
const { session, isSessionLoading } = useSessionContext();
const { session, sessionStatus } = useSessionContext();

useEffect(() => {
!isSessionLoading && fetchUser(() => UserService.getUserById(session, userId));
}, [fetchUser, session, isSessionLoading, userId]);
sessionStatus != 'LOADING' && fetchUser(() => UserService.getUserById(session, userId));
}, [fetchUser, session, sessionStatus, userId]);

if (status === Status.PENDING) return <Loading full />;

Expand Down
98 changes: 53 additions & 45 deletions src/contexts/SessionContext.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
'use client';
import React from 'react';
import UserAuthorized from '@/services/user/types/userAuthorized';
import { jwtDecode } from 'jwt-decode';
import AuthService from '@/services/auth/authService';
import { deleteCookie, getCookie } from 'cookies-next';
import { AUTH_PRE_SESSION } from '@/utils/constant';
import UserService from '@/services/user/userService';
import UserAuthorized from '@/services/user/types/userAuthorized';

const __SESSION_CACHE: {
signUri: string;
Expand All @@ -15,8 +19,12 @@ export interface Session {
user: {
id: number;
username: string;
state: number
role: string;
state: number;
roles: string[];
};
token: {
bearer: string;
refresh: string;
};
}

Expand All @@ -34,24 +42,23 @@ export interface Jwt {
export type SessionContextType =
| {
session: Session;
isSessionLoading: false
refresh: () => void;
sessionStatus: 'AUTHENTICATED';
update: (session: Session | undefined) => void;
} | {
session: undefined;
sessionStatus: 'UNAUTHENTICATED';
update: (session: Session | undefined) => void;
}
| {
session: Session | undefined;
isSessionLoading: true;
refresh: () => void;
sessionStatus: 'LOADING';
update: (session: Session | undefined) => void;
}
| {
session: undefined;
isSessionLoading: false;
refresh: () => void;
};

export const SessionContext = React.createContext<SessionContextType>({
session: undefined,
isSessionLoading: false,
refresh: () => {
sessionStatus: 'LOADING',
update: () => {
}
});

Expand All @@ -64,44 +71,42 @@ interface SessionContextProviderProps {
const SessionProvider = ({ session: sessionProp = undefined, signUri, children }: SessionContextProviderProps) => {
__SESSION_CACHE.signUri = signUri;

const updateSession = React.useCallback(async (user: UserAuthorized) => {
setSession({
user: { id: user.id, username: user.username, role: user.role.name, state: 0 }
});
}, []);

const [session, setSession] = React.useState<Session | undefined>(sessionProp);
const [isLoading, setIsLoading] = React.useState<boolean>(true);

const update = React.useCallback(() => {
const updateFromApi = async () => {
return await UserService.getMe().then((user) => updateSession(user));
};

updateFromApi().finally(() => {
setIsLoading(false);
});
}, [session]);

React.useEffect(() => {
const updateFromApi = async () => {
return await UserService.getMe().then((user) => updateSession(user));
const update = React.useCallback((user: UserAuthorized | undefined) => {
if (!user) {
setSession(undefined);
return undefined;
}
const session: Session = {
user: { id: user.id, username: user.username, roles: [user.role.name], state: 0 },
token: { bearer: '', refresh: '' }
};

updateFromApi().finally(() => {
setIsLoading(false);
});
setSession(session);
return session;
}, []);

const isLoading1 = React.useCallback(() => isLoading, [isLoading]);
React.useEffect(() => {
UserService.getMe()
.then((user) => update(user))
.catch(() => update(undefined))
.finally(() => {
setIsLoading(false);
});
}, [update]);

const status = React.useCallback(() => {
return isLoading ? 'LOADING' : (session ? 'AUTHENTICATED' : 'UNAUTHENTICATED');
}, [isLoading, session]);

const value: any = React.useMemo(
() => ({
session,
isSessionLoading: isLoading1(),
refresh: update
status: status(),
update
}),
[session, update]
[session, status, update]
);

return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
Expand All @@ -115,15 +120,18 @@ export const useSessionContext = (isSecure = false): SessionContextType => {
throw new Error('useSessionContext must be used within a SessionProvider');
}

React.useEffect(() => context.refresh(), []);
const isUnauthenticated = context.sessionStatus == 'UNAUTHENTICATED';

React.useEffect(() => {
if (isSecure && (context.session == undefined && context.isSessionLoading)) {
if (isSecure && isUnauthenticated) {
window.location.href = `${__SESSION_CACHE.signUri}?${new URLSearchParams({
callbackUri: window.location.href
})}`;
}
}, [isSecure, context.session, context.isSessionLoading]);
}, [isSecure, isUnauthenticated, context.sessionStatus]);

/*return isSecure && isUnauthenticated
? { session: context.session, sessionStatus: 'LOADING', update: context.update }
: context;*/
return context;
};
};

0 comments on commit ad0a0e9

Please sign in to comment.