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

[#43] 로그인 성공 시 쿠키 저장 #45

Merged
merged 8 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?

.env
Copy link
Collaborator

Choose a reason for hiding this comment

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

파일 마지막은 항상 개행 부탁드립니다!

https://blog.coderifleman.com/2015/04/04/text-files-end-with-a-newline/

95 changes: 94 additions & 1 deletion package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@emotion/styled": "^11.11.0",
"@tanstack/react-query": "^5.17.9",
"@tanstack/react-query-devtools": "^5.17.9",
"axios": "^1.6.5",
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
Expand Down
1 change: 1 addition & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as instance } from './lib/instance';
export { default as getExample } from './lib/getExample';
export { default as postLogin } from './lib/postLogin';
31 changes: 28 additions & 3 deletions src/api/lib/instance.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
const instance = () => {
return 'instance';
};
import { getCookies } from '@utils/lib/cookies';
import axios from 'axios';

const instance = axios.create({
baseURL: import.meta.env.VITE_SERVER_URL,
headers: {
'Content-Type': import.meta.env.VITE_CONTENT_TYPE
}
});

// 요청 인터셉터 추가
instance.interceptors.request.use(
(config: any): any => {
const accessToken = getCookies('accessToken');

if (accessToken) {
config.headers['Authorization'] = `Bearer ${accessToken}`;
}
},
error => {
return Promise.reject(error);
}
);

// TODO : 응답 인터셉터 추가
instance.interceptors.response.use((response: any): any => {
return response;
});

export default instance;
9 changes: 9 additions & 0 deletions src/api/lib/postLogin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LoginData } from '@/types/auth';
import { instance } from '..';

const postLogin = async (loginData: LoginData) => {
const response = await instance.post('/v1/member/login', loginData);
return response.data;
};

export default postLogin;
29 changes: 26 additions & 3 deletions src/components/Login/LoginForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,41 @@ import {
AuthInputNormal,
AuthInputPassword
} from '@components/common/Auth';
import { LoginData } from '@/types/auth';
import { postLogin } from 'src/api';
import { setCookies } from '@utils/lib/cookies';

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

// HACK : 추후 useState로 입력 데이터 관리할 예쩡
const formData: LoginData = {
email: '[email protected]',
password: 'qqqq1111!'
};

// HACK: 유효성 검사 기능 구현 후 유효성 메세지 노출 여부 결정
const isInvalid = true;

const movetoSignUp = (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
navigate('/signup');
};

const handleLoginSubmit = async (
event: React.FormEvent<HTMLButtonElement>
) => {
event.preventDefault();
const response = await postLogin(formData);
setCookies(
response.name,
response.email,
response.access_token,
response.refresh_token,
response.expires_in
);
};

return (
<form>
<Inputs $isInvalid={isInvalid}>
Expand Down Expand Up @@ -44,9 +69,7 @@ const LoginForm = () => {
size="large"
variant="navy"
text="로그인"
buttonFunc={() => {
// TODO : 로그인 API 요청
}}
buttonFunc={handleLoginSubmit}
/>
<AuthButton
size="large"
Expand Down
15 changes: 15 additions & 0 deletions src/types/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,18 @@ export type AuthButton = {
};

export type AuthButtonStyleProps = { $size: string; $variant: string };

export type LoginData = {
email: string;
password: string;
};

export type SetCookies = (
userName: string,
userEmail: string,
accessToken: string,
refreshToken: string,
expiresIn: number
) => void;

export type GetCookies = (name: string) => string | undefined;
28 changes: 28 additions & 0 deletions src/utils/lib/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { SetCookies, GetCookies } from '@/types/auth';

export const setCookies: SetCookies = (
userName,
userEmail,
accessToken,
refreshToken,
expiresIn
) => {
try {
document.cookie = `userName=${userName};max-age=${expiresIn};path=/;secure`;
document.cookie = `userEmail=${userEmail};max-age=${expiresIn};path=/;secure`;
document.cookie = `accessToken=${accessToken};max-age=${expiresIn};path=/;secure`;
document.cookie = `refreshToken=${refreshToken};max-age=${expiresIn};path=/;secure`;
console.log('쿠키설정 성공');
} catch (error) {
console.log(error);
alert('쿠키설정에 실패했습니다.');
}
};
Comment on lines +10 to +20
Copy link
Collaborator

Choose a reason for hiding this comment

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

이 부분 merge 이후에 error boundary 호출할 수 있게 테스트 겸 제가 변경해도 될까요?


export const getCookies: GetCookies = name => {
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith(`${name}=`))
?.split('=')[1];
return cookieValue;
};
Comment on lines +22 to +28
Copy link
Collaborator

Choose a reason for hiding this comment

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

accessToken을 가져오기 위해서는 원하는 곳에서

getCookies('accessToken')';

이런 식으로 반환받으면 될까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

넵 맞습니다!