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

Use info logic/#82 #90

Closed
wants to merge 14 commits into from
Closed
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
9 changes: 9 additions & 0 deletions app/(sub-page)/my/floating-component-container.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import UserDeleteModal from '@/app/ui/user/user-info-navigator/user-delete-modal';

export default function FloatingComponentContainer() {
return (
<>
<UserDeleteModal />
</>
);
}
2 changes: 2 additions & 0 deletions app/(sub-page)/my/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ContentContainer from '@/app/ui/view/atom/content-container';
import Drawer from '@/app/ui/view/molecule/drawer/drawer';
import { DIALOG_KEY } from '@/app/utils/key/dialog.key';
import { Suspense } from 'react';
import FloatingComponentContainer from './floating-component-container';

export default function MyPage() {
return (
Expand All @@ -22,6 +23,7 @@ export default function MyPage() {
<Drawer drawerKey={DIALOG_KEY.LECTURE_SEARCH}>
<LectureSearch />
</Drawer>
<FloatingComponentContainer />
</>
);
}
21 changes: 21 additions & 0 deletions app/__test__/ui/user/user-info-navigator.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import '@testing-library/jest-dom';
import UserInfoNavigator from '@/app/ui/user/user-info-navigator/user-info-navigator';
import { render, screen } from '@testing-library/react';

jest.mock('next/headers', () => ({
cookies: jest.fn().mockReturnValue({
get: jest.fn().mockReturnValue({
value: 'fake-access-token',
}),
}),
}));

describe('UserInfoNavigator', () => {
it('UserInfoNavigator๋ฅผ ๋ Œ๋”๋งํ•œ๋‹ค.', async () => {
render(await UserInfoNavigator());

expect(await screen.findByText(/๋ชจํ‚น์ด/i)).toBeInTheDocument();
expect(await screen.findByText(/์œตํ•ฉ์†Œํ”„ํŠธ์›จ์–ด/i)).toBeInTheDocument();
expect(await screen.findByText(/60000000/i)).toBeInTheDocument();
});
});
49 changes: 48 additions & 1 deletion app/business/user/user.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { FormState } from '@/app/ui/view/molecule/form/form-root';
import { API_PATH } from '../api-path';
import { SignUpRequestBody, SignInRequestBody, ValidateTokenResponse } from './user.type';
import { SignUpRequestBody, SignInRequestBody, ValidateTokenResponse, UserDeleteRequestBody } from './user.type';
import { httpErrorHandler } from '@/app/utils/http/http-error-handler';
import { BadRequestError } from '@/app/utils/http/http-error';
import {
Expand All @@ -15,6 +15,53 @@ import { cookies } from 'next/headers';
import { isValidation } from '@/app/utils/zod/validation.util';
import { redirect } from 'next/navigation';

export async function signOut() {
cookies().delete('accessToken');
cookies().delete('refreshToken');

redirect('/sign-in');
}

export async function deleteUser(prevState: FormState, formData: FormData): Promise<FormState> {
try {
const body: UserDeleteRequestBody = {
password: formData.get('password') as string,
};

const response = await fetch(`${API_PATH.user}/delete-me`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${cookies().get('accessToken')?.value}`,
},
body: JSON.stringify(body),
});
const result = await response.json();

httpErrorHandler(response, result);
} catch (error) {
if (error instanceof BadRequestError) {
// ์ž˜๋ชป๋œ ์š”์ฒญ ์ฒ˜๋ฆฌ ๋กœ์ง
return {
isSuccess: false,
isFailure: true,
validationError: {},
message: error.message,
};
} else {
// ๋‚˜๋จธ์ง€ ์—๋Ÿฌ๋Š” ๋” ์ƒ์œ„ ์ˆ˜์ค€์—์„œ ์ฒ˜๋ฆฌ
throw error;
}
}

return {
isSuccess: true,
isFailure: false,
validationError: {},
message: 'ํšŒ์› ํƒˆํ‡ด๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.',
};
}

export async function validateToken(): Promise<ValidateTokenResponse | false> {
const accessToken = cookies().get('accessToken')?.value;
const refreshToken = cookies().get('refreshToken')?.value;
Expand Down
4 changes: 4 additions & 0 deletions app/business/user/user.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export interface SignInRequestBody {
password: string;
}

export interface UserDeleteRequestBody {
password: string;
}

export type SignInResponse = z.infer<typeof SignInResponseSchema>;

export type UserInfoResponse = z.infer<typeof UserInfoResponseSchema>;
Expand Down
13 changes: 11 additions & 2 deletions app/mocks/db.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type MockDatabaseAction = {
createUser: (user: SignUpRequestBody) => boolean;
signIn: (userData: SignInRequestBody) => boolean;
getUserInfo: (authId: string) => UserInfoResponse;
deleteUser: (authId: string, password: string) => boolean;
};

export const mockDatabase: MockDatabaseAction = {
Expand Down Expand Up @@ -66,7 +67,7 @@ export const mockDatabase: MockDatabaseAction = {
{
...user,
isSumbitted: false,
major: '์œต์†Œ์ž…๋‹ˆ๋‹ค',
major: '์œตํ•ฉ์†Œํ”„ํŠธ์›จ์–ด',
name: '๋ชจํ‚น์ด2',
},
];
Expand All @@ -93,6 +94,14 @@ export const mockDatabase: MockDatabaseAction = {
isSumbitted: user.isSumbitted,
};
},
deleteUser: (authId: string, password: string) => {
const user = mockDatabaseStore.users.find((u) => u.authId === authId && u.password === password);
if (user) {
mockDatabaseStore.users = mockDatabaseStore.users.filter((u) => u.authId !== authId);
return true;
}
return false;
},
};

const initialState: MockDatabaseState = {
Expand All @@ -105,7 +114,7 @@ const initialState: MockDatabaseState = {
studentNumber: '60000000',
engLv: 'ENG12',
isSumbitted: false,
major: '์œต์†Œ์ž…๋‹ˆ๋‹ค',
major: '์œตํ•ฉ์†Œํ”„ํŠธ์›จ์–ด',
name: '๋ชจํ‚น์ด',
},
],
Expand Down
49 changes: 41 additions & 8 deletions app/mocks/handlers/user-handler.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import {
SignInResponse,
ValidateTokenResponse,
UserInfoResponse,
UserDeleteRequestBody,
} from '@/app/business/user/user.type';
import { ErrorResponseData } from '@/app/utils/http/http-error-handler';
import { StrictRequest } from 'msw';

function mockDecryptToken(token: string) {
if (token === 'fake-access-token') {
Expand All @@ -21,6 +23,21 @@ function mockDecryptToken(token: string) {
};
}

export const devModeAuthGuard = (request: StrictRequest<any>) => {
if (process.env.NODE_ENV === 'development') {
const accessToken = request.headers.get('Authorization')?.replace('Bearer ', '');
if (accessToken === 'undefined' || !accessToken) {
throw new Error('Unauthorized');
}

return mockDecryptToken(accessToken);
} else {
return {
authId: 'admin',
};
Comment on lines +35 to +37
Copy link
Member

Choose a reason for hiding this comment

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

๊ฐœ๋ฐœ ๋ชจ๋“œ๊ฐ€ ์•„๋‹๋•Œ๋Š”

 return {
    authId: '',
  };

์„ ๋ฐ˜ํ™˜ํ•ด์•ผํ•˜๋Š” ๊ฒƒ ์•„๋‹Œ๊ฐ€์š”?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

  • ๋จผ์ €, ๊ธฐ์กด์˜ mock ๋กœ์ง์„ ํ™œ์šฉํ•˜๋ ค๋ฉด authId๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๊ฐœ๋ฐœ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ํ…Œ์ŠคํŠธ ์ƒํ™ฉ์—์„œ๋Š” admin ๊ณ„์ •์œผ๋กœ ์ง„ํ–‰ํ•œ๋‹ค๋Š” ๊ฐ€์ • ํ•˜์— ์ด๋ฅผ ๊ตฌ์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค.

}
};

export const userHandlers = [
http.get<never, never, never>(`${API_PATH.auth}/failure`, async ({ request }) => {
await delay(500);
Expand All @@ -31,20 +48,36 @@ export const userHandlers = [
accessToken: 'fake-access-token',
});
}),
http.get<never, never, UserInfoResponse | ErrorResponseData>(`${API_PATH.user}`, async ({ request }) => {
const accessToken = request.headers.get('Authorization')?.replace('Bearer ', '');
if (accessToken === 'undefined' || !accessToken) {
http.delete<never, UserDeleteRequestBody, never>(`${API_PATH.user}/delete-me`, async ({ request }) => {
try {
const { authId } = devModeAuthGuard(request);
const { password } = await request.json();

const result = mockDatabase.deleteUser(authId, password);

if (result) {
return HttpResponse.json({ status: 200 });
} else {
return HttpResponse.json({ status: 400, message: '๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค' }, { status: 400 });
}
} catch {
return HttpResponse.json({ status: 401, message: 'Unauthorized' }, { status: 401 });
}
}),
http.get<never, never, UserInfoResponse | ErrorResponseData>(`${API_PATH.user}`, async ({ request }) => {
try {
const { authId } = devModeAuthGuard(request);
const userInfo = mockDatabase.getUserInfo(authId);
await delay(3000);

const userInfo = mockDatabase.getUserInfo(mockDecryptToken(accessToken).authId);
await delay(3000);
if (!userInfo) {
return HttpResponse.json({ status: 401, message: 'Unauthorized' }, { status: 401 });
}

if (!userInfo) {
return HttpResponse.json(userInfo);
} catch {
return HttpResponse.json({ status: 401, message: 'Unauthorized' }, { status: 401 });
}

return HttpResponse.json(userInfo);
}),
http.post<never, SignUpRequestBody, never>(`${API_PATH.user}/sign-up`, async ({ request }) => {
const userData = await request.json();
Expand Down
1 change: 1 addition & 0 deletions app/store/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const initialState = {
[DIALOG_KEY.RESULT_CATEGORY]: false,
[DIALOG_KEY.DIALOG_TEST]: true,
[DIALOG_KEY.LECTURE_SEARCH]: false,
[DIALOG_KEY.USER_DEELETE]: false,
};

const dialogAtom = atom(initialState);
Expand Down
11 changes: 11 additions & 0 deletions app/ui/user/user-info-navigator/sign-out-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use client';
import { signOut } from '@/app/business/user/user.command';
import Button from '../../view/atom/button/button';

export default function SignOutButton() {
const handleSignOut = async () => {
await signOut();
};

return <Button onClick={handleSignOut} size="sm" variant="secondary" label="๋กœ๊ทธ์•„์›ƒ" />;
}
14 changes: 14 additions & 0 deletions app/ui/user/user-info-navigator/user-delete-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use client';
import Button from '../../view/atom/button/button';
import { DIALOG_KEY } from '@/app/utils/key/dialog.key';
import useDialog from '@/app/hooks/useDialog';

export default function UserDeleteButton() {
const { toggle } = useDialog(DIALOG_KEY.USER_DEELETE);

const handleModalToggle = () => {
toggle();
};

return <Button onClick={handleModalToggle} size="sm" variant="text" label="ํšŒ์›ํƒˆํ‡ดํ•˜๊ธฐ" />;
}
26 changes: 26 additions & 0 deletions app/ui/user/user-info-navigator/user-delete-modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use client';
import { DIALOG_KEY } from '@/app/utils/key/dialog.key';
import Modal from '../../view/molecule/modal/modal';
import Form from '../../view/molecule/form';
import { deleteUser } from '@/app/business/user/user.command';

export default function UserDeleteModal() {
return (
<Modal modalKey={DIALOG_KEY.USER_DEELETE}>
<div className="max-w-sm mx-auto my-12 p-6 border rounded-lg shadow-md bg-white">
<h2 className="text-xl font-bold text-center">ํšŒ์› ํƒˆํ‡ด</h2>
<div className="h-1 w-10 bg-blue-600 mx-auto my-3" />
<p className="text-sm text-center my-4">
ํšŒ์›ํƒˆํ‡ด๋ฅผ ์ง„ํ–‰ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? ํƒˆํ‡ด๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด๋” ๋น„๋ฐ€๋ฒˆํ˜ธ ์ž…๋ ฅ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.
</p>
<div className="my-4">
<Form failMessageControl={'toast'} action={deleteUser} id={'user-delete'}>
<Form.PasswordInput label="๋น„๋ฐ€๋ฒˆํ˜ธ" id="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" required={true} />
<Form.SubmitButton label="ํƒˆํ‡ดํ•˜๊ธฐ" position="center" variant="primary" />
</Form>
</div>
<p className="text-xs text-center my-4">์ •๋ณด๋ฅผ ๋ˆ„๋ฝํ•˜์—ฌ ์„œ๋น„์Šค๋ฅผ ์ด์šฉํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.</p>
</div>
</Modal>
);
}
6 changes: 4 additions & 2 deletions app/ui/user/user-info-navigator/user-info-navigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import Avatar from '../../view/atom/avatar/avatar';
import Button from '../../view/atom/button/button';
import { getUserInfo } from '@/app/business/user/user.query';
import Skeleton from '../../view/atom/skeleton';
import SignOutButton from './sign-out-button';
import UserDeleteButton from './user-delete-button';

export default async function UserInfoNavigator() {
const userInfo = await getUserInfo();
Expand All @@ -18,10 +20,10 @@ export default async function UserInfoNavigator() {
<div className="text-sm text-gray-400">{userInfo.studentNumber}</div>

<div className="mt-9">
<Button size="sm" variant="secondary" label="๋กœ๊ทธ์•„์›ƒ" />
<SignOutButton />
</div>
<div className="mt-2">
<Button size="sm" variant="text" label="ํšŒ์›ํƒˆํ‡ดํ•˜๊ธฐ" />
<UserDeleteButton />
</div>
</div>
);
Expand Down
1 change: 1 addition & 0 deletions app/utils/key/dialog.key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const DIALOG_KEY = {
RESULT_CATEGORY: 'RESULT_CATEGORY',
DIALOG_TEST: 'DIALOG_TEST',
LECTURE_SEARCH: 'LECTURE_SEARCH',
USER_DEELETE: 'USER_DEELETE',
} as const;

export type DialogKey = (typeof DIALOG_KEY)[keyof typeof DIALOG_KEY];
12 changes: 9 additions & 3 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ async function getAuth(request: NextRequest): Promise<{
};
}

const allowdGuestPath = ['/tutorial', '/sign-in', '/sign-up', '/find-password', '/find-id'];
const allowdOnlyGuestPath = ['/sign-in', '/sign-up', '/find-password', '/find-id'];
const allowdGuestPath = ['/', '/tutorial', ...allowdOnlyGuestPath];

function isAllowedGuestPath(path: string) {
return allowdGuestPath.some((allowedPath) => path.startsWith(allowedPath));
function isAllowedGuestPath(path: string, strict: boolean = false) {
const allowdPath = strict ? allowdOnlyGuestPath : allowdGuestPath;
return allowdPath.some((allowedPath) => path.startsWith(allowedPath));
}

export async function middleware(request: NextRequest) {
Expand All @@ -51,6 +53,10 @@ export async function middleware(request: NextRequest) {
if (auth.role === 'guest' && !isAllowedGuestPath(request.nextUrl.pathname)) {
return Response.redirect(new URL('/sign-in', request.url));
}

if (auth.role !== 'guest' && isAllowedGuestPath(request.nextUrl.pathname, true)) {
return Response.redirect(new URL('/my', request.url));
}
}
}

Expand Down
Loading