umami/hooks/useRequireLogin.js

35 lines
678 B
JavaScript
Raw Normal View History

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';
import useUser from 'hooks/useUser';
2020-11-10 06:01:53 +01:00
import { get } from 'lib/web';
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();
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);
const { ok, data } = await get(`${router.basePath}/api/auth/verify`);
if (!ok) {
return router.push('/login');
2020-08-05 07:45:05 +02: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(() => {
if (!loading && user) {
return;
}
2020-08-05 07:45:05 +02:00
2020-10-01 07:34:16 +02:00
loadUser();
2020-08-05 07:45:05 +02:00
}, []);
return { user, loading };
}