Updated login check.

This commit is contained in:
Mike Cao 2023-11-29 14:03:10 -08:00
parent e074394b13
commit c24a0c87dc
6 changed files with 36 additions and 33 deletions

View File

@ -1,14 +1,23 @@
'use client';
import { Loading } from 'react-basics';
import Script from 'next/script';
import { usePathname } from 'next/navigation';
import { useLogin, useConfig } from 'components/hooks';
import UpdateNotice from './UpdateNotice';
import { useRequireLogin, useConfig } from 'components/hooks';
export function App({ children }) {
const { user } = useRequireLogin();
const { user, isLoading, error } = useLogin();
const config = useConfig();
const pathname = usePathname();
if (isLoading) {
return <Loading />;
}
if (error) {
window.location.href = `${process.env.basePath || ''}/login`;
}
if (!user || !config) {
return null;
}

View File

@ -13,7 +13,7 @@ export * from './useMessages';
export * from './useNavigation';
export * from './useReport';
export * from './useReports';
export * from './useRequireLogin';
export * from './useLogin';
export * from './useShareToken';
export * from './useSticky';
export * from './useTheme';

View File

@ -0,0 +1,22 @@
import useApi from 'components/hooks/useApi';
import useUser from 'components/hooks/useUser';
export function useLogin() {
const { get, useQuery } = useApi();
const { user, setUser } = useUser();
const query = useQuery({
queryKey: ['login'],
queryFn: async () => {
const data = await get('/auth/verify');
setUser(data);
return data;
},
});
return { user, ...query };
}
export default useLogin;

View File

@ -1,28 +0,0 @@
import { useEffect } from 'react';
import useApi from 'components/hooks/useApi';
import useUser from 'components/hooks/useUser';
export function useRequireLogin() {
const { get } = useApi();
const { user, setUser } = useUser();
useEffect(() => {
async function loadUser() {
try {
const data = await get('/auth/verify');
setUser(data);
} catch {
window.location.href = `${process.env.basePath || ''}/login`;
}
}
if (!user) {
loadUser();
}
}, [user]);
return { user };
}
export default useRequireLogin;

View File

@ -10,7 +10,7 @@ export * from 'components/hooks/useFormat';
export * from 'components/hooks/useLocale';
export * from 'components/hooks/useMessages';
export * from 'components/hooks/useNavigation';
export * from 'components/hooks/useRequireLogin';
export * from 'components/hooks/useLogin';
export * from 'components/hooks/useShareToken';
export * from 'components/hooks/useSticky';
export * from 'components/hooks/useTheme';

View File

@ -57,7 +57,7 @@ export const useAuth = createMiddleware(async (req, res, next) => {
} else if (redis.enabled && authKey) {
const key = await redis.client.get(authKey);
user = await getUserById(key.userId);
user = await getUserById(key?.userId);
}
if (process.env.NODE_ENV === 'development') {