login
This commit is contained in:
18
src/components/refreshTokenHandler.js
Normal file
18
src/components/refreshTokenHandler.js
Normal 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
29
src/components/useAuth.js
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user