Implement Auth account page
This commit is contained in:
@@ -2,8 +2,10 @@
|
||||
import { createContext, useState, useEffect } from "react";
|
||||
import { TokenType } from "@/types/user";
|
||||
import { TokenProps } from "@/types/user";
|
||||
import { useRouter, usePathname } from "@/src/navigation";
|
||||
|
||||
const LOCAL_STORAGE_KEY = "testplat-auth-token";
|
||||
const privatePaths = ["/account"];
|
||||
|
||||
function storeTokenToLocalStorage(token: TokenType) {
|
||||
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(token));
|
||||
@@ -16,7 +18,10 @@ function removeTokenFromLocalStorage() {
|
||||
const defaultTokenContext = {};
|
||||
const TokenContext = createContext(defaultTokenContext);
|
||||
|
||||
const TokenProvider = ({ children }: TokenProps) => {
|
||||
const TokenProvider = ({ locale, children }: TokenProps) => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
const [token, setToken] = useState<TokenType>({
|
||||
access_token: "",
|
||||
user: null,
|
||||
@@ -28,13 +33,27 @@ const TokenProvider = ({ children }: TokenProps) => {
|
||||
removeTokenFromLocalStorage,
|
||||
};
|
||||
|
||||
const restoreTokenFromLocalStorage = () => {
|
||||
const tokenString = localStorage.getItem(LOCAL_STORAGE_KEY);
|
||||
if (tokenString) {
|
||||
const restoredToken = JSON.parse(tokenString);
|
||||
setToken(restoredToken);
|
||||
} else {
|
||||
checkSignInPage();
|
||||
}
|
||||
};
|
||||
|
||||
const checkSignInPage = () => {
|
||||
if (
|
||||
privatePaths.some((path) => {
|
||||
return path === pathname;
|
||||
})
|
||||
) {
|
||||
router.push(`/account/signin`, { locale: locale });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const restoreTokenFromLocalStorage = () => {
|
||||
const tokenString = localStorage.getItem(LOCAL_STORAGE_KEY);
|
||||
if (tokenString) {
|
||||
setToken(JSON.parse(tokenString));
|
||||
}
|
||||
};
|
||||
restoreTokenFromLocalStorage();
|
||||
}, []);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user