Skip to content

Commit

Permalink
Protected-route-구현 (#23)
Browse files Browse the repository at this point in the history
* New : 보호된 라우트 레이아웃 구현

* New : 로그인 기능 개선

* New : Protected Route 구현에 따른 디렉토리 구조 변경
  • Loading branch information
jobkaeHenry authored Nov 9, 2023
1 parent b4346d7 commit 122ae9f
Show file tree
Hide file tree
Showing 17 changed files with 115 additions and 23 deletions.
File renamed without changes.
File renamed without changes.
9 changes: 9 additions & 0 deletions client/src/app/(logoutOnly)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import useLogoutOnlyProtector from "@/hooks/useLogoutOnlyProtector";
import { ReactNode } from "react";

const LogoutOnlyLayout = async ({ children }: { children: ReactNode }) => {
useLogoutOnlyProtector();
return <>{children}</>;
};

export default LogoutOnlyLayout;
9 changes: 9 additions & 0 deletions client/src/app/(protectedRoute)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import useAuthProtector from "@/hooks/useAuthProtector";
import { ReactNode } from "react";

const AuthProtectorlayout = async ({ children }: { children: ReactNode }) => {
useAuthProtector();
return <>{children}</>;
};

export default AuthProtectorlayout;
3 changes: 3 additions & 0 deletions client/src/app/(protectedRoute)/new-post/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function NewpostPage() {
return <>페지이</>;
}
12 changes: 12 additions & 0 deletions client/src/app/@Modal/(.)new-post/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import ModalWrapper from "@/components/ModalWrapper";
import React, { ReactNode } from "react";

type Props = {
children: ReactNode;
};

const NewPostPage = ({ children }: Props) => {
return <ModalWrapper>{children}</ModalWrapper>;
};

export default NewPostPage;
19 changes: 19 additions & 0 deletions client/src/app/api/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { LOGIN_API_PATH } from "@/const/serverPath";
import { setCookie } from "@/hooks/useSetCookie";
import axios from "@/libs/axios";
import { SigninResponseInterface } from "@/types/auth/signinResponse";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
const { id, password } = await request.json();
try {
const { data } = await axios.post<SigninResponseInterface>(LOGIN_API_PATH, {
id,
password,
});
setCookie({ key: "accessToken", value: data.token, httpOnly: true });
return NextResponse.json({ ...data });
} catch {
return NextResponse.json({ message: "로그인 실패" }, { status: 400 });
}
}
2 changes: 1 addition & 1 deletion client/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"use client";

import PostCardList from "@/components/post/PostCardList";
// import { getPostListQueryFn } from "@/queries/post/useGetPostListQuery";
import { Container } from "@mui/material";
Expand Down
7 changes: 4 additions & 3 deletions client/src/components/NavigationBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import SearchIcon from "~/assets/icons/SearchIcon.svg";
import PostIcon from "~/assets/icons/PostIcon.svg";
import BeverageIcon from "~/assets/icons/BeverageIcon.svg";
import MyIcon from "~/assets/icons/MyIcon.svg";
import HOME, { MY_PROFILE, SEARCH, WIKI } from "@/const/clientPath";
import HOME, { MY_PROFILE, NEW_POST, SEARCH, WIKI } from "@/const/clientPath";
import Link from "next/link";
import { usePathname } from "next/navigation";

Expand All @@ -19,10 +19,11 @@ const NavbarData = [
{
iconComponent: <SearchIcon />,
label: "검색",
href:SEARCH
href: SEARCH,
},
{
iconComponent: <PostIcon />,
href: NEW_POST,
},
{
iconComponent: <BeverageIcon />,
Expand Down Expand Up @@ -55,7 +56,7 @@ const NavigationBar = () => {
sx={{
borderRadius: "12px 12px 0 0",
border: "1px solid",
borderBottom:'none',
borderBottom: "none",
borderColor: "gray.secondary",
boxSizing: "border-box",
}}
Expand Down
14 changes: 2 additions & 12 deletions client/src/components/user/signin/SigninForm.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
"use client";
import HOME from "@/const/clientPath";
import useLoginMutation from "@/queries/auth/useLoginMutation";
import errorHandler from "@/utils/errorHandler";
import { Box, Button, TextField, Typography } from "@mui/material";
import { useRouter } from "next/navigation";

import { useState } from "react";

const SigninForm = () => {
const [id, setId] = useState("");
const [password, setPassword] = useState("");

const router = useRouter();
const { mutate: loginHandler, isError } = useLoginMutation();
const { mutate: loginMutation, isError } = useLoginMutation();

return (
<Box
Expand All @@ -22,12 +17,7 @@ const SigninForm = () => {
if (!id || !password) {
return;
}
try {
loginHandler({ id, password });
router.push(HOME);
} catch {
errorHandler("로그인에 실패했습다다");
}
loginMutation({ id, password });
}}
sx={{ mt: 1 }}
>
Expand Down
4 changes: 4 additions & 0 deletions client/src/const/clientPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ export const POST_DETAIL = (userId: string, postId: string) => {

return `/post/@${trimmedUserId}/${trimmedPostId}`;
};
/**
* 새로운 포스트를 작성하는 페이지
*/
export const NEW_POST = '/new-post'


export default HOME;
7 changes: 6 additions & 1 deletion client/src/const/serverPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@ export const LOGIN_API_PATH = '/user/login' as const
/**
* 내 정보를 받아오는 Path
*/
export const MY_INFO = '/user/me' as const
export const MY_INFO = '/user/me' as const

/**
* 쿠키를 심어주는 로그인 BFF
*/
export const LOGIN_BFF = '/api/auth/login' as const
14 changes: 14 additions & 0 deletions client/src/hooks/useAuthProtector.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { SIGNIN } from "@/const/clientPath";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
/**
* 쿠키에 accessToken 이나 refreshToken이 없을 경우 로그인 페이지로 리다이렉트 시키는 훅스
*/
export default function useAuthProtector() {
const cookieStore = cookies();
const accessToken = cookieStore.get("accessToken")?.value;

if (!accessToken) {
redirect(SIGNIN);
}
}
16 changes: 10 additions & 6 deletions client/src/hooks/useLogin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LOGIN_API_PATH } from "@/const/serverPath";
import { LOGIN_BFF } from "@/const/serverPath";
import axios from "@/libs/axios";
import { SigninRequirement } from "@/types/auth/signinRequirement";
import { SigninResponseInterface } from "@/types/auth/signinResponse";
Expand All @@ -10,12 +10,16 @@ import { SigninResponseInterface } from "@/types/auth/signinResponse";
export default function useLogin() {
const loginHandler = async (props: SigninRequirement) => {
const { id, password } = props;
const { data } = await axios.post<SigninResponseInterface>(LOGIN_API_PATH, {
id,
password,
});
const { data } = await axios.post<SigninResponseInterface>(
LOGIN_BFF,
{
id,
password,
},
{ baseURL: process.env.NEXT_PUBLIC_CLIENT_BASE_URL }
);
return data;
};

return {loginHandler};
return { loginHandler };
}
14 changes: 14 additions & 0 deletions client/src/hooks/useLogoutOnlyProtector.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import HOME from "@/const/clientPath";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
/**
* 쿠키에 accessToken 이나 refreshToken이 있을경우 메인페이지로 리다이렉트 시키는 훅스
*/
export default function useLogoutProtector() {
const cookieStore = cookies();
const accessToken = cookieStore.get("accessToken")?.value;

if (accessToken) {
redirect(HOME);
}
}
8 changes: 8 additions & 0 deletions client/src/queries/auth/useLoginMutation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ import useLogin from "@/hooks/useLogin";
import { SigninRequirement } from "@/types/auth/signinRequirement";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { userInfoQueryKeys } from "./useUserInfoQuery";
import { useRouter } from "next/navigation";
import HOME from "@/const/clientPath";
import errorHandler from "@/utils/errorHandler";
import { AxiosError } from "axios";

const useLoginMutation = () => {
const { loginHandler } = useLogin();
const queryClient = useQueryClient();
const router = useRouter();

return useMutation({
mutationKey: LoginMuataionKey.all,
Expand All @@ -16,7 +21,10 @@ const useLoginMutation = () => {
onSuccess: async ({ token }) => {
localStorage?.setItem("accessToken", token);
queryClient.invalidateQueries({ queryKey: userInfoQueryKeys.all });
router.push(HOME);
},
onError: (error: AxiosError<{ detailMessage: string }>) =>
errorHandler(error.response?.data.detailMessage ?? "에러가 발생했니다"),
});
};

Expand Down

0 comments on commit 122ae9f

Please sign in to comment.