Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat/#138] 카카오로그인 구현 완료 #145

Merged
merged 7 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file removed src/apis/auth/.keep
Empty file.
50 changes: 50 additions & 0 deletions src/apis/auth/usePostKakaoLogin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { AxiosResponse } from 'axios';

import { post } from '@apis/instance';

import { END_POINT, queryKey } from '@constants';
import { useEasyNavigate } from '@hooks';

import { ApiResponseType, LoginSuccessResponse } from '@types';

const postKakaoLogin = async (
authCode: string
): Promise<AxiosResponse<ApiResponseType<LoginSuccessResponse>>> => {
const response = await post<ApiResponseType<LoginSuccessResponse>>(
END_POINT.KAKAO_LOGIN,
{
socialType: 'KAKAO',
},
{
headers: {
Authorization: authCode,
},
}
);

return response;
};

export const usePostKakaoLogin = () => {
const queryClient = useQueryClient();
const { goHomePage } = useEasyNavigate();

return useMutation({
mutationFn: (authCode: string) => postKakaoLogin(authCode),
onSuccess: (response) => {
const resData = response.data.data;
if (resData) {
const { userId, userName } = resData;
const user = { userId, userName };
localStorage.setItem('user', JSON.stringify(user));

queryClient.invalidateQueries({ queryKey: [queryKey.KAKAO_LOGIN] });
goHomePage();
}
},
onError: (error) => {
console.log(error);
},
});
};
4 changes: 0 additions & 4 deletions src/apis/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ export const instance = axios.create({
baseURL: BASE_URL,

withCredentials: false,

// headers: {
// // Authorization: `Bearer 엑세스 토큰`,
// }, 서버에서 set-cookie로 줘서 만약 필요 없으면 지울 예정
});

export function get<T>(...args: Parameters<typeof instance.get>) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,17 @@ const platformIcon = {
kakao: <IcKakao />,
};

const SocialLoginButton = ({ platform, children }: SocialLoginButtonProps) => {
const SocialLoginButton = ({
platform,
children,
onClick,
}: SocialLoginButtonProps) => {
return (
<button
className={buttonStyle({
platform,
})}
onClick={onClick}
>
<span className={iconStyle}>{platformIcon[platform]}</span>
{children}
Expand Down
1 change: 1 addition & 0 deletions src/constants/apis/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export const BASE_URL = import.meta.env.VITE_APP_BASE_URL;

export const END_POINT = {
FETCH_STORE_RANK: '/api/v1/store/rank',
KAKAO_LOGIN: '/api/v1/user/login',
} as const;
1 change: 1 addition & 0 deletions src/constants/apis/queryKey.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const queryKey = {
STORE_RANK: 'storeRank',
KAKAO_LOGIN: 'kakaoLogin',
} as const;
8 changes: 2 additions & 6 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { StrictMode } from 'react';
// import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

import App from './App.tsx';

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
);
createRoot(document.getElementById('root')!).render(<App />);
22 changes: 18 additions & 4 deletions src/pages/auth/page/LoginPage/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useEffect } from 'react';

import { SocialLoginButton } from '@components';
import { LoginPageImage } from '@constants';
import { useEasyNavigate } from '@hooks';
import { isLoggedIn } from '@utils';

import { ImgLogo } from '@svgs';

Expand All @@ -16,6 +19,19 @@ import {

const LoginPage = () => {
const { goHomePage } = useEasyNavigate();
const kakaoLoginUrl = `https://kauth.kakao.com/oauth/authorize?client_id=${
import.meta.env.VITE_REST_API_KEY
}&redirect_uri=${import.meta.env.VITE_REDIRECT_URI}&response_type=code`;

const handleLoginClick = () => {
window.location.replace(kakaoLoginUrl);
};

useEffect(() => {
if (isLoggedIn()) {
goHomePage();
}
}, [goHomePage]);
return (
<div className={loginPageStlye}>
<div className={titleWrapper}>
Expand All @@ -28,12 +44,10 @@ const LoginPage = () => {
<div className={imageButtonContainer}>
<img src={LoginPageImage} className={loginMainImage} />
<div className={loginButtonWrapper}>
<SocialLoginButton platform="kakao">
<SocialLoginButton platform="kakao" onClick={handleLoginClick}>
카카오로 시작하기
</SocialLoginButton>
<u className={noLoginButton} onClick={goHomePage}>
로그인 없이 둘러보기
</u>
<u className={noLoginButton}>로그인 없이 둘러보기</u>
</div>
</div>
</div>
Expand Down
18 changes: 18 additions & 0 deletions src/pages/auth/page/Redirection/Redirection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react';

import { usePostKakaoLogin } from '@apis/auth/usePostKakaoLogin';

const Redirection = () => {
const code: string =
new URL(window.location.href).searchParams.get('code') || '';
window.history.forward();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

goHome을 작성해준다면 forward()는 불필요할 것 같습니다!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로그인 성공시 사용자가 브라우저 뒤로가기를 했을 때 카카오로그인 관련 url로 되돌아 가는것을 방지하기 위함입니다!!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

엇 그런거군요!!! 새롭게 알아갑니다💡

const { mutate } = usePostKakaoLogin();

useEffect(() => {
if (code) mutate(code);
}, [code, mutate]);

return <div></div>;
};

export default Redirection;
4 changes: 3 additions & 1 deletion src/pages/auth/page/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
import LoginPage from './LoginPage/LoginPage';
export { LoginPage };
import Redirection from './Redirection/Redirection';

export { LoginPage, Redirection };
7 changes: 5 additions & 2 deletions src/routes/authRoutes.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { LoginPage } from '@pages/auth/page';
import { LoginPage, Redirection } from '@pages/auth/page';

import routePath from './routePath';

import { RouteType } from '@types';


const authRoutes: RouteType[] = [
{
path: routePath.LOGINPAGE,
element: <LoginPage />,
},
{
path: routePath.KAKAO_REDIRECTION,
element: <Redirection />,
},
];

export default authRoutes;
3 changes: 2 additions & 1 deletion src/routes/routePath.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const authPages = {
LOGINPAGE: '/login',
KAKAO_REDIRECTION: '/kakao/redirection',
};

const homePages = {
Expand All @@ -12,7 +13,7 @@ const designListPages = {

const myPages = {
MYPAGE: '/mypage',
LIKELISTPAGE: '/mypage/like-list'
LIKELISTPAGE: '/mypage/like-list',
};

const storePages = {
Expand Down
4 changes: 4 additions & 0 deletions src/types/apis/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface LoginSuccessResponse {
userId: number;
userName: string;
}
2 changes: 2 additions & 0 deletions src/types/apis/commonType.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// 공통으로 사용되는 타입들을 정의합니다.

export interface ApiResponseType<T> {
code: number;
message: string;
Expand Down
1 change: 0 additions & 1 deletion src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export * from './routeType';
export * from './toastType';
export * from './orderFormType';
export * from './types';

export * from './apis/commonType';
export * from './apis/auth/index';
export * from './apis/designList/index';
Expand Down
7 changes: 7 additions & 0 deletions src/utils/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const getToken = () => {
return localStorage.getItem('user');
};

export const isLoggedIn = () => {
return getToken() ? true : false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어차피 true 또는 false로 반환되는 거면 삼항연산자보다 Boolean 함수가 더 적절해보입니다..!
return Boolean(getToken());은 어떠신가요 🤔

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋네요! 반영하겠습니다!

};
3 changes: 2 additions & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './getMarkerIcon';
export * from './formatHours';
export * from './formatHours';
export * from './auth';
Loading