diff --git a/.env b/.env new file mode 100644 index 0000000..b5bf32a --- /dev/null +++ b/.env @@ -0,0 +1,8 @@ +# Azure AD Configuration +VITE_AZURE_CLIENT_ID=d182d8e3-fa47-4b93-a736-8c4b7c25bc97 +VITE_AZURE_AUTHORITY=https://login.microsoftonline.com/common/oauth2/v2.0/authorize +VITE_AZURE_REDIRECT_URI=http://localhost:5173 +VITE_AZURE_POST_LOGOUT_REDIRECT_URI=http://localhost:5173 + +# API Configuration +VITE_API_BASE_URL=https://wiki.dahyeon.us/v1 \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b72c164 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# Azure AD Configuration +VITE_AZURE_CLIENT_ID=your-client-id-here +VITE_AZURE_AUTHORITY=https://login.microsoftonline.com/your-tenant-id-here +VITE_AZURE_REDIRECT_URI=http://localhost:5173 +VITE_AZURE_POST_LOGOUT_REDIRECT_URI=http://localhost:5173 + +# API Configuration +VITE_API_BASE_URL=https://wiki.dahyeon.us/v1 diff --git a/AUTHENTICATION_SETUP.md b/AUTHENTICATION_SETUP.md new file mode 100644 index 0000000..d3627b4 --- /dev/null +++ b/AUTHENTICATION_SETUP.md @@ -0,0 +1,179 @@ +# Azure Entra ID 인증 설정 가이드 + +이 문서는 Gem Wiki에 Azure Entra ID (구 Azure AD) OIDC 인증을 설정하는 방법을 설명합니다. + +## 1. Azure Portal에서 앱 등록 + +### 1.1 Azure Portal 접속 +1. [Azure Portal](https://portal.azure.com)에 로그인합니다. +2. "Azure Active Directory" (또는 "Microsoft Entra ID")로 이동합니다. +3. "앱 등록" 메뉴를 선택합니다. + +### 1.2 새 앱 등록 +1. **새 등록** 버튼을 클릭합니다. +2. 다음 정보를 입력합니다: + - **이름**: `Gem Wiki` (또는 원하는 이름) + - **지원되는 계정 유형**: 조직의 요구사항에 맞게 선택 + - **리디렉션 URI**: + - 플랫폼: `단일 페이지 애플리케이션(SPA)` + - URI: `http://localhost:5173` (개발용) + - 프로덕션: `https://wiki.dahyeon.us` + +### 1.3 필요한 정보 수집 +앱 등록 후, 다음 정보를 메모합니다: +- **Application (client) ID** (예: `12345678-1234-1234-1234-123456789abc`) +- **Directory (tenant) ID** (예: `87654321-4321-4321-4321-cba987654321`) + +### 1.4 API 권한 설정 +1. "API 권한" 메뉴로 이동합니다. +2. 기본적으로 `User.Read` 권한이 추가되어 있습니다. +3. 추가 권한이 필요한 경우 **권한 추가** 버튼을 클릭합니다. + +### 1.5 인증 설정 +1. "인증" 메뉴로 이동합니다. +2. **암시적 허용 및 하이브리드 흐름**에서: + - ✅ "액세스 토큰" 체크 + - ✅ "ID 토큰" 체크 +3. **고급 설정**에서: + - ✅ "공용 클라이언트 흐름 허용" 체크 (선택사항) + +## 2. 환경 변수 설정 + +프로젝트 루트에 `.env` 파일을 생성하고 다음 내용을 추가합니다: + +```env +# Azure AD Configuration +VITE_AZURE_CLIENT_ID=your-client-id-here +VITE_AZURE_AUTHORITY=https://login.microsoftonline.com/your-tenant-id-here +VITE_AZURE_REDIRECT_URI=http://localhost:5173 +VITE_AZURE_POST_LOGOUT_REDIRECT_URI=http://localhost:5173 + +# API Configuration +VITE_API_BASE_URL=https://wiki.dahyeon.us/v1 +``` + +**프로덕션 환경:** +```env +VITE_AZURE_CLIENT_ID=your-client-id-here +VITE_AZURE_AUTHORITY=https://login.microsoftonline.com/your-tenant-id-here +VITE_AZURE_REDIRECT_URI=https://wiki.dahyeon.us +VITE_AZURE_POST_LOGOUT_REDIRECT_URI=https://wiki.dahyeon.us +VITE_API_BASE_URL=https://wiki.dahyeon.us/v1 +``` + +## 3. 백엔드 API 설정 + +백엔드 API에서 JWT 토큰을 검증하도록 설정해야 합니다. + +### 3.1 JWT 검증 설정 +백엔드에서 다음을 확인해야 합니다: +- **Issuer**: `https://login.microsoftonline.com/{tenant-id}/v2.0` +- **Audience**: Azure Portal에서 설정한 Application (client) ID +- **JWKS URI**: `https://login.microsoftonline.com/{tenant-id}/discovery/v2.0/keys` + +### 3.2 API 엔드포인트 +서버 API는 다음과 같은 엔드포인트를 제공해야 합니다: +- `GET /v1/pages` - 모든 페이지 조회 +- `GET /v1/pages/:id` - 특정 페이지 조회 +- `POST /v1/pages` - 새 페이지 생성 +- `PUT /v1/pages/:id` - 페이지 업데이트 +- `DELETE /v1/pages/:id` - 페이지 삭제 + +모든 요청은 `Authorization: Bearer {token}` 헤더를 포함해야 합니다. + +## 4. 코드에서 인증 사용하기 + +### 4.1 컴포넌트에서 인증 상태 확인 +```typescript +import { useMsal } from '@azure/msal-react'; + +function MyComponent() { + const { accounts } = useMsal(); + const isAuthenticated = accounts.length > 0; + + if (!isAuthenticated) { + return
로그인이 필요합니다.
; + } + + return
환영합니다, {accounts[0].name}!
; +} +``` + +### 4.2 API 호출 시 인증 토큰 사용 +```typescript +import { useAuthenticatedApi } from '../shared/hooks/useAuthenticatedApi'; + +function MyComponent() { + const { authenticatedFetch } = useAuthenticatedApi(); + + const fetchData = async () => { + const response = await authenticatedFetch('https://wiki.dahyeon.us/v1/pages'); + const data = await response.json(); + return data; + }; + + // 사용 예시 +} +``` + +### 4.3 서버 API 파일 사용 +실제 서버와 통합하려면 `src/entities/page/api.ts`를 `api.server.ts`로 교체하거나, +조건부로 사용하도록 설정합니다: + +```typescript +// src/entities/page/index.ts +export * from './types'; + +// 개발/프로덕션 환경에 따라 다른 API 사용 +if (import.meta.env.PROD) { + export * from './api.server'; // 실제 서버 API +} else { + export * from './api'; // Mock API +} +``` + +## 5. 개발 서버 실행 + +```bash +npm run dev +``` + +브라우저에서 `http://localhost:5173`으로 접속하면 상단 우측에 "로그인" 버튼이 표시됩니다. + +## 6. 문제 해결 + +### 로그인 팝업이 차단되는 경우 +- 브라우저의 팝업 차단 설정을 확인하세요. +- 리다이렉트 방식으로 변경하려면 `AuthButton.tsx`에서 `loginPopup` 대신 `loginRedirect`를 사용하세요. + +### CORS 오류가 발생하는 경우 +- 백엔드 API에서 CORS 설정을 확인하세요. +- `Access-Control-Allow-Origin` 헤더가 올바르게 설정되어 있는지 확인하세요. + +### 토큰이 만료된 경우 +- MSAL은 자동으로 토큰을 갱신합니다. +- `acquireTokenSilent` 메서드가 실패하면 자동으로 팝업을 통해 재인증합니다. + +## 7. 보안 권장사항 + +1. **환경 변수 보안** + - `.env` 파일을 `.gitignore`에 추가하세요. + - 프로덕션 환경에서는 환경 변수를 안전하게 관리하세요. + +2. **토큰 저장** + - 현재 설정은 `sessionStorage`를 사용합니다. + - 더 안전한 저장이 필요한 경우 설정을 변경할 수 있습니다. + +3. **API 검증** + - 백엔드에서 모든 요청의 JWT 토큰을 검증해야 합니다. + - 토큰의 만료 시간, issuer, audience를 확인하세요. + +4. **HTTPS 사용** + - 프로덕션에서는 항상 HTTPS를 사용하세요. + - 개발 환경에서도 가능하면 HTTPS를 사용하세요. + +## 참고 자료 + +- [Azure AD 문서](https://docs.microsoft.com/azure/active-directory/) +- [MSAL.js 문서](https://github.com/AzureAD/microsoft-authentication-library-for-js) +- [React용 MSAL 가이드](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-react) diff --git a/package-lock.json b/package-lock.json index a71ea9a..652cc16 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,8 @@ "name": "wiki", "version": "0.0.0", "dependencies": { + "@azure/msal-browser": "^3.30.0", + "@azure/msal-react": "^2.1.3", "@lexical/code": "^0.38.2", "@lexical/link": "^0.38.2", "@lexical/list": "^0.38.2", @@ -61,6 +63,40 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@azure/msal-browser": { + "version": "3.30.0", + "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-3.30.0.tgz", + "integrity": "sha512-I0XlIGVdM4E9kYP5eTjgW8fgATdzwxJvQ6bm2PNiHaZhEuUz47NYw1xHthC9R+lXz4i9zbShS0VdLyxd7n0GGA==", + "license": "MIT", + "dependencies": { + "@azure/msal-common": "14.16.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-common": { + "version": "14.16.1", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-14.16.1.tgz", + "integrity": "sha512-nyxsA6NA4SVKh5YyRpbSXiMr7oQbwark7JU9LMeg6tJYTSPyAGkdx61wPT4gyxZfxlSxMMEyAsWaubBlNyIa1w==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-react": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@azure/msal-react/-/msal-react-2.2.0.tgz", + "integrity": "sha512-2V+9JXeXyyjYNF92y5u0tU4el9px/V1+vkRuN+DtoxyiMHCtYQpJoaFdGWArh43zhz5aqQqiGW/iajPDSu3QsQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@azure/msal-browser": "^3.27.0", + "react": "^16.8.0 || ^17 || ^18" + } + }, "node_modules/@babel/code-frame": { "version": "7.27.1", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", @@ -92,7 +128,6 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -2539,7 +2574,6 @@ "integrity": "sha512-qzQZRBqkFsYyaSWXuEHc2WR9c0a0CXwiE5FWUvn7ZM+vdy1uZLfCunD38UzhuB7YN/J11ndbDBcTmOdxJo9Q7A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -2554,9 +2588,8 @@ "version": "19.2.2", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz", "integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==", - "devOptional": true, + "dev": true, "license": "MIT", - "peer": true, "dependencies": { "csstype": "^3.0.2" } @@ -2565,9 +2598,8 @@ "version": "19.2.2", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.2.tgz", "integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==", - "devOptional": true, + "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "@types/react": "^19.2.0" } @@ -2618,7 +2650,6 @@ "integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.46.3", "@typescript-eslint/types": "8.46.3", @@ -2871,7 +2902,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -3050,7 +3080,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.19", "caniuse-lite": "^1.0.30001751", @@ -3175,7 +3204,7 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", - "devOptional": true, + "dev": true, "license": "MIT" }, "node_modules/debug": { @@ -3311,7 +3340,6 @@ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -3783,16 +3811,6 @@ "dev": true, "license": "ISC" }, - "node_modules/isomorphic.js": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", - "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", - "license": "MIT", - "funding": { - "type": "GitHub Sponsors ❤", - "url": "https://github.com/sponsors/dmonad" - } - }, "node_modules/jiti": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", @@ -3900,27 +3918,6 @@ "integrity": "sha512-JJmfsG3c4gwBHzUGffbV7ifMNkKAWMCnYE3xJl87gty7hjyV5f3xq7eqTjP5HFYvO4XpjJvvWO2/djHp5S10tw==", "license": "MIT" }, - "node_modules/lib0": { - "version": "0.2.114", - "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.114.tgz", - "integrity": "sha512-gcxmNFzA4hv8UYi8j43uPlQ7CGcyMJ2KQb5kZASw6SnAKAf10hK12i2fjrS3Cl/ugZa5Ui6WwIu1/6MIXiHttQ==", - "license": "MIT", - "dependencies": { - "isomorphic.js": "^0.2.4" - }, - "bin": { - "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", - "0gentesthtml": "bin/gentesthtml.js", - "0serve": "bin/0serve.js" - }, - "engines": { - "node": ">=16" - }, - "funding": { - "type": "GitHub Sponsors ❤", - "url": "https://github.com/sponsors/dmonad" - } - }, "node_modules/lightningcss": { "version": "1.30.2", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz", @@ -4435,7 +4432,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -4507,7 +4503,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz", "integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -4517,7 +4512,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz", "integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -4890,7 +4884,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -4949,7 +4942,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -5079,7 +5071,6 @@ "integrity": "sha512-qTl3VF7BvOupTR85Zc561sPEgxyUSNSvTQ9fit7DEMP7yPgvvIGm5Zfa1dOM+kOwWGNviK9uFM9ra77+OjK7lQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", @@ -5173,7 +5164,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -5214,24 +5204,6 @@ "dev": true, "license": "ISC" }, - "node_modules/yjs": { - "version": "13.6.27", - "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.27.tgz", - "integrity": "sha512-OIDwaflOaq4wC6YlPBy2L6ceKeKuF7DeTxx+jPzv1FHn9tCZ0ZwSRnUBxD05E3yed46fv/FWJbvR+Ud7x0L7zw==", - "license": "MIT", - "peer": true, - "dependencies": { - "lib0": "^0.2.99" - }, - "engines": { - "node": ">=16.0.0", - "npm": ">=8.0.0" - }, - "funding": { - "type": "GitHub Sponsors ❤", - "url": "https://github.com/sponsors/dmonad" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index 617de79..3d35599 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,8 @@ "preview": "vite preview" }, "dependencies": { + "@azure/msal-browser": "^3.30.0", + "@azure/msal-react": "^2.1.3", "@lexical/code": "^0.38.2", "@lexical/link": "^0.38.2", "@lexical/list": "^0.38.2", diff --git a/src/app/App.tsx b/src/app/App.tsx index 5f9bc0b..1c27c94 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -1,5 +1,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; +import { MsalProvider } from '@azure/msal-react'; +import { PublicClientApplication } from '@azure/msal-browser'; +import { msalConfig } from '../config/authConfig'; import { PageListPage, PageDetailPage, PageEditPage } from '../pages'; const queryClient = new QueryClient({ @@ -11,18 +14,23 @@ const queryClient = new QueryClient({ }, }); +// MSAL instance +const msalInstance = new PublicClientApplication(msalConfig); + function App() { return ( - - - - } /> - } /> - } /> - } /> - - - + + + + + } /> + } /> + } /> + } /> + + + + ); } diff --git a/src/config/authConfig.ts b/src/config/authConfig.ts new file mode 100644 index 0000000..6d57b23 --- /dev/null +++ b/src/config/authConfig.ts @@ -0,0 +1,60 @@ +import { LogLevel } from '@azure/msal-browser'; +import type { Configuration } from '@azure/msal-browser'; + +/** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL.js configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md + */ +export const msalConfig: Configuration = { + auth: { + clientId: import.meta.env.VITE_AZURE_CLIENT_ID || '', // Azure AD App Registration의 Application (client) ID + authority: import.meta.env.VITE_AZURE_AUTHORITY || '', // 예: https://login.microsoftonline.com/{tenant-id} + redirectUri: import.meta.env.VITE_AZURE_REDIRECT_URI || window.location.origin, // 리다이렉트 URI + postLogoutRedirectUri: import.meta.env.VITE_AZURE_POST_LOGOUT_REDIRECT_URI || window.location.origin, + }, + cache: { + cacheLocation: 'sessionStorage', // "sessionStorage" 또는 "localStorage" 중 선택 + storeAuthStateInCookie: false, // IE11/Edge를 지원하려면 true로 설정 + }, + system: { + loggerOptions: { + loggerCallback: (level, message, containsPii) => { + if (containsPii) { + return; + } + switch (level) { + case LogLevel.Error: + console.error(message); + return; + case LogLevel.Info: + console.info(message); + return; + case LogLevel.Verbose: + console.debug(message); + return; + case LogLevel.Warning: + console.warn(message); + return; + } + }, + }, + }, +}; + +/** + * Scopes you add here will be prompted for user consent during sign-in. + * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request. + * For more information about OIDC scopes, visit: + * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes + */ +export const loginRequest = { + scopes: ['User.Read'], // Microsoft Graph API에서 사용자 프로필 읽기 +}; + +/** + * API 호출을 위한 스코프 + */ +export const apiRequest = { + scopes: [`api://${import.meta.env.VITE_AZURE_CLIENT_ID}/.default`], +}; diff --git a/src/entities/page/api.server.ts b/src/entities/page/api.server.ts new file mode 100644 index 0000000..057d5aa --- /dev/null +++ b/src/entities/page/api.server.ts @@ -0,0 +1,91 @@ +import type { Page, CreatePageData, UpdatePageData } from './types'; + +const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'https://wiki.dahyeon.us/v1'; + +/** + * 인증 헤더를 생성합니다. + * MSAL을 통해 얻은 토큰을 사용합니다. + */ +function getAuthHeaders(token?: string): HeadersInit { + const headers: HeadersInit = { + 'Content-Type': 'application/json', + }; + + if (token) { + headers['Authorization'] = `Bearer ${token}`; + } + + return headers; +} + +/** + * API 에러 처리 + */ +async function handleResponse(response: Response): Promise { + if (!response.ok) { + const error = await response.json().catch(() => ({ message: 'Unknown error' })); + throw new Error(error.message || `HTTP error! status: ${response.status}`); + } + return response.json(); +} + +/** + * 모든 페이지 조회 + */ +export async function getPages(token?: string): Promise { + const response = await fetch(`${API_BASE_URL}/pages`, { + method: 'GET', + headers: getAuthHeaders(token), + }); + return handleResponse(response); +} + +/** + * 특정 페이지 조회 + */ +export async function getPage(id: string, token?: string): Promise { + const response = await fetch(`${API_BASE_URL}/pages/${id}`, { + method: 'GET', + headers: getAuthHeaders(token), + }); + return handleResponse(response); +} + +/** + * 새 페이지 생성 + */ +export async function createPage(data: CreatePageData, token?: string): Promise { + const response = await fetch(`${API_BASE_URL}/pages`, { + method: 'POST', + headers: getAuthHeaders(token), + body: JSON.stringify(data), + }); + return handleResponse(response); +} + +/** + * 페이지 업데이트 + */ +export async function updatePage(id: string, data: UpdatePageData, token?: string): Promise { + const response = await fetch(`${API_BASE_URL}/pages/${id}`, { + method: 'PUT', + headers: getAuthHeaders(token), + body: JSON.stringify(data), + }); + return handleResponse(response); +} + +/** + * 페이지 삭제 + */ +export async function deletePage(id: string, token?: string): Promise { + const response = await fetch(`${API_BASE_URL}/pages/${id}`, { + method: 'DELETE', + headers: getAuthHeaders(token), + }); + + if (!response.ok) { + const error = await response.json().catch(() => ({ message: 'Unknown error' })); + throw new Error(error.message || `HTTP error! status: ${response.status}`); + } +} diff --git a/src/shared/AuthButton.tsx b/src/shared/AuthButton.tsx new file mode 100644 index 0000000..65c5ce2 --- /dev/null +++ b/src/shared/AuthButton.tsx @@ -0,0 +1,66 @@ +import { useMsal } from '@azure/msal-react'; +import { useState } from 'react'; +import { loginRequest } from '../config/authConfig'; +import { PersonIcon, ExitIcon } from '@radix-ui/react-icons'; + +export function AuthButton() { + const { instance, accounts } = useMsal(); + const [isLoading, setIsLoading] = useState(false); + + const handleLogin = async () => { + setIsLoading(true); + try { + await instance.loginPopup(loginRequest); + } catch (error) { + console.error('Login failed:', error); + } finally { + setIsLoading(false); + } + }; + + const handleLogout = async () => { + setIsLoading(true); + try { + await instance.logoutPopup({ + postLogoutRedirectUri: '/', + mainWindowRedirectUri: '/', + }); + } catch (error) { + console.error('Logout failed:', error); + } finally { + setIsLoading(false); + } + }; + + const isAuthenticated = accounts.length > 0; + const userName = accounts[0]?.username || accounts[0]?.name || 'User'; + + if (isAuthenticated) { + return ( +
+
+ + {userName} +
+ +
+ ); + } + + return ( + + ); +} diff --git a/src/shared/Layout.tsx b/src/shared/Layout.tsx index 2551485..e3d5ee3 100644 --- a/src/shared/Layout.tsx +++ b/src/shared/Layout.tsx @@ -3,6 +3,7 @@ import { useState } from 'react'; import { Link } from 'react-router-dom'; import { HamburgerMenuIcon, Cross1Icon } from '@radix-ui/react-icons'; import { LeftSidebar } from './LeftSidebar'; +import { AuthButton } from './AuthButton'; interface LayoutProps { children: ReactNode; @@ -47,13 +48,14 @@ export function Layout({ children, showSidebar = true, rightSidebar }: LayoutPro Gem Wiki (잼위키) -