Skip to content

Commit

Permalink
Merge pull request #117 from TripInfoWeb/dev_auth
Browse files Browse the repository at this point in the history
Dev auth
  • Loading branch information
ssssksss authored Jul 12, 2024
2 parents 6da75bc + df58d55 commit 61d1625
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 22 deletions.
13 changes: 13 additions & 0 deletions src/app/api/auth/logout/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export async function GET() {
try {
cookies().delete('access_token');
cookies().delete('refresh_token');
return new NextResponse("로그아웃", { status: 200 });
} catch (error) {
console.error(error);
return new NextResponse("Internal Server Error", { status: 500 });
}
}
28 changes: 28 additions & 0 deletions src/app/api/auth/user/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
try {
const cookie = request.cookies.get("access_token");
if (!cookie) {
return new NextResponse("Access token not found", { status: 401 });
}

const response = await fetch(`${process.env.BACKEND_URL}/api/user/info`, {
method: "GET",
headers: {
Cookie: `${cookie?.name}=${cookie?.value}`,
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});

const data = await response.json();
return new NextResponse(JSON.stringify(data), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error(error);
return new NextResponse("Internal Server Error", { status: 500 });
}
}
6 changes: 3 additions & 3 deletions src/components/common/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,21 +141,21 @@ const Header = ({
</>
) : (
<>
<div className={"relative rounded-[50%]"}>
<Link href={"/mypage/profile"} className={"relative rounded-[50%]"}>
<Image
className="rounded-full shadow dark:bg-slate-200"
src="/user_sex_man_default_image.svg"
alt="user_sex_man_default_image"
width={30}
height={30}
/>
</div>
</Link>
<div className="text-gray-400">|</div>
<button
onClick={logoutHandler}
className="font-semibold text-black hover:text-main dark:text-slate-200"
>
로그아웃
로그아웃
</button>
</>
)}
Expand Down
19 changes: 10 additions & 9 deletions src/containers/auth/AuthKaKaoContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import useAuthStore from "@/store/authStore";
import UrlQueryStringToObject from "@/utils/UrlQueryStringToObject";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { userResponseDto } from './../../types/UserDto';

const AuthKaKaoContainer = () => {
const router = useRouter();
Expand All @@ -16,7 +17,8 @@ const AuthKaKaoContainer = () => {
}>(window.location.href);
const kakaoLogin = async () => {
try {
const response = await fetch(
// 액세스와 리프레시 토큰 발급
await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/auth/oauth2/login?type=kakao&redirectUrl=${process.env.NEXT_PUBLIC_KAKAO_REDIRECT_URL}&code=${_queryStringObject?.code}`,
{
method: "GET",
Expand All @@ -27,14 +29,13 @@ const AuthKaKaoContainer = () => {
credentials: "include",
},
);

if (!response.ok) {
throw new Error("Network response was not ok");
}

// const res = await response.json();
// res.accessToken 받아서 사용자 정보 받아오고 홈으로 이동
authStore.setUser({ nickname: "성공" });
// 액세스 토큰을 이용해서 사용자 정보 조회
const user = await fetch("/api/auth/user", {
credentials: "include",
});
user.json().then((res: userResponseDto) => {
authStore.setUser(res);
})
router.push("/");
} catch (error) {
console.error("로그인 실패", error);
Expand Down
16 changes: 15 additions & 1 deletion src/containers/common/HeaderContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import Header from "@/components/common/Header";
import useAuthStore from "@/store/authStore";
import { userResponseDto } from "@/types/UserDto";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";

Expand All @@ -26,9 +27,10 @@ const HeaderContainer = () => {
setVisible(false);
};

const logoutHandler = () => {
const logoutHandler = async () => {
// api로 로그아웃 요청해서 쿠키제거
authStore.initialize();
await fetch("/api/auth/logout");
};

useEffect(() => {
Expand All @@ -38,6 +40,18 @@ const HeaderContainer = () => {
};
}, []);

useEffect(() => {
const login = async () => {
const user = await fetch("/api/auth/user", {
credentials: "include",
});
user.json().then((res: userResponseDto) => {
authStore.setUser(res);
});
}
login();
},[])

return (
<Header
pathname={pathname}
Expand Down
24 changes: 15 additions & 9 deletions src/store/authStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ import { devtools } from "zustand/middleware";

// 1. 상태 인터페이스 정의
interface AuthState {
id: number;
userStatus: string; // "활성화" | "휴먼" | "삭제" | "관리자" | "";
nickname: string;
name: string;
age: number; // 연도
sex: string;
email: string;
phoneNumber: string;
id: number;
isAdmin: boolean;
createdAt: string;
nickname: string;
phoneNumber: string;
sex: string; // "male, female"
userImage: {
id: number;
address: string;
createdDate: string; // "2024-07-12",
};
userStatus: string; // "활성화" | "휴먼" | "삭제" | "관리자" | "";
}

// 2. 액션 인터페이스 정의
Expand All @@ -26,13 +29,16 @@ const initialState: AuthState = {
id: NaN,
userStatus: "",
nickname: "",
name: "",
age: 0,
sex: "",
email: "",
phoneNumber: "",
isAdmin: false,
createdAt: "",
userImage: {
id: NaN,
address: "",
createdDate: "",
}
};

// 4. 상태 및 액션 생성
Expand Down
16 changes: 16 additions & 0 deletions src/types/UserDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Request 요청 결과 Dto
export interface userResponseDto {
age: number; // 연도
email: string;
id: number;
isAdmin: boolean;
nickname: string;
phoneNumber: string;
sex: string; // "male, female"
userImage: {
id: number;
address: string;
createdDate: string; // "2024-07-12",
};
userStatus: string; // "활성화" | "휴먼" | "삭제" | "관리자" | "";
}

0 comments on commit 61d1625

Please sign in to comment.