-
Notifications
You must be signed in to change notification settings - Fork 2
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] 세션 방식의 인증인가로 수정 #165
Changes from 5 commits
52475ce
5aaa868
e8d9847
6804ec8
c291496
0f18cdf
0bb2e89
3de2bf2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { LoginParams } from '../types/Auth'; | ||
|
||
import login from './login'; | ||
// 클라이언트 측의 로그인 함수 | ||
|
||
export async function clientLogin(params: LoginParams) { | ||
const { accessToken, refreshToken } = await login(params); | ||
|
||
// 세션 스토리지에 저장 | ||
if (typeof window !== 'undefined') { | ||
sessionStorage.setItem('accessToken', accessToken); | ||
localStorage.setItem('refreshToken', refreshToken); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
'use server'; | ||
|
||
import { setCookie } from '@/utils/cookies'; | ||
|
||
import { LoginParams } from '../types/Auth'; | ||
// 서버 측의 로그인 함수 | ||
|
||
async function login(params: LoginParams) { | ||
const loginData = await fetch(`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/v2/auth/login`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(params), | ||
}) | ||
.then(res => res.json()) | ||
.then(jsonRes => jsonRes.result_data); | ||
|
||
const accessToken = loginData.access_token; | ||
const refreshToken = loginData.refresh_token; | ||
|
||
setCookie('accessToken', accessToken); | ||
|
||
return { accessToken, refreshToken }; | ||
} | ||
|
||
export default login; |
This file was deleted.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,13 +3,15 @@ | |
import { useForm, SubmitHandler } from 'react-hook-form'; | ||
|
||
import Link from 'next/link'; | ||
import { useRouter, useSearchParams } from 'next/navigation'; | ||
|
||
import usePostLogin from '@/apis/queryHooks/Auth/usePostLogin'; | ||
import { clientLogin } from '@/apis/queryFunctions/clientLogin'; | ||
import GoogleIcon from '@/assets/svg/google.svg'; | ||
import NaverIcon from '@/assets/svg/naver.svg'; | ||
import CommonButton from '@/components/CommonButton'; | ||
import CommonInput from '@/components/CommonInput'; | ||
import MaxLayout from '@/components/MaxLayout'; | ||
import { useAuth } from '@/provider/authProvider'; | ||
import sha256 from '@/utils/sha256'; | ||
|
||
import * as S from './Login.css'; | ||
|
@@ -26,15 +28,31 @@ function Home() { | |
formState: { errors }, | ||
} = useForm<Inputs>(); | ||
|
||
const { mutate: login } = usePostLogin(); | ||
const { setIsLoggedIn } = useAuth(); | ||
const router = useRouter(); | ||
const searchParams = useSearchParams(); | ||
|
||
const prevUrl = searchParams.get('prevUrl'); | ||
|
||
const onSubmit: SubmitHandler<Inputs> = async data => { | ||
const newPassword = await sha256(data.passwordRequired); | ||
|
||
login({ | ||
email: data.emailRequired, | ||
password: newPassword, | ||
}); | ||
try { | ||
await clientLogin({ | ||
email: data.emailRequired, | ||
password: newPassword, | ||
}); | ||
setIsLoggedIn(true); | ||
if (prevUrl?.startsWith('/join') || prevUrl?.startsWith('/login')) { | ||
router.push('/'); | ||
} else { | ||
router.push(prevUrl || '/'); | ||
} | ||
|
||
router.refresh(); | ||
} catch (error) { | ||
console.error('Login failed:', error); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
이전 usePostLogin이랑 동일해요. mutationFn이 단지 fetch로 동작하는 것 뿐입니다! There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. const { mutate } = useMutation({
mutationFn: (loginParams: LoginParams) => setTokenCookies(loginParams),
onSuccess: data => {
sessionStorage.setItem('accessToken', data.accessToken);
localStorage.setItem('refreshToken', data.refreshToken);
setIsLoggedIn(true);
showToast('success', '로그인 되었습니다.');
if (prevUrl?.startsWith('/join') || prevUrl?.startsWith('/login')) {
router.push('/');
} else {
router.push(prevUrl || '/');
}
},
onError: (e: AxiosError<Response<string>>) => {
if (e.response) {
showToast('error', `${e.response.data.result_msg}`);
} else {
// 네트워크 에러나 기타 처리되지 않은 에러 처리
showToast('error', '알 수 없는 오류가 발생했습니다. 새로고침을 진행해 주세요.');
}
},
});
return { mutate }; 이런식으로 변경해보았어요~ |
||
}; | ||
|
||
return ( | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,6 +23,10 @@ function useChatSocket({ | |
onMessage, | ||
checkBottom, | ||
}: UseChatSocketParams) { | ||
const accessToken = sessionStorage.getItem('accessToken'); | ||
|
||
console.log('accessToken: useChatSocket.ts', accessToken); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이거 지워도 괜찮을 것 가탕요! |
||
|
||
const [newMessage, setNewMessage] = useState<Message | null>(null); | ||
const user = useGetUser(); | ||
const timerRef = useRef<NodeJS.Timeout | null>(null); // 타이머 ID 저장 | ||
|
@@ -78,6 +82,7 @@ function useChatSocket({ | |
}; | ||
|
||
const { client } = useSocket({ | ||
access: accessToken, | ||
url: `${process.env.NEXT_PUBLIC_SOCKET_SERVER_URL}`, | ||
config: { | ||
// https://stomp-js.github.io/api-docs/latest/classes/Client.html | ||
|
@@ -86,6 +91,7 @@ function useChatSocket({ | |
// 연결을 시도합니다. | ||
setMessages(lastChat); | ||
}, | ||
|
||
onWebSocketError: error => { | ||
console.log('WebSocket Error :', error); | ||
}, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이 부분 깔끔하게 eslint diabled 추가해서 require로 선언하는 거 어떨까요??
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
음...다른 곳에서도 모두 Import 문법을 쓰고 있어서 통일 하는게 더 낫다고 느껴지기는 하네요ㅠㅠ
import 하면 상단에 정의되어 비동기문으로 처리해야하는 것이 조금 불편할 수 있지만 저렇게 처리 하는 경우도 있다고 들어서요..!
혹시 성능에 큰 문제가 없다면 import문으로 통일하시는건 어떤가요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
넵 확인했습니다~