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: 로그인 및 Account 페이지 API 연결, 토큰 관리 로직 구현 등 #216

Merged
merged 16 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
57 changes: 32 additions & 25 deletions package-lock.json

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

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
"dayjs": "^1.11.10",
"framer-motion": "^11.0.8",
"fullcalendar": "^6.1.11",
"js-cookie": "^3.0.5",
"next": "14.1.1",
"nookies": "^2.5.2",
"openai": "^4.29.0",
"react": "^18",
"react-daum-postcode": "^3.1.3",
Expand All @@ -46,7 +46,6 @@
"@storybook/nextjs": "^7.6.17",
"@storybook/react": "^7.6.17",
"@storybook/test": "^7.6.17",
"@types/js-cookie": "^3.0.6",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
Expand Down
19 changes: 18 additions & 1 deletion src/apis/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,26 @@ import { AUTH_API, LOGIN_API, TOKENS_API } from '@/constants';
import { Account } from '@/types';

import instance from './axios';
import ssrInstance from './ssrInstance';

export const Auth = {
/**
* 로그인
* @param value
* @returns 액세스토큰, 리프레시토큰, 유저정보
*/
signin: (value: Account) => instance.post(`${AUTH_API}${LOGIN_API}`, value),

renewToken: () => instance.post(`${AUTH_API}${TOKENS_API}`),
/**
* 토큰 갱신
* @param isCsr CSR인지 아닌지
* @returns 새로운 액세스토큰, 리프레시토큰
*/
renewToken: (type: 'CSR' | 'SSR') => {
if (type === 'CSR') {
return instance.post(`${AUTH_API}${TOKENS_API}`);
} else {
return ssrInstance.post(`${AUTH_API}${TOKENS_API}`);
}
},
};
27 changes: 11 additions & 16 deletions src/apis/axios.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import Cookies from 'js-cookie';
import { parseCookies } from 'nookies';

import { ACCESS_TOKEN_EXPIRED_TIME, REFRESH_TOKEN_EXPIRED_TIME } from '@/constants';
import { setAuthCookie } from '@/utils';

import { Auth } from './auth';

Expand All @@ -11,27 +11,20 @@ const instance = axios.create({
headers: {
'Content-Type': 'application/json',
},
withCredentials: false,
});

instance.interceptors.request.use(
async (config) => {
const accessToken = Cookies.get('accessToken');
const refreshToken = Cookies.get('refreshToken');
const cookies = parseCookies();
const accessToken = cookies?.accessToken;
const refreshToken = cookies?.refreshToken;

if (!accessToken && refreshToken) {
config.headers['Authorization'] = `Bearer ${refreshToken}`;
try {
const res = await Auth.renewToken();
const res = await Auth.renewToken('CSR');
const { accessToken, refreshToken } = res.data;
Cookies.set('accessToken', accessToken, {
expires: ACCESS_TOKEN_EXPIRED_TIME,
secure: true,
sameSite: 'strict',
});
Cookies.set('refreshToken', refreshToken, {
expires: REFRESH_TOKEN_EXPIRED_TIME,
secure: true,
sameSite: 'strict',
});
setAuthCookie(null, accessToken, refreshToken);
} catch (error) {
return Promise.reject(error);
}
Expand All @@ -43,8 +36,10 @@ instance.interceptors.request.use(
},
(error) => Promise.reject(error),
);

instance.interceptors.response.use(
(response) => response,
(error) => Promise.reject(error),
);

export default instance;
11 changes: 11 additions & 0 deletions src/apis/ssrInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import axios from 'axios';

const ssrInstance = axios.create({
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
},
});

export default ssrInstance;
77 changes: 65 additions & 12 deletions src/components/auth/SigninForm/index.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
import Link from 'next/link';

import { zodResolver } from '@hookform/resolvers/zod';
import { AxiosError } from 'axios';
import classNames from 'classnames/bind';
import { FormProvider, useForm } from 'react-hook-form';
import { z } from 'zod';

import { ERROR_MESSAGE, PAGE_PATHS, REGEX } from '@/constants';
import { API_ERROR_MESSAGE, ERROR_MESSAGE, PAGE_PATHS, REGEX } from '@/constants';
import { redirectToPage } from '@/utils';

import AuthInputField from '@/components/auth/AuthInputField';
import { BaseButton } from '@/components/commons/buttons';
import { ConfirmModal, ModalButton } from '@/components/commons/modals';
import useSignin from '@/hooks/useSignin';
import useToggleButton from '@/hooks/useToggleButton';

import { Account } from '@/types';

import styles from './SigninForm.module.scss';

const cx = classNames.bind(styles);

const SigninSchema = z.object({
email: z.string().min(1, { message: ERROR_MESSAGE.email.min }).email({
message: ERROR_MESSAGE.email.regex,
}),
password: z
.string()
.min(8, { message: ERROR_MESSAGE.password.min })
.regex(REGEX.password, ERROR_MESSAGE.password.regex),
});

const SigninForm = () => {
const SigninSchema = z.object({
email: z.string().min(1, { message: ERROR_MESSAGE.email.min }).email({
message: ERROR_MESSAGE.email.regex,
}),
password: z
.string()
.min(8, { message: ERROR_MESSAGE.password.min })
.regex(REGEX.password, ERROR_MESSAGE.password.regex),
});
const { isVisible: is404Visible, handleToggleClick: toggle404Click } = useToggleButton();
const { isVisible: is400Visible, handleToggleClick: toggle400Click } = useToggleButton();

const methods = useForm({
mode: 'all',
Expand All @@ -34,6 +44,23 @@ const SigninForm = () => {
formState: { isValid },
} = methods;

const { mutate } = useSignin();

const onSubmit = (formData: object) => {
mutate(formData as Account, {
onSuccess: () => {
redirectToPage(PAGE_PATHS.mainList);
},
onError: (error) => {
if ((error as AxiosError)?.response?.status === 404) {
toggle404Click();
} else if ((error as AxiosError)?.response?.status === 400) {
toggle400Click();
}
},
});
};

return (
<section className={cx('container')}>
<div className={cx('signin')}>
Expand All @@ -45,7 +72,7 @@ const SigninForm = () => {
</div>
</header>
<FormProvider {...methods}>
<form className={cx('signin-form')}>
<form className={cx('signin-form')} onSubmit={methods.handleSubmit(onSubmit)}>
<fieldset className={cx('fieldset')}>
<legend>회원가입 정보 등록</legend>
<AuthInputField label='Email' name='email' type='email' placeholder='Type your email' />
Expand All @@ -56,7 +83,7 @@ const SigninForm = () => {
maxLength={15}
placeholder='Type your password'
/>
<BaseButton theme='fill' size='large' isDisabled={!isValid} isQuantico>
<BaseButton type='submit' theme='fill' size='large' isDisabled={!isValid} isQuantico>
Match Now
</BaseButton>
</fieldset>
Expand All @@ -69,6 +96,32 @@ const SigninForm = () => {
</Link>
</footer>
</div>
<ConfirmModal
openModal={is404Visible}
onClose={toggle404Click}
state='ALERT'
title='로그인 실패'
desc={API_ERROR_MESSAGE.signin[404]}
renderButton={
<ModalButton onClick={toggle404Click} variant='warning'>
확인
</ModalButton>
}
warning
/>
<ConfirmModal
openModal={is400Visible}
onClose={toggle400Click}
state='ALERT'
title='로그인 실패'
desc={API_ERROR_MESSAGE.signin[400]}
renderButton={
<ModalButton onClick={toggle400Click} variant='warning'>
확인
</ModalButton>
}
warning
/>
</section>
);
};
Expand Down
12 changes: 10 additions & 2 deletions src/constants/auth.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
export const ACCESS_TOKEN_EXPIRED_TIME = new Date(new Date().getTime() + 25 * 60 * 1000);
export const REFRESH_TOKEN_EXPIRED_TIME = 13;
/**
* 25분
* SS * MM
*/
export const ACCESS_TOKEN_EXPIRED_TIME = 60 * 25;
/**
* 13일
* SS * MM * HH * DD
*/
export const REFRESH_TOKEN_EXPIRED_TIME = 60 * 60 * 24 * 13;
7 changes: 7 additions & 0 deletions src/constants/inputValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,10 @@ export const REGEX = {
password: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,15}$/,
textarea: /\n/g,
};

export const API_ERROR_MESSAGE = {
signin: {
404: '회원가입을 해주세요',
400: '이메일과 비밀번호를 확인해주세요',
},
};
1 change: 1 addition & 0 deletions src/constants/pagePaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export const PAGE_PATHS = {
mypage: '/mypage',
signup: '/signup',
signin: '/signin',
mainList: '/league-of-legends',
};
Loading