-
Notifications
You must be signed in to change notification settings - Fork 5
Feature: 회원가입, 로그인 화면 구현 및 axios 인터셉터 설정 #52
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
Merged
Merged
Changes from 34 commits
Commits
Show all changes
44 commits
Select commit
Hold shift + click to select a range
7598b14
feat: 회원가입 화면 UI 개발
summerDev96 c0c4f46
feat: 회원가입 화면 react-hook-form, zod 적용, FormInput 컴포넌트 추가
summerDev96 503f32c
chore: FormInput 컴포넌트 주석 추가
summerDev96 5f38e73
feat: 회원가입 기능 API 연결 중
summerDev96 2c06250
feat: 회원가입 화면 에러 처리 수정
summerDev96 e52f7dd
feat: 회원가입 후 로그인 자동 처리 로직 추가
summerDev96 129e59a
feat: 로그인 페이지 추가
summerDev96 d22e8fc
Merge branch 'dev' of https://github.com/codeit-part3-7/WHYNE_FE into…
summerDev96 e8aec0a
fix: 오류 수정
summerDev96 8a47aad
Merge branch 'dev' of https://github.com/codeit-part3-7/WHYNE_FE into…
summerDev96 1e5f5fb
feat: axios 인터셉터 토큰 및 에러 처리 로직 수정
summerDev96 43760d3
fix: 앱 내 Gnb 안보이는 페이지 목록에 로그인화면 추가
summerDev96 187bba9
feat: 회원가입, 로그인화면 토큰 저장 추가
summerDev96 544906f
feat: 회원가입, 로그인 및 axios 설정 완료
summerDev96 b952a7b
fix: 로그인 에러 시 서버 오류 처리
summerDev96 47179c8
refactor: 리액트훅폼 메소드 구조 분해할당하여 사용
summerDev96 8d2dd6f
fix: 회원가입 시 비밀번호 입력값 변경 시 비밀번호 확인 체크하도록 변경
summerDev96 3855c32
feat: 카카오로그인 버튼 추가중
summerDev96 1e2da84
chore: 주석 제거
summerDev96 cd2f14b
fix: header 태그 설정 수정
summerDev96 da83ffa
feat: 회원가입/로그인 페이지 리디렉트 처리
summerDev96 1543814
fix: 리프레쉬 토큰 에러 시 리디렉트 처리 수정
summerDev96 4d4a075
fix: 카카오 로그인 경로 수정
summerDev96 15f413a
fix: axios 인터셉터 메소드 수정
summerDev96 2ab7649
feat: 회원가입/로그인 화면 구현완료
summerDev96 3cac55c
Merge branch 'dev' of https://github.com/codeit-part3-7/WHYNE_FE into…
summerDev96 9d8245e
fix: 빌드 오류 수정
summerDev96 464dfa9
chore: 인터셉터 코드 순서 변경
summerDev96 9435d7a
fix: apiClient 임포트 시 이름 변경
summerDev96 89b992a
chore: 밀리초 표기형식 변경
summerDev96 89a4eb6
fix: 회원가입, 로그인 화면 훅 분리
summerDev96 af1d671
fix: 카카오 로그인 처리 화면 에러 모달 적용
summerDev96 eca3cd3
refactor: 폼 인풋 입력 시 인풋 초기화 및 비밀번호 유효성 체크 메소드 추가
summerDev96 e3aea2c
refactor: 카카오 로그인 버튼 컬러 변경
summerDev96 adc13b3
fix: 로그인/회원가입 리디렉트 처리 추가
summerDev96 531732d
fix: 리디렉트 처리 토큰 확인 추가
summerDev96 79a23cc
feat: 토큰 체크 훅 추가
summerDev96 aff7213
feat: FormInput 컴포넌트 비밀번호 아이콘 추가
summerDev96 ce390d5
fix: 머지 충돌 해결
summerDev96 d8c3fe5
fix: 로그인/회원가입 화면 인풋 gap 조정
summerDev96 67cd440
Merge branch 'dev' of https://github.com/codeit-part3-7/WHYNE_FE into…
summerDev96 e365daa
chore: 폼 인풋 컴포넌트 콘솔 삭제
summerDev96 1548545
chore: pacakge-lock.json 변경
summerDev96 aaaed45
fix: 비밀번호 아이콘 button으로 수정 및 aria 속성 추가
summerDev96 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "extends": "next/core-web-vitals" | ||
| } |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios'; | ||
| import Router from 'next/router'; | ||
|
|
||
| import { RetryRequestConfig } from '@/types/AuthTypes'; | ||
|
|
||
| import { updateAccessToken } from './auth'; | ||
|
|
||
| // axios 인스턴스 생성 | ||
| const apiClient = axios.create({ | ||
| baseURL: process.env.NEXT_PUBLIC_BASE_URL, | ||
| timeout: 10_000, | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| }); | ||
|
|
||
| /* Axios 인터셉터 설정 */ | ||
| // 토큰 추가 인터셉터 | ||
| apiClient.interceptors.request.use(addAccessToken); | ||
|
|
||
| // 에러 처리 및 리프레쉬 토큰 추가 인터셉터 | ||
| apiClient.interceptors.response.use( | ||
| (res) => res.data, | ||
| async (error) => { | ||
| const status = error.response?.status; | ||
| const refreshToken = localStorage.getItem('refreshToken'); | ||
|
|
||
| if (status !== 401 || !refreshToken) return handleCommonError(error); | ||
| try { | ||
| const result = await handleRequestRefreshToken(error, refreshToken); | ||
| if (result) return result; | ||
| } catch (refreshTokenError) { | ||
| // 토큰 삭제 처리 후 리디렉트 | ||
| localStorage.removeItem('accessToken'); | ||
| localStorage.removeItem('refreshToken'); | ||
| Router.replace('/signin'); | ||
| return handleCommonError(refreshTokenError as AxiosError); | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| export default apiClient; | ||
|
|
||
| // 토큰 추가 메소드 | ||
| function addAccessToken(config: InternalAxiosRequestConfig) { | ||
| const accessToken = localStorage.getItem('accessToken'); | ||
| if (accessToken && config.headers) { | ||
| config.headers.Authorization = `Bearer ${accessToken}`; | ||
| } | ||
| return config; | ||
| } | ||
|
|
||
| // 공통 에러 처리 메소드 | ||
| function handleCommonError(error: AxiosError) { | ||
| if (!error.response) { | ||
| return Promise.reject(new Error('네트워크 오류가 발생했습니다. 인터넷 상태를 확인해주세요.')); | ||
| } | ||
|
|
||
| const { status, data } = error.response; | ||
| // todo: 에러 타입 정의하여 바꾸기 | ||
| let errorMessage = (data as { message?: string })?.message ?? '서버에서 오류가 발생했습니다.'; | ||
|
|
||
| // 에러 디버깅 | ||
| console.error('API 에러 발생:', { status, errorMessage, data }); | ||
| return Promise.reject(error); | ||
| } | ||
|
|
||
| // 리프레쉬 토큰 및 에러 처리 메소드 | ||
| async function handleRequestRefreshToken( | ||
| error: AxiosError, | ||
| refreshToken: string, | ||
| ): Promise<AxiosResponse | null> { | ||
| const originalRequest = error.config as RetryRequestConfig; | ||
|
|
||
| if (originalRequest._retry) return null; | ||
| originalRequest._retry = true; | ||
|
|
||
| const data = await updateAccessToken({ refreshToken }); | ||
|
|
||
| // 갱신받은 access 토큰 저장 | ||
| localStorage.setItem('accessToken', data.accessToken); | ||
|
|
||
| // 새 토큰으로 헤더 수정 | ||
| if (originalRequest.headers) { | ||
| originalRequest.headers.Authorization = `Bearer ${data.accessToken}`; | ||
| } | ||
|
|
||
| return apiClient(originalRequest); // 토큰 갱신 후 재요청 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import apiClient from '@/api/apiClient'; | ||
| import { | ||
| AccessTokenRequest, | ||
| AccessTokenResponse, | ||
| KakakoSignInRequest, | ||
| KakakoSignInResponse, | ||
| LoginRequest, | ||
| LoginResponse, | ||
| SignupRequest, | ||
| SignupResponse, | ||
| } from '@/types/AuthTypes'; | ||
|
|
||
| export const createUser = (data: SignupRequest): Promise<SignupResponse> => { | ||
| return apiClient.post(`/${process.env.NEXT_PUBLIC_TEAM}/auth/signUp`, data); | ||
| }; | ||
|
|
||
| export const loginUser = (data: LoginRequest): Promise<LoginResponse> => { | ||
| return apiClient.post(`/${process.env.NEXT_PUBLIC_TEAM}/auth/signIn`, data); | ||
| }; | ||
|
|
||
| export const updateAccessToken = (data: AccessTokenRequest): Promise<AccessTokenResponse> => { | ||
| return apiClient.post(`/${process.env.NEXT_PUBLIC_TEAM}/auth/refresh-token`, data); | ||
| }; | ||
|
|
||
| export const signInKakao = (data: KakakoSignInRequest): Promise<KakakoSignInResponse> => { | ||
| return apiClient.post(`/${process.env.NEXT_PUBLIC_TEAM}/auth/signIn/KAKAO`, data); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| import apiClient from '@/api/apiClient'; | ||
| import { GetUserResponse } from '@/types/UserTypes'; | ||
|
|
||
| export const getUser = (): Promise<GetUserResponse> => { | ||
| return apiClient.get(`/${process.env.NEXT_PUBLIC_TEAM}/users/me`); | ||
| }; |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import React from 'react'; | ||
|
|
||
| import { cn } from '@/lib/utils'; | ||
|
|
||
| interface AuthLayoutProps { | ||
| children?: React.ReactNode; | ||
| className?: string; | ||
| } | ||
| const AuthLayout = ({ children, className }: AuthLayoutProps) => { | ||
| const bgClass = 'flex justify-center items-center bg-gray-100 min-h-screen'; | ||
| const cardClass = cn( | ||
| 'w-full max-w-[21rem] md:max-w-[31rem] py-14 px-5 md:py-16 md:px-12 lg:py-20 flex flex-col items-center justify-center rounded-2xl bg-white border border-gray-300 shadow-[0px_2px_20px_rgba(0,0,0,0.04)]', | ||
| className, | ||
| ); | ||
|
|
||
| return ( | ||
| <div className={bgClass}> | ||
| <div className={cardClass}>{children}</div> | ||
| </div> | ||
| ); | ||
| }; | ||
|
|
||
| export default AuthLayout; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import Logo from '../common/Logo'; | ||
|
|
||
| const AuthLogo = () => { | ||
| return ( | ||
| <div className='w-[104px] h-[30px] mb-[56px] md:mb-[64px]'> | ||
| <Logo className='text-black' /> | ||
| </div> | ||
| ); | ||
| }; | ||
|
|
||
| export default AuthLogo; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import React from 'react'; | ||
|
|
||
| import { | ||
| useFormContext, | ||
| useFormState, | ||
| type FieldErrors, | ||
| type FieldValues, | ||
| type Path, | ||
| } from 'react-hook-form'; | ||
|
|
||
| import Input from '@/components/common/Input'; | ||
|
|
||
| interface FormInputProps<T> { | ||
| placeholder: string; | ||
| name: Path<T>; | ||
| type: string; | ||
| id: string; | ||
| onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void; | ||
| } | ||
|
|
||
| // FormProvider로 감싸지 않으면 오류 발생 | ||
| const FormInput = <T extends FieldValues>(props: FormInputProps<T>) => { | ||
| const { placeholder, name, type, id, onChange } = props; | ||
| const methods = useFormContext(); | ||
| const { errors } = useFormState({ name }); | ||
|
|
||
| function getErrorMessage(errors: FieldErrors) { | ||
| const errMsg = errors[name]?.message; | ||
| const result = errMsg && typeof errMsg === 'string' ? errMsg : ''; | ||
| return result; | ||
| } | ||
|
|
||
| const { onChange: formOnChange, ...inputProps } = methods.register(name); | ||
|
|
||
| return ( | ||
| <Input | ||
| {...inputProps} | ||
| type={type} | ||
| id={id} | ||
| name={name} | ||
| placeholder={placeholder} | ||
| errorMessage={getErrorMessage(errors)} | ||
| onChange={(e) => { | ||
| formOnChange(e); | ||
| onChange?.(e); | ||
| }} | ||
| /> | ||
| ); | ||
| }; | ||
|
|
||
| export default FormInput; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import React from 'react'; | ||
|
|
||
| import ConfirmModal from '@/components/common/Modal/ConfirmModal'; | ||
| import { Button } from '@/components/ui/button'; | ||
|
|
||
| interface ErrorModalProps { | ||
| open: boolean; | ||
| onOpenChange: (value: boolean) => void; | ||
| onConfirm?: () => void; | ||
| errorMessage: string; | ||
| } | ||
|
|
||
| const ErrorModal = ({ open, onOpenChange, errorMessage, onConfirm }: ErrorModalProps) => { | ||
| return ( | ||
| <ConfirmModal | ||
| open={open} | ||
| onOpenChange={onOpenChange} | ||
| /* 버튼커스텀 영역 */ | ||
| buttons={ | ||
| <> | ||
| <Button | ||
| size='xl' | ||
| width='xl' | ||
| variant='purpleDark' | ||
| className='flex-auto text-base font-bold' | ||
| onClick={() => { | ||
| onOpenChange(false); | ||
| onConfirm?.(); | ||
| }} | ||
| > | ||
| 확인 | ||
| </Button> | ||
| </> | ||
| } | ||
| > | ||
| {/* 모달 내용 영역 */} | ||
| {errorMessage} | ||
| </ConfirmModal> | ||
| ); | ||
| }; | ||
|
|
||
| export default ErrorModal; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { useEffect } from 'react'; | ||
|
|
||
| import { useQuery } from '@tanstack/react-query'; | ||
| import { useRouter } from 'next/router'; | ||
|
|
||
| import { getUser } from '@/api/user'; | ||
|
|
||
| const useAuthRedirect = () => { | ||
| const router = useRouter(); | ||
| const { data: userData, isLoading } = useQuery({ | ||
| queryKey: ['getUser'], | ||
| queryFn: getUser, | ||
| retry: false, | ||
| }); | ||
|
|
||
| useEffect(() => { | ||
| if (userData) { | ||
| router.replace('/'); | ||
| } | ||
| }, [userData, router]); | ||
|
|
||
| return { userData, isLoading }; | ||
| }; | ||
|
|
||
| export default useAuthRedirect; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import { useState } from 'react'; | ||
|
|
||
| const useErrorModal = () => { | ||
| const [open, setOpen] = useState(false); | ||
| const [errorMessage, setErrorMessage] = useState(''); | ||
|
|
||
| const updateErrorMessage = (error: Error) => { | ||
| setErrorMessage(error.message); | ||
| }; | ||
|
|
||
| const showErrorModal = () => { | ||
| setOpen(true); | ||
| }; | ||
|
|
||
| const closeErrorModal = () => { | ||
| setOpen(false); | ||
| setErrorMessage(''); | ||
| }; | ||
|
|
||
| const handleError = (error: Error) => { | ||
| updateErrorMessage(error); | ||
| showErrorModal(); | ||
| }; | ||
|
|
||
| return { open, setOpen, errorMessage, handleError, showErrorModal, closeErrorModal }; | ||
| }; | ||
|
|
||
| export default useErrorModal; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import z from 'zod'; | ||
| export const emailSchema = z | ||
| .string() | ||
| .min(1, '이메일은 필수 입력입니다.') | ||
| .refine( | ||
| (val) => { | ||
| const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; | ||
| return emailRegex.test(val); | ||
| }, | ||
| { | ||
| message: '이메일 형식으로 작성해 주세요.', | ||
| }, | ||
| ); | ||
|
|
||
| export const nicknameSchema = z | ||
| .string() | ||
| .min(1, '닉네임은 필수 입력입니다.') | ||
| .max(20, '닉네임은 최대 20자까지 가능합니다.'); | ||
|
|
||
| export const passwordSchema = z | ||
| .string() | ||
| .min(1, '비밀번호는 필수 입력입니다.') | ||
| .min(8, '비밀번호는 최소 8자 이상입니다.') | ||
| .refine( | ||
| (val) => { | ||
| // 이메일 정규식 직접 검사 | ||
| const passwordRegex = /^[A-Za-z0-9!@#$%^&*]+$/; | ||
| return passwordRegex.test(val); | ||
| }, | ||
| { | ||
| message: '비밀번호는 숫자, 영문, 특수문자로만 가능합니다.', | ||
| }, | ||
| ); | ||
|
|
||
| export const passwordConfirmationSchema = z | ||
| .string() | ||
| .min(1, '비밀번호 확인을 입력해주세요') | ||
| .min(8, '비밀번호 확인을 8자 이상 입력해주세요'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
깔끔하게 구현 잘 하셨네요. 색상도 잘 넣은 것 확인했습니다. 승인하겠습니다!
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.
테일윈드 색상 추가한 부분도 꼼꼼히 확인해주셨군요 감사합니다!