Skip to content

Commit

Permalink
feat: 인가코드로 토큰 발급받기
Browse files Browse the repository at this point in the history
  • Loading branch information
urjimyu committed May 21, 2024
1 parent 8d11e7d commit 6afc973
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 13 deletions.
22 changes: 22 additions & 0 deletions src/hooks/queries/useGetToken.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import axios from 'axios';
import { REDIRECT_URI, REST_API_KEY } from '../../utils/login';

const useGetToken = async () => {
const code = new URL(window.location.href).searchParams.get('code');
const res = axios.post(
'https://kauth.kakao.com/oauth/token',
{
grant_type: 'authorization_code',
client_id: REST_API_KEY,
redirect_uri: REDIRECT_URI,
code: code,
},
{
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=utf-8',
},
}
);
return res;
};
export default useGetToken;
2 changes: 2 additions & 0 deletions src/hooks/queries/usePostKakao.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const usePostKakao = () => {
setKakaoLoading(true);
setKakaoError(null);
try {
console.log('TYPE', typeof accessToken);
console.log('TOKEN', accessToken);
const res = await kakao.postKakaoLogin({ kakaoToken: accessToken, fcmToken: '0' });
const data: KakaoLoginResponseType = res.data.data;
setKakaoResponse({
Expand Down
33 changes: 20 additions & 13 deletions src/pages/KakaoLoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,40 @@
// import { useEffect, useState } from "react";
import { useEffect } from "react";
import usePostKakao from "../hooks/queries/usePostKakao";
import { useNavigate } from "react-router-dom";
import { useEffect } from 'react';
import usePostKakao from '../hooks/queries/usePostKakao';
import { useNavigate } from 'react-router-dom';
import useGetToken from '../hooks/queries/useGetToken';

const KakaoLoginPage = () => {
const navigate = useNavigate();

let code = new URL(window.location.href).searchParams.get("code");
console.log("CODE", code);
if (!code) code = "";
// let code = new URL(window.location.href).searchParams.get('code');
// console.log('CODE', code);

const { kakaoResponse, kakaoError, kakaoLoading, postKakao } = usePostKakao();

const handlePostKakao = async (code: string) => {
try {
await postKakao(code);
if (!kakaoError && !kakaoLoading && kakaoResponse) {
navigate("/delete");
navigate('/delete');
}
} catch (error) {
navigate("/unregistered");
console.log("ERROR", error);
navigate('/unregistered');
console.log('ERROR', error);
}
};

useEffect(() => {
if (code) {
handlePostKakao(code);
}
}, [code]);
useGetToken()
.then((res) => {
if (res) {
const token = res.data.access_token;
localStorage.setItem('token', JSON.stringify(token));
handlePostKakao(token);
}
})
.catch((err) => console.log(err));
}, []);

return <></>;
};
Expand Down

0 comments on commit 6afc973

Please sign in to comment.