Skip to content

Commit

Permalink
[JR-865] 페이지별 권한 처리 (#171)
Browse files Browse the repository at this point in the history
* feat: 노드 환경에서 실행되지 않도록 코드 추가

* feat: 타입가드 추가

* feat: 권한별 페이지 접근 처리

* feat: test 계정의 토큰을 받는 api 추가

* feat: 테스트 계정의 토큰을 받은 후 회원가입 페이지로 리다이렉트 처리

* feat: 회원가입 유무를 판단하여 리다이렉트 시키는 코드 추가
  • Loading branch information
Leejha authored Oct 13, 2023
1 parent cb7a1a4 commit cb7b8c2
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 25 deletions.
48 changes: 48 additions & 0 deletions apps/jurumarble/src/app/test/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client";

import { getTestUserAPI, getUserInfoAPI } from "lib/apis/user";
import Path from "lib/Path";
import { queryKeys } from "lib/queryKeys";
import userStorage from "lib/utils/userStorage";
import { useRouter } from "next/navigation";
import { useEffect } from "react";

// const getQuery = [queryKeys.LOGIN_INFO];

function TestPage() {
const router = useRouter();

// const { userInfo } = useGetUserInfo();
// if (!userInfo) return null;
// const { gender, yearOfBirth, mbti } = userInfo!;
// const isRegister = gender && yearOfBirth && mbti;

// const { data: loginInfo } = useQuery(getQuery, getTestUserAPI);

useEffect(() => {
const testUserLogin = async () => {
try {
const { accessToken } = await getTestUserAPI();
userStorage.set({ accessToken });
const userInfo = await getUserInfoAPI();
if (userInfo.gender && userInfo.yearOfBirth && userInfo.mbti) {
router.push(Path.MAIN_PAGE);
} else router.push(Path.REGISTER_PAGE);
} catch (error) {
alert("에러가 발생하였습니다.");
}
};
testUserLogin();
// if (loginInfo?.accessToken) {
// userStorage.set({ accessToken: loginInfo.accessToken });
// if (isRegister) router.push(Path.MAIN_PAGE);
// else {
// router.replace(Path.REGISTER_PAGE);
// }
// }
}, []);

return <>잠시만 기다려주십시오.</>;
}

export default TestPage;
66 changes: 60 additions & 6 deletions apps/jurumarble/src/components/AuthProcess.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,69 @@
"use client";

import { useRouter } from "next/navigation";
import useGetUserInfo from "services/useGetUserInfo";
import { usePathname, useRouter } from "next/navigation";
import Path from "lib/Path";
import { useEffect } from "react";
import { isLogin } from "lib/utils/auth";
import { getUserInfoAPI } from "lib/apis/user";

const LOGIN_BLOCK_PATHS = [
Path.LOGIN_PAGE,
/**
* @NOTE 회원가입 페이지를 막을 경우 테스트 페이지에서 회원가입 페이지로
* 리다이렉트 됐을 때, 다시 메인페이지로 리다이렉트 되는 문제가 발생함.
*/
// Path.REGISTER_PAGE,
Path.KAKAO_LOGIN_PROCESS,
Path.NAVER_LOGIN_PROCESS,
Path.TEST_PAGE,
];
const GUEST_BLOCK_PATHS = [
Path.MY_PAGE,
Path.POST_PAGE,
Path.PROFILE_EDIT,
Path.NOTIFICATION_PAGE,
Path.STAMP_PAGE,
];

function AuthProcess() {
const { userInfo } = useGetUserInfo();
if (!userInfo) return null;
const { gender, yearOfBirth, mbti } = userInfo!;
// const { userInfo } = useGetUserInfo();
// const { gender, yearOfBirth, mbti } = userInfo ?? {};
const router = useRouter();
if (!(gender && yearOfBirth && mbti)) router.replace(Path.REGISTER_PAGE);
const pathname = usePathname();

// const isRegister = gender && yearOfBirth && mbti;

useEffect(() => {
const registerCheck = async () => {
try {
const userInfo = await getUserInfoAPI();
if (!(userInfo.gender && userInfo.yearOfBirth && userInfo.mbti)) {
router.push(Path.REGISTER_PAGE);
}
} catch (error) {
alert("에러가 발생하였습니다.");
}
};

if (isLogin()) {
// if (!isRegister) {
// router.replace(Path.REGISTER_PAGE);
// return;
// }
registerCheck();

/**
* @TODO any 타입 제거
*/
if (LOGIN_BLOCK_PATHS.includes(pathname as any)) {
router.push(Path.MAIN_PAGE);
}
} else {
if (GUEST_BLOCK_PATHS.includes(pathname as any)) {
router.push(Path.LOGIN_PAGE);
}
}
}, [pathname, router]);

return <></>;
}
Expand Down
1 change: 1 addition & 0 deletions apps/jurumarble/src/lib/Path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const Path = {
LOGIN_PAGE: "/login",
KAKAO_LOGIN_PROCESS: "/login/kakao-login-process",
NAVER_LOGIN_PROCESS: "/login/naver-login-process",
TEST_PAGE: "/test",

// logged In
REGISTER_PAGE: "/register",
Expand Down
14 changes: 13 additions & 1 deletion apps/jurumarble/src/lib/apis/user.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { GENDER } from "lib/constants";
import { baseApi } from "./http/base";
import { http } from "./http/http";

type GenderType = keyof typeof GENDER;
Expand All @@ -14,7 +15,7 @@ export interface GetUserInfoResponse {
userId: number;
}

export const getUserInfo = async () => {
export const getUserInfoAPI = async () => {
const response = await http.get<GetUserInfoResponse>("api/users");
return response.data;
};
Expand All @@ -30,3 +31,14 @@ export const addUserInfoAPI = async (params: AddUserInfoRequest) => {
const response = await http.put<AddUserInfoRequest>("api/users/additional-info", params);
return response.data;
};

interface GetTestUserResponse {
accessToken: string;
refreshToken: string;
newUser: boolean;
}

export const getTestUserAPI = async () => {
const response = await baseApi.get<GetTestUserResponse>("api/users/test");
return response.data;
};
1 change: 1 addition & 0 deletions apps/jurumarble/src/lib/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const queryKeys = {
DRINKS_MAP: "drinksMap" as const,
DRINKS_INFO: "drinksInfo" as const,
NOTIFICATION_LIST: "notificationList" as const,
LOGIN_INFO: "loginInfo" as const,
};

export const reactQueryKeys = {
Expand Down
16 changes: 10 additions & 6 deletions apps/jurumarble/src/lib/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@ import Path from "lib/Path";
import userStorage from "./userStorage";

export function logout() {
userStorage.remove();
window.location.replace(Path.MAIN_PAGE);
if (typeof window !== "undefined") {
userStorage.remove();
window.location.replace(Path.MAIN_PAGE);
}
}

export function isLogin() {
const user = userStorage.get();
if (!user) return false;
if (typeof window !== "undefined") {
const user = userStorage.get();
if (!user) return false;

const { accessToken } = user;
return !!accessToken;
const { accessToken } = user;
return !!accessToken;
}
}
26 changes: 16 additions & 10 deletions apps/jurumarble/src/lib/utils/userStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,27 @@ interface Token {

const userStorage = {
get() {
const user = localStorage.getItem(USER_STORAGE_KEY);
try {
if (!user) return null;
const parsedUser = JSON.parse(user) as Token;
return parsedUser;
} catch (e) {
localStorage.removeItem(USER_STORAGE_KEY);
return null;
if (typeof window !== "undefined") {
const user = localStorage.getItem(USER_STORAGE_KEY);
try {
if (!user) return null;
const parsedUser = JSON.parse(user) as Token;
return parsedUser;
} catch (e) {
localStorage.removeItem(USER_STORAGE_KEY);
return null;
}
}
},
set(user: Token) {
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
if (typeof window !== "undefined") {
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
}
},
remove() {
localStorage.removeItem(USER_STORAGE_KEY);
if (typeof window !== "undefined") {
localStorage.removeItem(USER_STORAGE_KEY);
}
},
};

Expand Down
4 changes: 2 additions & 2 deletions apps/jurumarble/src/services/useGetUserInfo.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { queryKeys } from "lib/queryKeys";
import { useQuery } from "@tanstack/react-query";
import { getUserInfo, GetUserInfoResponse } from "lib/apis/user";
import { getUserInfoAPI, GetUserInfoResponse } from "lib/apis/user";

const getQueryKey = [queryKeys.USER_INFO];

export default function useGetUserInfo() {
const { data: userInfo } = useQuery<GetUserInfoResponse>(getQueryKey, getUserInfo, {
const { data: userInfo } = useQuery<GetUserInfoResponse>(getQueryKey, getUserInfoAPI, {
placeholderData: () => ({
gender: "MALE",
nickname: "",
Expand Down

0 comments on commit cb7b8c2

Please sign in to comment.