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

[REFACTOR] Refresh token 도입, Locker API 검증 #80

Merged
merged 13 commits into from
Feb 29, 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
15 changes: 8 additions & 7 deletions src/@types/locker.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ declare namespace Locker {
export interface Dto {
id: string;
name: string;
description: string;
//description: string;
enableLockerCount: number;
totalLockerCount: number;
}
export interface LocationDto {
id: string;
lockerNumber: number;
lockerLocationName: string;
//lockerLocationName: string;
updatedAt: string;
expireAt: string;
isActive: boolean;
Expand All @@ -29,15 +29,16 @@ declare namespace Locker {
export interface FindByLocationResponseDto {
locationName: string;
lockerList: LockerLocationDto[];
/*
LockerLocationDto may be: id: string;
}

interface LockerLocationDto {
id: string;
lockerNumber: number;
lockerLocationName: string;
//lockerLocationName: string;
updatedAt: string;
expireAt: string;
isActive: boolean;
isMine: boolean;
*/
isMine: boolean;
}

export interface FindByLocationResponse {
Expand Down
4 changes: 4 additions & 0 deletions src/@types/user.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ declare namespace User {
updatedPassword: string;
}

export interface UpdateAccessTokenRequestDto {
refreshToken: string;
}

// ==

export interface FindPostsResponse {
Expand Down
25 changes: 1 addition & 24 deletions src/AuthRouter.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,10 @@
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
import { useHistory, useLocation, Route, Redirect } from 'react-router-dom';

import { PAGE_URL } from '@/configs/path';
import { useRootStore } from '@/stores/RootStore';
import { Route } from 'react-router-dom';

type Props = {
children?: React.ReactNode;
};

export const AuthRouter: React.FC<Props> = observer(({ children, ...rest }) => {
const {
auth: { checkToken },
} = useRootStore();
const history = useHistory();
const location = useLocation();

const isTokenAvailable = async () => {
const { success } = (await checkToken()) as unknown as StoreAPI;
if (!success)
history.push({
pathname: PAGE_URL.SignIn,
state: { from: location },
});
};

useEffect(() => {
isTokenAvailable();
}, []);

return <Route {...rest} render={() => children} />;
});
56 changes: 33 additions & 23 deletions src/configs/axios.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios from 'axios';
import axios, { AxiosResponse } from 'axios';

import { PAGE_URL } from './path';

Expand All @@ -9,42 +9,52 @@ export const API = axios.create({
: import.meta.env.VITE_DEV_SERVER_URL,
});

export const setAuth = (token: string): unknown => (API.defaults.headers['Authorization'] = token);
export const resetAuth = (): unknown => delete API.defaults.headers['Authorization'];
//Auth
export const setAccess = (token: string): unknown =>
(API.defaults.headers['Authorization'] = token);
export const resetAccess = (): unknown => delete API.defaults.headers['Authorization'];

const storageKey = 'CAUCSE_JWT';
//Refresh
const storageRefreshKey = 'CAUCSE_JWT_REFRESH';

export const storeAuth = (isStored: boolean, token: string): void => {
if (isStored) localStorage.setItem(storageKey, token);
else sessionStorage.setItem(storageKey, token);
export const storeRefresh = (token: string): void => {
localStorage.setItem(storageRefreshKey, token);
};
export const restoreAuth = (): boolean => {
const token = localStorage.getItem(storageKey) ?? sessionStorage.getItem(storageKey);

if (token) setAuth(token);

return !!token;
export const removeRefresh = (): void => {
localStorage.removeItem(storageRefreshKey);
};
export const removeAuth = (): void => {
localStorage.removeItem(storageKey);
sessionStorage.removeItem(storageKey);
export const getRefresh = (): string | null => {
return localStorage.getItem(storageRefreshKey);
};

API.interceptors.response.use(
response => response,
error => {
async error => {
if (error.response) {
const {
response: { data },
config,
} = error;

// 4012: 접근 권한이 없습니다. 다시 로그인 해주세요. 문제 반복시 관리자에게 문의해주세요.
// 4103: 비활성화된 사용자 입니다.
// 4015: 다시 로그인 해주세요.

if (data.errorCode === 4012 || data.errorCode === 4103 || data.errorCode === 4105) {
removeAuth();
if (!localStorage.getItem(storageRefreshKey) || config.url === '/api/v1/users/token/update') {
removeRefresh();
if (location.pathname !== PAGE_URL.SignIn) location.href = PAGE_URL.SignIn;
} else if (data.errorCode === '4105') {
const {
data: { accessToken, refreshToken },
} = (await API.put(`/api/v1/users/token/update`, {
refreshToken: getRefresh(),
})) as AxiosResponse<{
accessToken: string;
refreshToken: string;
}>;

setAccess(accessToken);
removeRefresh();
storeRefresh(refreshToken);

config.headers['Authorization'] = accessToken;
return API.request(config);
}

return Promise.reject({
Expand Down
6 changes: 2 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ render(
document.getElementById('root'),
);

/* mocking
async function enableMocking() {
/* async function enableMocking() {
if (process.env.NODE_ENV !== 'development') {
return;
}
Expand All @@ -39,5 +38,4 @@ enableMocking().then(() => {
</React.StrictMode>,
document.getElementById('root'),
);
});
*/
}); */
4 changes: 2 additions & 2 deletions src/mocks/data/locker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const lockerAllLocationsList: Locker.FindAllLocationResponseDto = {
{
id: '3',
name: 'locker_location',
description: 'description',
//description: 'description',
enableLockerCount: 0,
totalLockerCount: 0,
},
Expand All @@ -16,7 +16,7 @@ export const lockerAllLocationsList: Locker.FindAllLocationResponseDto = {
isMine: true,
lockerNumber: 1,
updatedAt: '2024-01-22T09:50:43.175Z',
lockerLocationName: 'lockerLocationName', //problem: Swagger API에 없음
//lockerLocationName: 'lockerLocationName', //problem: Swagger API에 없음
},
};

Expand Down
36 changes: 36 additions & 0 deletions src/mocks/handlers/authHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { http, ResponseResolver, HttpResponse } from 'msw';

const postSignInHandler: ResponseResolver = () => {
return HttpResponse.json<{
accessToken: string;
refreshToken: string;
}>({
accessToken: 'accessToken',
refreshToken: 'refreshToken',
});
};

const putAccessTokenHandler: ResponseResolver = () => {
return HttpResponse.json<{
accessToken: string;
refreshToken: string;
}>({
accessToken: 'accessToken2',
refreshToken: 'refreshToken2',
});
};

const accessTokenErrorHandler: ResponseResolver = () => {
return new HttpResponse(null, {
status: 401,
});
};

export const authHandler = [
// http.post(import.meta.env.VITE_DEV_SERVER_URL + '/api/v1/users/sign-in', postSignInHandler),
http.put(
import.meta.env.VITE_DEV_SERVER_URL + '/api/v1/users/token/update',
putAccessTokenHandler,
),
// http.get(import.meta.env.VITE_DEV_SERVER_URL + '/api/v1/users/me', accessTokenErrorHandler),
];
2 changes: 2 additions & 0 deletions src/mocks/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { authHandler } from './authHandler';
import { boardHandler } from './boardHandler';
import { circleHandler } from './circleHandler';
import { commentHandler } from './commentHandler';
Expand All @@ -16,6 +17,7 @@ const handlers = [
...lockerHandler,
...historyHandler,
...settingHandler,
...authHandler,
];

export default handlers;
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useEffect, useState } from 'react';
import { Bar, Card, Desc, Name, Status } from './styled';

export const LockerListCard: React.FC<{ model: Model.Locker }> = ({
model: { to, name, description, enableLockerCount, totalLockerCount },
model: { to, name, enableLockerCount, totalLockerCount },
}) => {
const [progress, setProgress] = useState(0);

Expand All @@ -14,7 +14,7 @@ export const LockerListCard: React.FC<{ model: Model.Locker }> = ({
return (
<Card to={to}>
<Name>{name}</Name>
<Desc>{description}</Desc>
{/* <Desc>{description}</Desc> */}
<Bar variant="determinate" value={progress} />
<Status>
잔여 {enableLockerCount} / 전체 {totalLockerCount}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ export const LockerPosition: React.FC<{ model?: Model.LockerLocation }> = observ
model ? (
<Box>
<Title>보유중인 사물함</Title>
{model.lockerLocationName} {model.lockerNumber}번 <br></br>
{model.lockerNumber} 번 <br></br>
마감기한 : {model.expireAt}
</Box>
) : null,

);
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ export const LocationCell: React.FC<{ model: Model.LockerLocation }> = observer(
const isSelected = computed(() => store.target?.id === model.id).get();

return (
<Cell key={id} onClick={handleClick} isActive={isActive} isMine={isMine} isSelected={isSelected}>
<Cell
key={id}
onClick={handleClick}
isActive={isActive}
isMine={isMine}
isSelected={isSelected}
>
<span className="absolute-center">{lockerNumber}</span>
</Cell>
);
Expand Down
10 changes: 3 additions & 7 deletions src/stores/AuthStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { makeAutoObservable } from 'mobx';

import { AuthRepoImpl as Repo } from './repositories/AuthRepo';

import { removeAuth, restoreAuth } from '@/configs/axios';
import { getRefresh, removeRefresh } from '@/configs/axios';

export class AuthStore {
rootStore: Store.Root;
Expand All @@ -26,23 +26,19 @@ export class AuthStore {
}

*checkToken(): Generator {
//Token 존재 확인
if (!restoreAuth()) return { success: false };
//Token 유효성 확인
try {
this.me = (yield Repo.findCurrentUser()) as Model.User;
return { success: true };
} catch (err) {
removeAuth();
return err;
}
}

signOut(): void {
removeAuth();
removeRefresh();
}

get isSignIn(): boolean {
return restoreAuth();
return getRefresh() ? true : false;
}
}
4 changes: 2 additions & 2 deletions src/stores/models/LockerLocationModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { action, makeObservable, observable } from 'mobx';
export class LockerLocationModel implements Locker.LocationDto {
id: string;
lockerNumber: number;
lockerLocationName: string;
//lockerLocationName: string;
updatedAt: string;
expireAt: string;
isActive: boolean;
Expand All @@ -12,7 +12,7 @@ export class LockerLocationModel implements Locker.LocationDto {
constructor(props: Locker.LocationDto) {
this.id = props.id;
this.lockerNumber = props.lockerNumber;
this.lockerLocationName = props.lockerLocationName;
//this.lockerLocationName = props.lockerLocationName;
this.updatedAt = props.updatedAt;
this.expireAt = props.expireAt;
this.isActive = props.isActive;
Expand Down
4 changes: 2 additions & 2 deletions src/stores/models/LockerModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import { PAGE_URL } from '@/configs/path';
export class LockerModel implements Locker.Dto {
id: string;
name: string;
description: string;
//description: string;
enableLockerCount: number;
totalLockerCount: number;

constructor(props: Locker.Dto) {
this.id = props.id;
this.name = props.name;
this.description = props.description;
//this.description = props.description;
this.enableLockerCount = props.enableLockerCount;
this.totalLockerCount = props.totalLockerCount;
}
Expand Down
15 changes: 10 additions & 5 deletions src/stores/repositories/AuthRepo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ import { AxiosResponse } from 'axios';

import { UserModel } from '../models/UserModel';

import { API, setAuth, storeAuth } from '@/configs/axios';
import { API, setAccess, storeRefresh, removeRefresh } from '@/configs/axios';

class AuthRepo {
URI = '/api/v1/users';

signIn = async (body: User.SignInRequestDto) => {
const { data: token } = (await API.post(`${this.URI}/sign-in`, body)) as AxiosResponse<string>;

storeAuth(true, token);
setAuth(token);
const {
data: { accessToken, refreshToken },
} = (await API.post(`${this.URI}/sign-in`, body)) as AxiosResponse<{
accessToken: string;
refreshToken: string;
}>;

setAccess(accessToken);
storeRefresh(refreshToken);
};

isDuplicatedEmail = async (email: string): Promise<boolean> => {
Expand Down
Loading