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

[ORT-2] feat: add KakaoLoginButton #2

Merged
merged 10 commits into from
Aug 30, 2024
24 changes: 24 additions & 0 deletions app/components/KakaoLoginButton/KakaoLoginButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React, { useMemo } from 'react';
import { v4 as uuidv4 } from 'uuid';

const clientId = 'f5aa2f20e42d783654b8e8c01bfc6312';
//redirectUri는 등록된 redirectUri중에 임의로 사용했습니다.
const redirectUri = 'http://localhost:5173/oauth/kakao';
Comment on lines +4 to +6
Copy link
Member

Choose a reason for hiding this comment

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

우선은 상관없지만, 제가 Env 관련 작업을 하고 나면 환경변수로 변경하면 좋을 듯합니다!


//이용자의 uuid를 받아와 state값으로 사용합니다.
const getUserUUID = (): string => uuidv4();
aube-dev marked this conversation as resolved.
Show resolved Hide resolved

const KakaoLoginButton: React.FC = () => {
const kakaoAuthUrl = useMemo(() => {
const userUUID = getUserUUID();
return `https://kauth.kakao.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&state=${userUUID}`;
}, []);

return (
<a href={kakaoAuthUrl}>
<button>카카오로 로그인</button>
</a>
);
};

export default KakaoLoginButton;
3 changes: 3 additions & 0 deletions app/components/KakaoLoginButton/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import KakaoLoginButton from './KakaoLoginButton';

export default KakaoLoginButton;
6 changes: 4 additions & 2 deletions app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { MetaFunction } from '@remix-run/cloudflare';
import Test from '@/components/Test';
import KakaoLoginButton from '@/components/KakaoLoginButton';
// import Test from '@/components/Test';

export const meta: MetaFunction = () => [
{ title: 'ORT - 동아리 플랫폼' },
Expand All @@ -13,7 +14,8 @@ export const meta: MetaFunction = () => [
const Index = () => (
<div>
<h1>Ort</h1>
<Test />
{/* <Test /> */}
<KakaoLoginButton />
</div>
);

Expand Down
71 changes: 71 additions & 0 deletions app/routes/oauth.kakao.tsx.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//HTTP 요청을 보내기 위해 axios라이브러리를 추가했습니다.
Copy link
Member

Choose a reason for hiding this comment

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

제가 API 요청 코드베이스를 작성 중인데, axios를 굳이 사용하지 않아도 작업이 가능할 것 같습니다.
제 작업이 끝나고 나면 그 코드베이스 기반으로 제가 수정해 놓겠습니다!

import { ActionFunction, json } from '@remix-run/cloudflare';
import { useSearchParams } from '@remix-run/react';
import axios, { AxiosError } from 'axios';
import { useEffect } from 'react';

export const action: ActionFunction = async ({ request }) => {
aube-dev marked this conversation as resolved.
Show resolved Hide resolved
//request.formData()를 통해 요청에서 전송된 폼 데이터를 가져옵니다.
const formData = await request.formData();
const code = formData.get('code');
const state = formData.get('state');

/*
code와 state 값을 추출하여 axios.post를 사용해 백엔드 서버에 요청을 보냅니다.
요청 성공 시 성공 메시지와 반환된 데이터를 JSON 형태로 반환합니다.
요청 실패 시 오류 메시지를 JSON 형태로 반환하고 콘솔에 오류를 출력합니다.
*/
try {
//추후에 진짜 백엔드 api url로 변경예정입니다.
const response = await axios.post('(백엔드api url)', {
code,
state,
});
return json({ message: 'Success', data: response.data });
} catch (error) {
const axiosError = error as AxiosError;
console.error('Error sending code to backend:', axiosError);
return json({ message: 'Error', error: axiosError.message });
}
};

/*
KakaoRedirect 함수는 카카오 로그인 후 리다이렉트된 페이지에서 실행되는 컴포넌트입니다.
useSearchParams 훅을 사용해 URL 쿼리 파라미터를 가져옵니다.
useEffect 훅을 사용해 컴포넌트가 마운트될 때 실행되는 코드를 작성합니다.
sendCodeToServer 함수는 쿼리 파라미터에서 code와 state를 추출하고, 이 값을 FormData 객체에 추가한 후, /oauth/kakao 엔드포인트로 POST 요청을 보냅니다.
*/
aube-dev marked this conversation as resolved.
Show resolved Hide resolved
const KakaoRedirect = () => {
const [searchParams] = useSearchParams();

useEffect(() => {
const sendCodeToServer = async () => {
const code = searchParams.get('code');
const state = searchParams.get('state');

if (code) {
const formData = new FormData();
formData.append('code', code);
if (state) {
formData.append('state', state);
}

try {
const response = await fetch('/oauth/kakao', {
method: 'POST',
body: formData,
});
const data = await response.json();
console.log('Server response:', data);
} catch (error) {
console.error('Error:', error);
}
}
};
sendCodeToServer();
}, [searchParams]);
aube-dev marked this conversation as resolved.
Show resolved Hide resolved
aube-dev marked this conversation as resolved.
Show resolved Hide resolved

return <div>카카오 로그인 중...</div>;
};

export default KakaoRedirect;
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
"@remix-run/react": "2.10.2",
"@remix-run/serve": "2.10.2",
"@vanilla-extract/css": "1.15.3",
"axios": "^1.7.4",
Copy link
Member

Choose a reason for hiding this comment

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

이 라이브러리 지워주실 수 있을까요? 제가 API 부분 작업하려고 합니다!

"isbot": "4.4.0",
"react": "18.3.1",
"react-dom": "18.3.1"
"react-dom": "18.3.1",
"uuid": "^10.0.0"
Copy link
Member

Choose a reason for hiding this comment

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

^을 붙이면 일관된 버전을 적용하지 않아서 예상치 못한 breaking change를 디버깅하기 어려울 수 있어요.

Suggested change
"uuid": "^10.0.0"
"uuid": "10.0.0"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

오...이건 그냥 몰랐습니다
정말 위대합니다, 선생!

},
"devDependencies": {
"@commitlint/cli": "19.3.0",
Expand All @@ -39,6 +41,7 @@
"@storybook/test": "8.2.5",
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"@types/uuid": "^10.0.0",
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
"@types/uuid": "^10.0.0",
"@types/uuid": "10.0.0",

"@typescript-eslint/eslint-plugin": "7.16.0",
"@typescript-eslint/parser": "7.16.0",
"@vanilla-extract/vite-plugin": "4.0.13",
Expand Down
76 changes: 76 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.