This commit is contained in:
Kar
2023-05-20 19:16:59 +05:30
parent 37786c459e
commit 54f74f8860
10 changed files with 547 additions and 10 deletions

View File

@@ -0,0 +1,18 @@
import { useSession } from "next-auth/react";
import { useEffect } from "react";
const RefreshTokenHandler = (props) => {
const { data: session } = useSession();
useEffect(() => {
if(!!session) {
// We did set the token to be ready to refresh after 23 hours, here we set interval of 23 hours 30 minutes.
const timeRemaining = Math.round((((session.accessTokenExpiry - 30 * 60 * 1000) - Date.now()) / 1000));
props.setInterval(timeRemaining > 0 ? timeRemaining : 0);
}
}, [session]);
return null;
}
export default RefreshTokenHandler;

29
src/components/useAuth.js Normal file
View File

@@ -0,0 +1,29 @@
import { signOut, useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
export default function useAuth(shouldRedirect) {
const { data: session } = useSession();
const router = useRouter();
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
if (session?.error === "RefreshAccessTokenError") {
signOut({ callbackUrl: '/login', redirect: shouldRedirect });
}
if (session === null) {
if (router.route !== '/login') {
router.replace('/login');
}
setIsAuthenticated(false);
} else if (session !== undefined) {
if (router.route === '/login') {
router.replace('/');
}
setIsAuthenticated(true);
}
}, [session]);
return isAuthenticated;
}