Implemented a simple authentication scheme with Firebase and Iron Session

This commit is contained in:
Tiago Ribeiro
2023-04-12 16:53:36 +01:00
parent cb1a67de23
commit 58bdc745e4
16 changed files with 1371 additions and 33 deletions

29
src/hooks/useUser.tsx Normal file
View File

@@ -0,0 +1,29 @@
import {useEffect} from "react";
import Router from "next/router";
import useSWR from "swr";
import {User} from "@/interfaces/user";
import axios from "axios";
const fetcher = (url: string) => axios.get(url).then((res) => res.data);
export default function useUser({redirectTo = "", redirectIfFound = false} = {}) {
const {data: user, mutate: mutateUser, isLoading} = useSWR<User>("/api/user", fetcher);
useEffect(() => {
// if no redirect needed, just return (example: already on /dashboard)
// if user data not yet there (fetch in progress, logged in or not) then don't do anything yet
console.log(redirectTo, user);
if (!redirectTo || !user) return;
if (
// If redirectTo is set, redirect if the user was not found.
(redirectTo && !redirectIfFound && !user) ||
// If redirectIfFound is also set, redirect if the user was found
(redirectIfFound && user)
) {
Router.push(redirectTo);
}
}, [user, redirectIfFound, redirectTo]);
return {user, mutateUser, isLoading};
}