Skip to content

Commit

Permalink
fix useAuth
Browse files Browse the repository at this point in the history
  • Loading branch information
version-1 committed Feb 29, 2024
1 parent 0b8ebbb commit 5b9790c
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 12 deletions.
8 changes: 4 additions & 4 deletions frontend/core/src/app/layout.tsx
Expand Up @@ -3,19 +3,19 @@ import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"] });

import { Metadata } from 'next'
import { Metadata } from "next";

export const metadata: Metadata = {
title: 'Turbo',
}
title: "Turbo",
};

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<html lang="ja">
<body className={inter.className}>{children}</body>
</html>
);
Expand Down
26 changes: 26 additions & 0 deletions frontend/core/src/app/login/layout.tsx
@@ -0,0 +1,26 @@
import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"] });

import { Metadata } from "next";
import AuthContainer from "@/components/auth";

export const metadata: Metadata = {
title: "Turbo",
};

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<AuthContainer isPublic>
<html lang="ja">
<body className={inter.className}>{children}</body>
</html>
</AuthContainer>
);
}

export const dynamic = "error";
30 changes: 26 additions & 4 deletions frontend/core/src/components/auth/index.tsx
Expand Up @@ -5,6 +5,7 @@ import { User } from "@/services/api/models/user";
import { useRouter } from "next/navigation";
import { useContext, useEffect, useState, createContext } from "react";
import route from "@/lib/route";
import { AxiosError } from "axios";

interface IAuthContext {
user?: User;
Expand All @@ -18,7 +19,12 @@ const AuthContext = createContext<IAuthContext>({
initialized: false,
});

const AuthContainer = ({ children }: { children: React.ReactNode }) => {
interface Props {
children: React.ReactNode;
isPublic?: boolean;
}

const AuthContainer = ({ children, isPublic }: Props) => {
const router = useRouter();
const [user, setUser] = useState<User>();
const [initialized, setInitialized] = useState(false);
Expand All @@ -27,6 +33,7 @@ const AuthContainer = ({ children }: { children: React.ReactNode }) => {
const init = async () => {
try {
if (!getAccessToken()) {
debugger
const uuid = getUserId();
const r1 = await api.refreshToken({ uuid });
api.client.setAccessToken(r1.data.accessToken);
Expand All @@ -35,23 +42,38 @@ const AuthContainer = ({ children }: { children: React.ReactNode }) => {
const r2 = await api.fetchUser();
const user = factory.user(r2.data.data);
setUser(user);
setInitialized(true);
if (isPublic) {
router.push(route.main.toString());
}
} catch (e) {
router.push(route.login.with("?error=loginRequired"));
const error = e as AxiosError;
if (!isPublic && error.response?.status === 401) {
router.push(route.login.with("?error=loginRequired"));
return;
}

if (error.response?.status === 401) {
return;
}
throw e;
} finally {
setInitialized(true);
}
};

init();
}, []);

const logout = async () => {
await api.logout()
await api.logout();
setUser(undefined);
api.client.setAccessToken("");

router.push(route.login.toString());
};

console.log("initialized ===========", initialized);

if (!initialized) {
return null;
}
Expand Down
7 changes: 3 additions & 4 deletions frontend/core/src/services/api/index.ts
@@ -1,9 +1,7 @@
import axios, { AxiosError, AxiosInstance } from "axios";
import mockApi from "./mock";

let accessToken: string;

export const getAccessToken = () => accessToken;
export const getAccessToken = () => sessionStorage?.getItem('token') || '';

export const setUserId = (uuid: string) => localStorage.setItem("uuid", uuid);
export const getUserId = () => localStorage.getItem("uuid") || "";
Expand All @@ -26,6 +24,7 @@ class Client {
...(config.headers || {}),
},
});
this._instance.defaults.headers["Authorization"] = `Bearer ${getAccessToken()}`;
}

get instance() {
Expand All @@ -37,7 +36,7 @@ class Client {
}

setAccessToken = (token: string) => {
accessToken = token;
sessionStorage?.setItem('token', token)
if (this._instance) {
this._instance.defaults.headers["Authorization"] = `Bearer ${token}`;
}
Expand Down

0 comments on commit 5b9790c

Please sign in to comment.