2020-08-05 07:45:05 +02:00
|
|
|
import { useState, useEffect } from 'react';
|
2020-10-01 07:34:16 +02:00
|
|
|
import { useRouter } from 'next/router';
|
2022-02-23 07:47:59 +01:00
|
|
|
import useUser from 'hooks/useUser';
|
2022-02-27 00:53:45 +01:00
|
|
|
import useApi from 'hooks/useApi';
|
2020-08-05 07:45:05 +02:00
|
|
|
|
2020-08-06 04:04:02 +02:00
|
|
|
export default function useRequireLogin() {
|
2020-10-01 07:34:16 +02:00
|
|
|
const router = useRouter();
|
2022-02-27 00:53:45 +01:00
|
|
|
const { get } = useApi();
|
2022-02-23 07:47:59 +01:00
|
|
|
const { user, setUser } = useUser();
|
|
|
|
const [loading, setLoading] = useState(false);
|
2020-08-05 07:45:05 +02:00
|
|
|
|
2020-10-01 07:34:16 +02:00
|
|
|
async function loadUser() {
|
|
|
|
setLoading(true);
|
|
|
|
|
2022-02-27 00:53:45 +01:00
|
|
|
const { ok, data } = await get('/auth/verify');
|
2020-10-01 07:34:16 +02:00
|
|
|
|
|
|
|
if (!ok) {
|
2022-02-27 00:53:45 +01:00
|
|
|
await router.push('/login');
|
|
|
|
return null;
|
2020-08-05 07:45:05 +02:00
|
|
|
}
|
|
|
|
|
2022-02-23 07:47:59 +01:00
|
|
|
setUser(data);
|
2020-08-05 07:45:05 +02:00
|
|
|
|
2020-10-01 07:34:16 +02:00
|
|
|
setLoading(false);
|
|
|
|
}
|
2020-08-05 07:45:05 +02:00
|
|
|
|
2020-10-01 07:34:16 +02:00
|
|
|
useEffect(() => {
|
2022-02-27 00:53:45 +01:00
|
|
|
if (loading || user) {
|
2020-10-01 07:34:16 +02:00
|
|
|
return;
|
|
|
|
}
|
2020-08-05 07:45:05 +02:00
|
|
|
|
2020-10-01 07:34:16 +02:00
|
|
|
loadUser();
|
2022-02-27 00:53:45 +01:00
|
|
|
}, [user, loading]);
|
2020-08-05 07:45:05 +02:00
|
|
|
|
|
|
|
return { user, loading };
|
|
|
|
}
|