Skip to content

Commit

Permalink
Merge pull request #15 from TripInfoWeb/dev_auth
Browse files Browse the repository at this point in the history
fix: 토큰이 만료되어 401 에러를 받을 경우 재요청 처리 작업 수정
  • Loading branch information
ssssksss authored Sep 2, 2024
2 parents 1cce42d + 4f7392e commit bb6b2d3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
8 changes: 7 additions & 1 deletion src/app/api/auth/user/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,19 @@ export async function GET(request: NextRequest) {
cache: "no-store",
});

if (response.status === 200) {
if (response.ok) {
const data = await response.json();
return new NextResponse(JSON.stringify(data), {
status: 200,
});
}

if (response.status == 401) {
return new NextResponse("토큰 만료", {
status: 401,
});
}

cookies().delete("access_token");
cookies().delete("refresh_token");
return new NextResponse("서버 에러", {
Expand Down
28 changes: 16 additions & 12 deletions src/components/Header/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import SearchForm from "@/components/Header/SearchForm";
import useAuthStore from "@/store/authStore";
import { userResponseDto } from "@/types/UserDto";
import { fetchWithAuth } from "@/utils/fetchWithAuth";
import Image from "next/image";
import Link from "next/link";
Expand All @@ -16,19 +15,24 @@ const Header = (props: {

useLayoutEffect(() => {
// 자동 로그인
const login = async () => {
const data = await fetchWithAuth("/api/auth/user");
if (data.status == 200) {
data.json().then(async (res: userResponseDto) => {
if (!res.isAdmin) {
await fetch("/api/auth/logout");
} else {
authStore.setUser(res);
}
const login = async () => {
try {
const res = await fetchWithAuth("/api/auth/user");
if (res.status == 200) {
const data = await res.json();
authStore.setUser(data);
} else {
authStore.setUser({
id: -1,
});
}
};
login();
} catch {
authStore.setUser({
id: -1,
});
}
};
login();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down

0 comments on commit bb6b2d3

Please sign in to comment.