Compare commits
23 Commits
776a2930f5
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 74f16f2f02 | |||
| 5f41995c84 | |||
| 5590cc657f | |||
| 57280a4b61 | |||
| 1a70cbbad9 | |||
| c2a26af0dc | |||
| cbd0a559e9 | |||
| 69939f8d2b | |||
| 8ce438d0b2 | |||
| 4bfa2af213 | |||
| 403682485d | |||
| c6cc7edfc7 | |||
| 43b4c4be54 | |||
| 8420a22e67 | |||
| e2cdf63e81 | |||
| a1f39c74de | |||
| d4747b0ea0 | |||
| 9e9fe45d03 | |||
| 0d6cdd1eaa | |||
| 6f1b7423ec | |||
| 642350bc6c | |||
| 86e7ce3e32 | |||
| a964dcbee3 |
@@ -13,10 +13,10 @@
|
|||||||
|
|
||||||
- New backend only; development front 4014/backend 4015/api/v1. Use published @kri/common HTTP and persistent hydratedAtom plus TanStack Query; do not add axios or duplicate common storage/auth helpers. Repository package.json and lockfile are authoritative for versions. Add dependencies only after user approval; preserve existing chart, drag-and-drop and registry integrations.
|
- New backend only; development front 4014/backend 4015/api/v1. Use published @kri/common HTTP and persistent hydratedAtom plus TanStack Query; do not add axios or duplicate common storage/auth helpers. Repository package.json and lockfile are authoritative for versions. Add dependencies only after user approval; preserve existing chart, drag-and-drop and registry integrations.
|
||||||
- Next stores the 24-hour token in an HttpOnly cookie and returns validated LoginUser only. Secure for ENV prod/production. Backend logout/session endpoints do not exist: Next logout clears its cookie, client auth and query cache. BFF accepts only fixed implemented project reads and whitelisted query fields; never trust browser role/id headers or send API keys to the browser.
|
- Next stores the 24-hour token in an HttpOnly cookie and returns validated LoginUser only. Secure for ENV prod/production. Backend logout/session endpoints do not exist: Next logout clears its cookie, client auth and query cache. BFF accepts only fixed implemented project reads and whitelisted query fields; never trust browser role/id headers or send API keys to the browser.
|
||||||
- Basic routes are /, /login, /logout and project pages without query parameters (/Report/Current, /Report/Quota, /Report/Tabulation, /Report/Crosstab, /Management/Derived, /Management/Exim). The selected project {projectType, pkey} lives in the user-scoped persistent atom `useSelectedProject` (localStorage, like legacy ptokenState); home, login and logout clear it, and old `?projectType=0|1&pkey=rawKey` links are stored and stripped. Preserve pkey case and use projectType+pkey in query keys and BFF paths, with current user id/role/team in query keys. Runtime-validate data, use existing UI components, retain raw server count/LOI semantics and display-only padded date cleanup. Keep loading/error/empty/retry states.
|
- Basic routes are /, /login, /logout and project pages without query parameters (/Report/Current, /Report/Quota, /Report/Tabulation, /Report/Crosstab, /Management/Derived, /Management/Exim). The selected project {projectType, pkey} lives in the user-scoped persistent atom `useSelectedProject` (localStorage, like legacy ptokenState); home, login and logout clear it. Address parameters never select a project: old `?projectType=0|1&pkey=rawKey` links are ignored, and sharing is only through generated Page Copy/URL Copy links. This is not access control; server project scope is authoritative. Preserve pkey case and use projectType+pkey in query keys and BFF paths, with current user id/role/team in query keys. Runtime-validate data, use existing UI components, retain raw server count/LOI semantics and display-only padded date cleanup. Keep loading/error/empty/retry states.
|
||||||
- Basic progress uses type/loi/day/screen; date filters affect type/loi/screen, never day, matching the server. Logging is a best-effort /log/visit call with server cookie identity, no /log/site HTTP.
|
- Basic progress uses type/loi/day/screen; date filters affect type/loi/screen, never day, matching the server. Logging is a best-effort /log/visit call with server cookie identity, no /log/site HTTP.
|
||||||
- The second migration phase is closed. Until the user explicitly announces launch, this application is unlaunched and old External token compatibility is unnecessary. The user performs every operation that writes to the shared database (live login, bookmark/derived saves, imports, share issuance and External login) and live Excel generation checks. No shared DB calls in local validation. Phase closure does not certify unexecuted live checks.
|
- The second migration phase is closed. Until the user explicitly announces launch, this application is unlaunched and old External token compatibility is unnecessary. The user performs every operation that writes to the shared database (live login, bookmark/derived saves, imports, share issuance and External login) and live Excel generation checks. No shared DB calls in local validation. Phase closure does not certify unexecuted live checks.
|
||||||
- ReportMember/URL Copy/Page Copy roles are 9001/9002/9003. External login replaces the prior identity; validate the server-returned user and link together. Keep the link's project and page scope, disable project-list/summary reads, and use the link title. Page Copy has no GNB menus; URL Copy has only the four report menus. Hide logo navigation, Logout, project selection, Copy and bookmark writes. Bookmark reads and aggregate/Quota Excel remain allowed; server scope enforcement is authoritative.
|
- ReportMember/URL Copy/Page Copy roles are 9001/9002/9003. External login replaces the prior identity; validate the server-returned user and link together. Keep the link's project and page scope, disable project-list/summary reads, and use the link title. Page Copy has no GNB menus; URL Copy has only the four report menus. Hide logo navigation, Logout, project selection, Copy and bookmark writes. Bookmark reads and aggregate/Quota Excel remain allowed; server scope enforcement is authoritative. Like legacy Main (isAdmin > 8 → Logout), an External user opening / goes to /logout and then /login; other out-of-scope paths return to the link's realUrl.
|
||||||
- Export/Import APIs intentionally have no ordinary-user role restriction. Their menu restriction (userRole === 1001 || userTeam === "R701") is temporary UX policy. Do not ask the server to add a role restriction; External access remains blocked by its interceptor.
|
- Export/Import APIs intentionally have no ordinary-user role restriction. Their menu restriction (userRole === 1001 || userTeam === "R701") is temporary UX policy. Do not ask the server to add a role restriction; External access remains blocked by its interceptor.
|
||||||
|
|
||||||
## KART report streaming UI
|
## KART report streaming UI
|
||||||
|
|||||||
3
.env
Normal file
3
.env
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
NEXT_PUBLIC_API_BASE=/api
|
||||||
|
NEXT_PUBLIC_STORE_KEY=kri-local-storage-key-32-bytes!!
|
||||||
|
NEXT_PUBLIC_STORE_IV=kri-local-iv-16!
|
||||||
4
.env.development
Normal file
4
.env.development
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
NEXT_PUBLIC_ENV=development
|
||||||
|
ENV=development
|
||||||
|
API_SERVER=http://127.0.0.1:4015/api/v1
|
||||||
|
AUTH_COOKIE_DOMAIN=kric.com
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# 모든 환경 공통
|
|
||||||
NEXT_PUBLIC_API_BASE=/api
|
|
||||||
NEXT_PUBLIC_STORE_KEY=change-this-storage-key-32-bytes
|
|
||||||
NEXT_PUBLIC_STORE_IV=change-this-iv-16
|
|
||||||
|
|
||||||
# 환경별 값 (.env.local / .env.development / .env.production)
|
|
||||||
NEXT_PUBLIC_ENV=local
|
|
||||||
ENV=local
|
|
||||||
API_SERVER=http://localhost:4015/api/v1
|
|
||||||
4
.env.local
Normal file
4
.env.local
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
NEXT_PUBLIC_ENV=local
|
||||||
|
ENV=local
|
||||||
|
API_SERVER=http://localhost:4015/api/v1
|
||||||
|
AUTH_COOKIE_DOMAIN=
|
||||||
4
.env.production
Normal file
4
.env.production
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
NEXT_PUBLIC_ENV=production
|
||||||
|
ENV=prod
|
||||||
|
API_SERVER=http://127.0.0.1:4015/api/v1
|
||||||
|
AUTH_COOKIE_DOMAIN=kric.com
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -15,9 +15,4 @@ yarn-debug.log*
|
|||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
.pnpm-debug.log*
|
.pnpm-debug.log*
|
||||||
.idea/
|
.idea/
|
||||||
*.iml
|
*.iml
|
||||||
|
|
||||||
# Local environment files
|
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
!.env.example
|
|
||||||
38
AGENTS.md
38
AGENTS.md
@@ -229,6 +229,7 @@ When implementation is complete, report in Korean:
|
|||||||
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
|
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
|
||||||
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
|
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
|
||||||
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
|
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
|
||||||
|
- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable.
|
||||||
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
|
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
|
||||||
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
|
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
|
||||||
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
|
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
|
||||||
@@ -265,6 +266,26 @@ Before each related task, read the current contents of every matching reference,
|
|||||||
|
|
||||||
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
|
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
|
||||||
|
|
||||||
|
## Noti-hub SMS Types
|
||||||
|
|
||||||
|
- `MessageType.SMS = 21`, `LMS = 22`, `MMS = 23`; `ChannelType.SMS = 2` is unchanged. `SMS_TYPE_ARRAY` and `SmsType` include all three.
|
||||||
|
- `LMS_MMS = 22` remains a deprecated source-compatibility alias for LMS only. It does not represent MMS. Enum reverse lookup for 22 returns LMS. Use numeric bulk-list paths; the server no longer accepts LMS_MMS in paths. Numeric 21/22/23 bulk-list requests all return the entire SMS channel, not type-filtered lists.
|
||||||
|
- Requests retain their existing URLs/body shapes. The server chooses the actual type per recipient after substitution: attachment -> MMS; otherwise title or UTF-8 body >= 90 bytes -> LMS; otherwise SMS.
|
||||||
|
- Refresh templates from the save response (`tmplatTy`); display actual delivery types from `sendTy`, not the template or result code. A bulk can contain multiple SMS types. LMS/MMS share result codes; use existing server result labels.
|
||||||
|
- SMS, LMS, MMS and KKO use cancellation code 9998. Verify with `npm run typecheck`, `npm run build`, and `node --test tests/noti-hub-sms.test.mjs`.
|
||||||
|
|
||||||
|
## Noti-hub Reservation Cancellation
|
||||||
|
|
||||||
|
- Import cancellation types, constants, and helpers from `@kri/common/noti-hub` only. They are runtime-neutral and require no optional peers.
|
||||||
|
- Individual current cancellation state is determined by resultCode via isReserveCanceledResult; bulk current state is cancellationStatus (NONE/PARTIAL/ALL). These describe current cancellation state, not cancellation eligibility. cancelDt and cancelUser are request history, not current state.
|
||||||
|
- SendResultInfo, SendInfo, and BulkSendInfo expose optional cancelable. Use isSendCancelable(item), which returns true only for cancelable === true, for cancellation eligibility; missing values from older responses are treated as false. Never infer eligibility from cancelDt, result labels, or result codes.
|
||||||
|
- cancelable reflects query-time state and may change before cancellation. Determine the final outcome from SendCancelResponse counts.
|
||||||
|
- sendIdx is the single-cancel identifier, not cmid. It is absent from the latest abbreviated report (/api/v1/report/last/send/...). Request sendIdx must be a positive integer; bulkSendKey is required and at most 32 characters.
|
||||||
|
- EMAIL_RESERVE_CANCELED_RESULT_CODE is 108 for EMAIL. SMS_KKO_RESERVE_CANCELED_RESULT_CODE is 9998 for SMS, LMS, MMS, and KKO. Unknown message types are not recognized as canceled.
|
||||||
|
- Display the server's resultViewLabel/resultLabel ("예약 취소"). There is no separate result-code list API.
|
||||||
|
- HTTP 200 can contain notCancelableCount. parseSendCancelResponse validates nonnegative integer counts and targetCount = canceledCount + alreadyCanceledCount + notCancelableCount, throwing TypeError on invalid data. Bulk targetCount counts currently registered detail rows; response canceledCount counts only cancellations made by that request.
|
||||||
|
- Existing response fields are unchanged; all added fields on existing types are optional. Verify with npm run typecheck and npm run build.
|
||||||
|
|
||||||
## HTTP Streaming
|
## HTTP Streaming
|
||||||
|
|
||||||
- `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body).
|
- `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body).
|
||||||
@@ -288,6 +309,23 @@ When implementing or changing frontend UI, use this order:
|
|||||||
- `kri-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior.
|
- `kri-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior.
|
||||||
- When enabled, a search value change (including clearing it) resets the option list scroll to the top on the next animation frame in both `filter` and `inputOnly` modes. Async result updates alone do not trigger another reset.
|
- When enabled, a search value change (including clearing it) resets the option list scroll to the top on the next animation frame in both `filter` and `inputOnly` modes. Async result updates alone do not trigger another reset.
|
||||||
|
|
||||||
|
### KriAutoComplete Option Tooltip
|
||||||
|
|
||||||
|
- `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior.
|
||||||
|
- When enabled, hovering an option shows its full `label` in a right-side tooltip. `singleLine` stays on one line until the available viewport width; `wrap` wraps at 28rem. The item depends on the shadcn `tooltip` component and provides its own `TooltipProvider`.
|
||||||
|
|
||||||
|
### KriAutoComplete Search Match
|
||||||
|
|
||||||
|
- `kri-auto-complete` exposes `searchMatch?: 'fuzzy' | 'contains'` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `fuzzy` (cmdk's default subsequence scoring), preserving existing behavior.
|
||||||
|
- `contains` keeps only options whose label or value contains the search text as a case-insensitive substring, in the original option order. It applies only when `searchMode` is `filter`.
|
||||||
|
|
||||||
|
### KriEditor SMS Preview
|
||||||
|
|
||||||
|
- `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract.
|
||||||
|
- Attachment presence (`smsHasAttachment`) takes priority and reports MMS. Otherwise a title or UTF-8 preview size >= `smsMaxBytes` (default 90) reports LMS; the remainder reports SMS. LMS/MMS share `lmsMaxBytes` (default 2000).
|
||||||
|
- UTF-8 byte counting includes `smsPreviewSuffix` and its separating newline, without storing the suffix in the body.
|
||||||
|
- This is a preview. Use the template-save response for saved `tmplatTy` and delivery-result `sendTy` for actual per-recipient type after server substitution. Registry updates require updating installed consumer copies.
|
||||||
|
|
||||||
### Required Shared References
|
### Required Shared References
|
||||||
|
|
||||||
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
||||||
|
|||||||
@@ -1,6 +1,26 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
import { createKriNextConfig } from "@kri/common/config";
|
import { createKriNextConfig } from "@kri/common/config";
|
||||||
|
|
||||||
const nextConfig = createKriNextConfig({}) satisfies NextConfig;
|
const nextConfig = createKriNextConfig({
|
||||||
|
async headers() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: "/api/kric-internal/:path*",
|
||||||
|
headers: [
|
||||||
|
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||||
|
{ key: "Access-Control-Allow-Methods", value: "GET, POST, OPTIONS" },
|
||||||
|
{
|
||||||
|
key: "Access-Control-Allow-Headers",
|
||||||
|
value: "Content-Type, X-API-Key",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "Access-Control-Expose-Headers",
|
||||||
|
value: "Content-Disposition",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
},
|
||||||
|
}) satisfies NextConfig;
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
98
package-lock.json
generated
98
package-lock.json
generated
@@ -41,7 +41,7 @@
|
|||||||
"embla-carousel-react": "^8.6.0",
|
"embla-carousel-react": "^8.6.0",
|
||||||
"jotai": "latest",
|
"jotai": "latest",
|
||||||
"lucide-react": "latest",
|
"lucide-react": "latest",
|
||||||
"next": "latest",
|
"next": "~16.4.1",
|
||||||
"prettier": "^3.9.10",
|
"prettier": "^3.9.10",
|
||||||
"radix-ui": "^1.8.0",
|
"radix-ui": "^1.8.0",
|
||||||
"react": "latest",
|
"react": "latest",
|
||||||
@@ -59,7 +59,7 @@
|
|||||||
"@types/react-dom": "latest",
|
"@types/react-dom": "latest",
|
||||||
"babel-plugin-react-compiler": "latest",
|
"babel-plugin-react-compiler": "latest",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "latest",
|
"eslint-config-next": "~16.4.1",
|
||||||
"playwright": "^1.64.1",
|
"playwright": "^1.64.1",
|
||||||
"tailwindcss": "latest",
|
"tailwindcss": "latest",
|
||||||
"tw-animate-css": "latest",
|
"tw-animate-css": "latest",
|
||||||
@@ -1260,15 +1260,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/env": {
|
"node_modules/@next/env": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz",
|
||||||
"integrity": "sha512-pyLlT5oafGlX8X7xjgGNXz5dNIDSxREm+qD6i9VLSZiZFopA/XWl8NM/KPmLx/8EG/++c49iid3gNWSQW1+2dQ==",
|
"integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@next/eslint-plugin-next": {
|
"node_modules/@next/eslint-plugin-next": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.3.tgz",
|
||||||
"integrity": "sha512-ffeflB/dL8RrvWejQximw01pOpKHN692Y3FjDB82DCd0YVvXvBD6vY7mcZp27yvSVFVM6wA73xVodEKF4spizA==",
|
"integrity": "sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -1309,9 +1309,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-darwin-arm64": {
|
"node_modules/@next/swc-darwin-arm64": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz",
|
||||||
"integrity": "sha512-yyZ+9MgViAKLLb5l1gPBGjRwnq3teNLb5Zx6JEw8LzNSTjlsnp+baUHFxTgl7PpjCmKf48VQfyipG1eBflb48Q==",
|
"integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1325,9 +1325,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-darwin-x64": {
|
"node_modules/@next/swc-darwin-x64": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz",
|
||||||
"integrity": "sha512-RePEEejEj1Auf5s9qEcG0JbcDP3ceNUS/ofNX8AhxzgIjTVlZIHMatlp16YplcSMpsVo/ZMQHJTjbMYJznjGUg==",
|
"integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1341,9 +1341,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz",
|
||||||
"integrity": "sha512-HhsyCqd+NpmvDDVY/LqkAN24f+QVvXh3ie+PfcwKinWL2Mu826JymQxJXGjAIfmJ4VlHjp4Pe/nZtXtUoEMAqw==",
|
"integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1357,9 +1357,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-arm64-musl": {
|
"node_modules/@next/swc-linux-arm64-musl": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz",
|
||||||
"integrity": "sha512-sN9Pf+Zh+RpZAOmbR7d8KAA8T61CVhawtbEJ2Bk6QrRzx6Z/6haaF4UiwBzytM96GRRRWZh9/WALIEO3npMamA==",
|
"integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1373,9 +1373,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-x64-gnu": {
|
"node_modules/@next/swc-linux-x64-gnu": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz",
|
||||||
"integrity": "sha512-D5M5xLWQVd1CvR+L7BickM1weRfmM41x3L1NWcnKY/oyJJqr1qwaCgmu3dMAhLBOMdZwSuDCRV6DJRRpiUkbDQ==",
|
"integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1389,9 +1389,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-x64-musl": {
|
"node_modules/@next/swc-linux-x64-musl": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz",
|
||||||
"integrity": "sha512-8d5WLS6a9YalqpOgXdlbvonFu+sIgjA+CO6tGzetrpPVcUL56foa7B7664h41rAlbLi5fJwK4vWji3zf4QDy+w==",
|
"integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1405,9 +1405,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz",
|
||||||
"integrity": "sha512-sQuOIiW3snb48UwrBcDMvFA/u03qtw2LeuSIxFIQ9AJuW9UG/4Ddsfo+eV73PnZwBhyncMtsKVh7PrzMol2/fA==",
|
"integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1421,9 +1421,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-win32-x64-msvc": {
|
"node_modules/@next/swc-win32-x64-msvc": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz",
|
||||||
"integrity": "sha512-6/33lCuxpdHUy27RegyGM/5uTpF7YZd3UR4D0gpkOA/tWY5YR7msbQjqPgCZmSmxrrTLGCXYA4A8vT2H5DPGTQ==",
|
"integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -5785,13 +5785,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-config-next": {
|
"node_modules/eslint-config-next": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.3.tgz",
|
||||||
"integrity": "sha512-2RHLYswzc+hNRktWAjIL6XAvwb1cKcjLawJ5KWywAxn/JivNHtG42ZigL1yobVXDqsimuuL2F9jcEcnHFzbppQ==",
|
"integrity": "sha512-j9IqBma6abp800frdUURaizYMgXOK+jNGyq6CsYcM9AxpSJs5D/TgMNGeAmRUilZvA7g9V1Tr71gNg9/SVTuMQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@next/eslint-plugin-next": "16.4.0",
|
"@next/eslint-plugin-next": "16.4.3",
|
||||||
"eslint-import-resolver-node": "^0.3.6",
|
"eslint-import-resolver-node": "^0.3.6",
|
||||||
"eslint-import-resolver-typescript": "^3.5.2",
|
"eslint-import-resolver-typescript": "^3.5.2",
|
||||||
"eslint-plugin-import": "^2.32.0",
|
"eslint-plugin-import": "^2.32.0",
|
||||||
@@ -7723,12 +7723,12 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/next": {
|
"node_modules/next": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/next/-/next-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz",
|
||||||
"integrity": "sha512-N2C+9q89Z/oLrsepSRS4jRMtwmUZAoZuAHU0e9T6+sAB5DdhADmrnOW+zjYijlrYFmVfmQhGVGy9eMFoB7UgKg==",
|
"integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@next/env": "16.4.0",
|
"@next/env": "16.4.3",
|
||||||
"@swc/helpers": "0.5.23",
|
"@swc/helpers": "0.5.23",
|
||||||
"baseline-browser-mapping": "^2.9.19",
|
"baseline-browser-mapping": "^2.9.19",
|
||||||
"caniuse-lite": "^1.0.30001579",
|
"caniuse-lite": "^1.0.30001579",
|
||||||
@@ -7742,15 +7742,15 @@
|
|||||||
"node": ">=20.9.0"
|
"node": ">=20.9.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@next/swc-darwin-arm64": "16.4.0",
|
"@next/swc-darwin-arm64": "16.4.3",
|
||||||
"@next/swc-darwin-x64": "16.4.0",
|
"@next/swc-darwin-x64": "16.4.3",
|
||||||
"@next/swc-linux-arm64-gnu": "16.4.0",
|
"@next/swc-linux-arm64-gnu": "16.4.3",
|
||||||
"@next/swc-linux-arm64-musl": "16.4.0",
|
"@next/swc-linux-arm64-musl": "16.4.3",
|
||||||
"@next/swc-linux-x64-gnu": "16.4.0",
|
"@next/swc-linux-x64-gnu": "16.4.3",
|
||||||
"@next/swc-linux-x64-musl": "16.4.0",
|
"@next/swc-linux-x64-musl": "16.4.3",
|
||||||
"@next/swc-win32-arm64-msvc": "16.4.0",
|
"@next/swc-win32-arm64-msvc": "16.4.3",
|
||||||
"@next/swc-win32-x64-msvc": "16.4.0",
|
"@next/swc-win32-x64-msvc": "16.4.3",
|
||||||
"sharp": "^0.35.4"
|
"sharp": "^0.35.5"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@opentelemetry/api": "^1.1.0",
|
"@opentelemetry/api": "^1.1.0",
|
||||||
|
|||||||
@@ -43,7 +43,7 @@
|
|||||||
"embla-carousel-react": "^8.6.0",
|
"embla-carousel-react": "^8.6.0",
|
||||||
"jotai": "latest",
|
"jotai": "latest",
|
||||||
"lucide-react": "latest",
|
"lucide-react": "latest",
|
||||||
"next": "latest",
|
"next": "~16.4.1",
|
||||||
"prettier": "^3.9.10",
|
"prettier": "^3.9.10",
|
||||||
"radix-ui": "^1.8.0",
|
"radix-ui": "^1.8.0",
|
||||||
"react": "latest",
|
"react": "latest",
|
||||||
@@ -61,7 +61,7 @@
|
|||||||
"@types/react-dom": "latest",
|
"@types/react-dom": "latest",
|
||||||
"babel-plugin-react-compiler": "latest",
|
"babel-plugin-react-compiler": "latest",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "latest",
|
"eslint-config-next": "~16.4.1",
|
||||||
"playwright": "^1.64.1",
|
"playwright": "^1.64.1",
|
||||||
"tailwindcss": "latest",
|
"tailwindcss": "latest",
|
||||||
"tw-animate-css": "latest",
|
"tw-animate-css": "latest",
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { cookies } from "next/headers";
|
import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
import { AppMainLayout } from "@/components/app-shell/AppMainLayout";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
|
|
||||||
export default async function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
export const dynamic = "force-dynamic";
|
||||||
const cookieStore = await cookies();
|
|
||||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
export default function MainLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||||
if (!accessToken) redirect("/logout");
|
// External JWTs live in this tab, so authentication is checked after hydration.
|
||||||
return <AppMainLayout>{children}</AppMainLayout>;
|
// Every BFF/API request still enforces verified server authentication and scope.
|
||||||
|
return <AuthSessionGate><AppMainLayout>{children}</AppMainLayout></AuthSessionGate>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,18 +3,20 @@
|
|||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useLogoutMutation } from "@/query/auth";
|
import { useLogoutMutation } from "@/query/auth";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
|
|
||||||
export default function LogoutPage() {
|
export default function LogoutPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { hydrated } = useAuth();
|
||||||
const logoutMutation = useLogoutMutation();
|
const logoutMutation = useLogoutMutation();
|
||||||
const started = useRef(false);
|
const started = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (started.current) return;
|
if (!hydrated || started.current) return;
|
||||||
started.current = true;
|
started.current = true;
|
||||||
void logoutMutation.mutateAsync().finally(() => router.replace("/login"));
|
void logoutMutation.mutateAsync().finally(() => router.replace("/login"));
|
||||||
}, [logoutMutation, router]);
|
}, [hydrated, logoutMutation, router]);
|
||||||
|
|
||||||
return <LoadingOverlayAdapter force label="로그아웃 중" />;
|
return <LoadingOverlayAdapter force label="로그아웃 중" />;
|
||||||
}
|
}
|
||||||
|
|||||||
22
src/app/api/auth/[[...slug]]/route.ts
Normal file
22
src/app/api/auth/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { errorToResponse } from "@kri/common/http";
|
||||||
|
import { createServerApi } from "@/lib/http-server";
|
||||||
|
import { isLoginUser } from "@/types/kart";
|
||||||
|
|
||||||
|
export async function GET(_request: Request, context: { params: Promise<{ slug?: string[] }> }) {
|
||||||
|
const { slug = [] } = await context.params;
|
||||||
|
if (slug.length !== 1 || slug[0] !== "my-info")
|
||||||
|
return NextResponse.json({ message: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||||
|
try {
|
||||||
|
const api = await createServerApi();
|
||||||
|
const user = await api.get<unknown>("/auth/my-info", { cache: "no-store" });
|
||||||
|
if (!isLoginUser(user)) {
|
||||||
|
return NextResponse.json({ message: "Invalid user response" }, { status: 502, headers: { "Cache-Control": "no-store" } });
|
||||||
|
}
|
||||||
|
return NextResponse.json({ userId: user.userId, userName: user.userName, userCmpn: user.userCmpn, userTeam: user.userTeam, userRole: user.userRole }, { headers: { "Cache-Control": "no-store" } });
|
||||||
|
} catch (error) {
|
||||||
|
const response = errorToResponse(error);
|
||||||
|
response.headers.set("Cache-Control", "no-store");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import {
|
import {
|
||||||
bookmarkUpstreamPath,
|
bookmarkUpstreamPath,
|
||||||
isBookmarkCreatePath,
|
isBookmarkCreatePath,
|
||||||
@@ -9,7 +8,6 @@ import {
|
|||||||
isBookmarkListPath,
|
isBookmarkListPath,
|
||||||
} from "@/lib/project-proxy-policy";
|
} from "@/lib/project-proxy-policy";
|
||||||
import { isBookmarkPage, readBookmarkSaveRequest } from "@/types/bookmark";
|
import { isBookmarkPage, readBookmarkSaveRequest } from "@/types/bookmark";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
const notFound = () =>
|
const notFound = () =>
|
||||||
@@ -19,7 +17,7 @@ const unauthorized = () =>
|
|||||||
const badRequest = () =>
|
const badRequest = () =>
|
||||||
NextResponse.json({ message: "북마크 저장 내용을 확인해 주세요." }, { status: 400 });
|
NextResponse.json({ message: "북마크 저장 내용을 확인해 주세요." }, { status: 400 });
|
||||||
const noStore = { headers: { "Cache-Control": "no-store" } };
|
const noStore = { headers: { "Cache-Control": "no-store" } };
|
||||||
const loggedIn = async () => !!(await cookies()).get(CookieKeys.AuthToken)?.value;
|
const loggedIn = async () => !!(await getServerAccessToken());
|
||||||
|
|
||||||
export async function GET(request: NextRequest, context: RouteContext) {
|
export async function GET(request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import {
|
import {
|
||||||
derivedUpstreamPath,
|
derivedUpstreamPath,
|
||||||
isDerivedCreatePath,
|
isDerivedCreatePath,
|
||||||
@@ -9,7 +8,6 @@ import {
|
|||||||
isDerivedListPath,
|
isDerivedListPath,
|
||||||
} from "@/lib/project-proxy-policy";
|
} from "@/lib/project-proxy-policy";
|
||||||
import { readDerivedSaveRequest } from "@/types/derived";
|
import { readDerivedSaveRequest } from "@/types/derived";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
const notFound = () =>
|
const notFound = () =>
|
||||||
@@ -17,7 +15,7 @@ const notFound = () =>
|
|||||||
const unauthorized = () =>
|
const unauthorized = () =>
|
||||||
NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
const noStore = { headers: { "Cache-Control": "no-store" } };
|
const noStore = { headers: { "Cache-Control": "no-store" } };
|
||||||
const loggedIn = async () => !!(await cookies()).get(CookieKeys.AuthToken)?.value;
|
const loggedIn = async () => !!(await getServerAccessToken());
|
||||||
|
|
||||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { exportTarget } from "@/lib/project-proxy-policy";
|
import { exportTarget } from "@/lib/project-proxy-policy";
|
||||||
import { readExcelRequest, readRawDataRequest } from "@/types/export";
|
import { readExcelRequest, readRawDataRequest } from "@/types/export";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
// Workbooks for large projects take a while to build on the server.
|
// Workbooks for large projects take a while to build on the server.
|
||||||
@@ -20,7 +18,7 @@ async function download(request: NextRequest, context: RouteContext, method: "GE
|
|||||||
const target = exportTarget(method, slug);
|
const target = exportTarget(method, slug);
|
||||||
if (!target)
|
if (!target)
|
||||||
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
if (target.body !== "none") {
|
if (target.body !== "none") {
|
||||||
|
|||||||
13
src/app/api/external/[urlkey]/login/route.ts
vendored
13
src/app/api/external/[urlkey]/login/route.ts
vendored
@@ -1,21 +1,17 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
|
||||||
import { serverEnv } from "@/lib/env.server";
|
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isRecord } from "@/types/kart";
|
import { isRecord } from "@/types/kart";
|
||||||
import { isExternalSession, isUrlKey } from "@/types/share";
|
import { isExternalSession, isUrlKey } from "@/types/share";
|
||||||
|
|
||||||
export async function POST(_request: NextRequest, context: { params: Promise<{ urlkey: string }> }) {
|
export async function POST(_request: NextRequest, context: { params: Promise<{ urlkey: string }> }) {
|
||||||
const { urlkey } = await context.params;
|
const { urlkey } = await context.params;
|
||||||
let response: NextResponse;
|
let response: NextResponse;
|
||||||
let token = "";
|
|
||||||
try {
|
try {
|
||||||
if (!isUrlKey(urlkey)) {
|
if (!isUrlKey(urlkey)) {
|
||||||
response = NextResponse.json({ message: "공유 링크를 찾을 수 없습니다." }, { status: 404 });
|
response = NextResponse.json({ message: "공유 링크를 찾을 수 없습니다." }, { status: 404 });
|
||||||
} else {
|
} else {
|
||||||
// Link login replaces the previous identity, including an expired credential cookie.
|
// A link login issues a tab-scoped credential without touching normal-login cookies.
|
||||||
const api = await createServerApi(false);
|
const api = await createServerApi(false);
|
||||||
const result = await api.post<unknown>(`/external/${urlkey}/login`, null, { cache: "no-store" });
|
const result = await api.post<unknown>(`/external/${urlkey}/login`, null, { cache: "no-store" });
|
||||||
const accessToken = isRecord(result) ? result.accessToken : null;
|
const accessToken = isRecord(result) ? result.accessToken : null;
|
||||||
@@ -23,8 +19,7 @@ export async function POST(_request: NextRequest, context: { params: Promise<{ u
|
|||||||
typeof accessToken !== "string" || !accessToken) {
|
typeof accessToken !== "string" || !accessToken) {
|
||||||
response = NextResponse.json({ message: "공유 링크 로그인 응답을 확인해 주세요." }, { status: 502 });
|
response = NextResponse.json({ message: "공유 링크 로그인 응답을 확인해 주세요." }, { status: 502 });
|
||||||
} else {
|
} else {
|
||||||
token = accessToken;
|
response = NextResponse.json({ user: result.user, link: result.link, accessToken });
|
||||||
response = NextResponse.json({ user: result.user, link: result.link });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -32,9 +27,5 @@ export async function POST(_request: NextRequest, context: { params: Promise<{ u
|
|||||||
response = new NextResponse(failure.body, { status: failure.status, headers: failure.headers });
|
response = new NextResponse(failure.body, { status: failure.status, headers: failure.headers });
|
||||||
}
|
}
|
||||||
response.headers.set("Cache-Control", "no-store");
|
response.headers.set("Cache-Control", "no-store");
|
||||||
response.cookies.set(CookieKeys.AuthToken, token, {
|
|
||||||
httpOnly: true, secure: ["prod", "production"].includes(serverEnv.ENV),
|
|
||||||
sameSite: "lax", path: "/", maxAge: token ? AUTH_COOKIE_MAX_AGE : 0,
|
|
||||||
});
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { isImportPath } from "@/lib/project-proxy-policy";
|
import { isImportPath } from "@/lib/project-proxy-policy";
|
||||||
import { readImportResult } from "@/types/export";
|
import { readImportResult } from "@/types/export";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
// Imports replace project data on the server and may run for minutes.
|
// Imports replace project data on the server and may run for minutes.
|
||||||
@@ -15,7 +13,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
if (!isImportPath(slug))
|
if (!isImportPath(slug))
|
||||||
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
return NextResponse.json({ message: "지원하지 않는 경로입니다." }, { status: 404 });
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
let file: File;
|
let file: File;
|
||||||
try {
|
try {
|
||||||
|
|||||||
129
src/app/api/kric-internal/[[...slug]]/route.ts
Normal file
129
src/app/api/kric-internal/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { errorToResponse } from "@kri/common/http";
|
||||||
|
import { createServerApiWithApiKey } from "@/lib/http-server";
|
||||||
|
import {
|
||||||
|
internalTarget,
|
||||||
|
readInternalProjectListQuery,
|
||||||
|
readInternalQuotaRequest,
|
||||||
|
readInternalReportBatch,
|
||||||
|
readInternalShareRequest,
|
||||||
|
} from "@/lib/kric-internal-policy";
|
||||||
|
import { readExcelRequest } from "@/types/export";
|
||||||
|
import { isRecord } from "@/types/kart";
|
||||||
|
import { isShareLink } from "@/types/share";
|
||||||
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
|
export const maxDuration = 660;
|
||||||
|
const noStore = { "Cache-Control": "no-store" };
|
||||||
|
const jsonError = (message: string, status: number) =>
|
||||||
|
NextResponse.json({ message }, { status, headers: noStore });
|
||||||
|
|
||||||
|
async function handle(request: NextRequest, context: RouteContext) {
|
||||||
|
const { slug = [] } = await context.params;
|
||||||
|
const target = internalTarget(request.method, slug);
|
||||||
|
if (!target) return jsonError("지원하지 않는 경로입니다.", 404);
|
||||||
|
const apiKey = request.headers.get("x-api-key")?.trim();
|
||||||
|
if (!apiKey) return jsonError("X-API-Key는 필수입니다.", 401);
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
let query: Record<string, string> = {};
|
||||||
|
if (target.kind === "projects") {
|
||||||
|
try {
|
||||||
|
query = readInternalProjectListQuery(request.nextUrl.searchParams);
|
||||||
|
} catch (error) {
|
||||||
|
return jsonError(error instanceof Error ? error.message : "조회 조건을 확인해 주세요.", 400);
|
||||||
|
}
|
||||||
|
} else if (target.kind !== "list" && target.kind !== "respondent") {
|
||||||
|
try {
|
||||||
|
const input: unknown = await request.json();
|
||||||
|
if (target.kind === "report") {
|
||||||
|
body = readInternalReportBatch(input);
|
||||||
|
} else if (target.kind === "quota") {
|
||||||
|
body = readInternalQuotaRequest(input);
|
||||||
|
} else if (target.kind === "share") {
|
||||||
|
body = readInternalShareRequest(input);
|
||||||
|
} else {
|
||||||
|
body = readExcelRequest(input);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
let message = "요청 내용을 확인해 주세요.";
|
||||||
|
if (error instanceof SyntaxError) {
|
||||||
|
message = "요청 JSON을 확인해 주세요.";
|
||||||
|
} else if (error instanceof Error) {
|
||||||
|
message = error.message;
|
||||||
|
}
|
||||||
|
return jsonError(message, 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const api = createServerApiWithApiKey(apiKey);
|
||||||
|
const options = { signal: request.signal, cache: "no-store" as const };
|
||||||
|
if (
|
||||||
|
target.kind === "list" ||
|
||||||
|
target.kind === "projects" ||
|
||||||
|
target.kind === "quota" ||
|
||||||
|
target.kind === "respondent" ||
|
||||||
|
target.kind === "share"
|
||||||
|
) {
|
||||||
|
let result: unknown;
|
||||||
|
if (target.kind === "list") {
|
||||||
|
result = await api.get<unknown>(target.path, options);
|
||||||
|
} else if (target.kind === "projects") {
|
||||||
|
result = await api.get<unknown>(target.path, { ...options, query });
|
||||||
|
} else {
|
||||||
|
result = await api.post<unknown>(target.path, body, options);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
target.kind === "share" &&
|
||||||
|
(!isShareLink(result) ||
|
||||||
|
result.projectType !== Number(slug[1]) ||
|
||||||
|
result.pkey !== slug[2] ||
|
||||||
|
result.pageOnly ||
|
||||||
|
!isRecord(body) ||
|
||||||
|
result.realUrl !== body.realUrl)
|
||||||
|
)
|
||||||
|
return jsonError("공유 링크 응답을 확인해 주세요.", 502);
|
||||||
|
return NextResponse.json(result, { headers: noStore });
|
||||||
|
}
|
||||||
|
const upstream = await api.streamPost(target.path, body, {
|
||||||
|
...options,
|
||||||
|
timeoutMs: 600_000,
|
||||||
|
idleTimeoutMs: 600_000,
|
||||||
|
...(target.kind === "report"
|
||||||
|
? { headers: { Accept: "application/x-ndjson" } }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
const contentType =
|
||||||
|
upstream.headers.get("content-type") ?? "application/octet-stream";
|
||||||
|
const disposition = upstream.headers.get("content-disposition");
|
||||||
|
if (
|
||||||
|
!upstream.body ||
|
||||||
|
(target.kind === "report"
|
||||||
|
? !contentType.includes("application/x-ndjson")
|
||||||
|
: !disposition || /json|text\/html/i.test(contentType))
|
||||||
|
) {
|
||||||
|
await upstream.body?.cancel();
|
||||||
|
return jsonError("서버 응답 형식을 확인해 주세요.", 502);
|
||||||
|
}
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
...noStore,
|
||||||
|
"Content-Type": contentType,
|
||||||
|
};
|
||||||
|
if (target.kind === "report") {
|
||||||
|
headers["X-Accel-Buffering"] = "no";
|
||||||
|
} else if (disposition) {
|
||||||
|
headers["Content-Disposition"] = disposition;
|
||||||
|
}
|
||||||
|
return new Response(upstream.body, { headers });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const response = errorToResponse(error);
|
||||||
|
response.headers.set("Cache-Control", "no-store");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET = handle;
|
||||||
|
export const POST = handle;
|
||||||
|
export const OPTIONS = () =>
|
||||||
|
new NextResponse(null, { status: 204, headers: noStore });
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isProjectRef, isRecord } from "@/types/kart";
|
import { isProjectRef, isRecord } from "@/types/kart";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "로그인이 필요합니다." },
|
{ message: "로그인이 필요합니다." },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
import { setAuthCookie } from "@/lib/auth-cookie";
|
||||||
import { serverEnv } from "@/lib/env.server";
|
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isLoginUser, isRecord } from "@/types/kart";
|
import { isLoginUser, isRecord } from "@/types/kart";
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
@@ -28,7 +26,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
{ status: 400 },
|
{ status: 400 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const serverApi = await createServerApi();
|
const serverApi = await createServerApi(false);
|
||||||
const result = await serverApi.post<unknown>(
|
const result = await serverApi.post<unknown>(
|
||||||
"/auth/login",
|
"/auth/login",
|
||||||
{ userId: body.userId.trim(), userPw: body.userPw },
|
{ userId: body.userId.trim(), userPw: body.userPw },
|
||||||
@@ -48,13 +46,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
const response = NextResponse.json(result.user, {
|
const response = NextResponse.json(result.user, {
|
||||||
headers: { "Cache-Control": "no-store" },
|
headers: { "Cache-Control": "no-store" },
|
||||||
});
|
});
|
||||||
response.cookies.set(CookieKeys.AuthToken, result.accessToken, {
|
setAuthCookie(response, result.accessToken);
|
||||||
httpOnly: true,
|
|
||||||
secure: ["prod", "production"].includes(serverEnv.ENV),
|
|
||||||
sameSite: "lax",
|
|
||||||
path: "/",
|
|
||||||
maxAge: AUTH_COOKIE_MAX_AGE,
|
|
||||||
});
|
|
||||||
return response;
|
return response;
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof SyntaxError)
|
if (error instanceof SyntaxError)
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { serverEnv } from "@/lib/env.server";
|
import { setAuthCookie } from "@/lib/auth-cookie";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
|
|
||||||
/** Stateless backend authentication has no logout API; discard the frontend session cookie. */
|
/** Stateless backend authentication has no logout API; discard the frontend session cookie. */
|
||||||
export async function POST() {
|
export async function POST() {
|
||||||
@@ -8,12 +7,6 @@ export async function POST() {
|
|||||||
{ ok: true },
|
{ ok: true },
|
||||||
{ headers: { "Cache-Control": "no-store" } },
|
{ headers: { "Cache-Control": "no-store" } },
|
||||||
);
|
);
|
||||||
response.cookies.set(CookieKeys.AuthToken, "", {
|
setAuthCookie(response, "");
|
||||||
httpOnly: true,
|
|
||||||
secure: ["prod", "production"].includes(serverEnv.ENV),
|
|
||||||
sameSite: "lax",
|
|
||||||
path: "/",
|
|
||||||
maxAge: 0,
|
|
||||||
});
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { readReportBatch } from "@/lib/report-contract";
|
import { readReportBatch } from "@/lib/report-contract";
|
||||||
import {
|
import {
|
||||||
isProjectReadPath,
|
isProjectReadPath,
|
||||||
projectReadQuery,
|
projectReadQuery,
|
||||||
isReportStreamPath,
|
isReportStreamPath,
|
||||||
} from "@/lib/project-proxy-policy";
|
} from "@/lib/project-proxy-policy";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
export async function GET(request: NextRequest, context: RouteContext) {
|
export async function GET(request: NextRequest, context: RouteContext) {
|
||||||
@@ -18,7 +16,7 @@ export async function GET(request: NextRequest, context: RouteContext) {
|
|||||||
{ message: "지원하지 않는 경로입니다." },
|
{ message: "지원하지 않는 경로입니다." },
|
||||||
{ status: 404 },
|
{ status: 404 },
|
||||||
);
|
);
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "로그인이 필요합니다." },
|
{ message: "로그인이 필요합니다." },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
@@ -49,7 +47,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
|
|||||||
{ message: "지원하지 않는 경로입니다." },
|
{ message: "지원하지 않는 경로입니다." },
|
||||||
{ status: 404 },
|
{ status: 404 },
|
||||||
);
|
);
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "로그인이 필요합니다." },
|
{ message: "로그인이 필요합니다." },
|
||||||
{ status: 401 },
|
{ status: 401 },
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { isQuotaListPath, isQuotaResultPath } from "@/lib/project-proxy-policy";
|
import { isQuotaListPath, isQuotaResultPath } from "@/lib/project-proxy-policy";
|
||||||
import { readQuotaRequest } from "@/types/quota";
|
import { readQuotaRequest } from "@/types/quota";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import type { RouteContext } from "@/types/common";
|
import type { RouteContext } from "@/types/common";
|
||||||
|
|
||||||
const notFound = () =>
|
const notFound = () =>
|
||||||
@@ -15,7 +13,7 @@ const unauthorized = () =>
|
|||||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
if (!isQuotaListPath(slug)) return notFound();
|
if (!isQuotaListPath(slug)) return notFound();
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
|
if (!(await getServerAccessToken())) return unauthorized();
|
||||||
try {
|
try {
|
||||||
const serverApi = await createServerApi();
|
const serverApi = await createServerApi();
|
||||||
const result = await serverApi.get<unknown>(
|
const result = await serverApi.get<unknown>(
|
||||||
@@ -31,7 +29,7 @@ export async function GET(_request: NextRequest, context: RouteContext) {
|
|||||||
export async function POST(request: NextRequest, context: RouteContext) {
|
export async function POST(request: NextRequest, context: RouteContext) {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
if (!isQuotaResultPath(slug)) return notFound();
|
if (!isQuotaResultPath(slug)) return notFound();
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value) return unauthorized();
|
if (!(await getServerAccessToken())) return unauthorized();
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = readQuotaRequest(await request.json());
|
body = readQuotaRequest(await request.json());
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import { cookies } from "next/headers";
|
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { errorToResponse } from "@kri/common/http";
|
import { errorToResponse } from "@kri/common/http";
|
||||||
import { createServerApi } from "@/lib/http-server";
|
import { createServerApi, getServerAccessToken } from "@/lib/http-server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
|
||||||
import { isProjectRef, isRecord } from "@/types/kart";
|
import { isProjectRef, isRecord } from "@/types/kart";
|
||||||
import { isShareLink } from "@/types/share";
|
import { isShareLink } from "@/types/share";
|
||||||
|
|
||||||
@@ -12,7 +10,7 @@ export async function POST(request: NextRequest, context: {
|
|||||||
const params = await context.params;
|
const params = await context.params;
|
||||||
const project = { projectType: params.projectType === "0" ? 0 : params.projectType === "1" ? 1 : null, pkey: params.pkey };
|
const project = { projectType: params.projectType === "0" ? 0 : params.projectType === "1" ? 1 : null, pkey: params.pkey };
|
||||||
if (!isProjectRef(project)) return NextResponse.json({ message: "프로젝트를 확인해 주세요." }, { status: 400 });
|
if (!isProjectRef(project)) return NextResponse.json({ message: "프로젝트를 확인해 주세요." }, { status: 400 });
|
||||||
if (!(await cookies()).get(CookieKeys.AuthToken)?.value)
|
if (!(await getServerAccessToken()))
|
||||||
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
return NextResponse.json({ message: "로그인이 필요합니다." }, { status: 401 });
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
try { body = await request.json(); } catch { body = null; }
|
try { body = await request.json(); } catch { body = null; }
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { kartMenus } from "@/config/menu.data";
|
|||||||
import type { KartMenuItem } from "@/config/menu.type";
|
import type { KartMenuItem } from "@/config/menu.type";
|
||||||
import { ProjectSelector } from "@/components/project/ProjectSelector";
|
import { ProjectSelector } from "@/components/project/ProjectSelector";
|
||||||
import { useProjectTitle } from "@/query/project";
|
import { useProjectTitle } from "@/query/project";
|
||||||
import { useProjectParamsMigration, useSelectedProject } from "@/hooks/useSelectedProject";
|
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { projectPagePath } from "@/lib/report-navigation";
|
import { projectPagePath } from "@/lib/report-navigation";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useMutation } from "@tanstack/react-query";
|
import { useMutation } from "@tanstack/react-query";
|
||||||
@@ -28,13 +28,18 @@ export function AppHeader({ user }: AppHeaderProps) {
|
|||||||
const { auth } = useAuth();
|
const { auth } = useAuth();
|
||||||
const external = isExternalUser(user);
|
const external = isExternalUser(user);
|
||||||
const { project } = useSelectedProject();
|
const { project } = useSelectedProject();
|
||||||
useProjectParamsMigration();
|
|
||||||
const title = useProjectTitle(project);
|
const title = useProjectTitle(project);
|
||||||
const [mobileOpen, setMobileOpen] = useState(false);
|
const [mobileOpen, setMobileOpen] = useState(false);
|
||||||
const menus = project && !(external && auth.external?.pageOnly)
|
const menus = project && !(external && auth.external?.pageOnly)
|
||||||
? kartMenus.filter((menu) => !menu.visible || menu.visible(user))
|
? kartMenus.filter((menu) => !menu.visible || menu.visible(user))
|
||||||
: [];
|
: [];
|
||||||
const projectTitle = project ? title : "Project Overview TOP 6";
|
// "(code) name" like the project selector; the code alone until the project list provides the
|
||||||
|
// name (useProjectTitle falls back to pkey). External links keep their link title.
|
||||||
|
const projectTitle = !project
|
||||||
|
? "Project Overview TOP 6"
|
||||||
|
: external || title === project.pkey
|
||||||
|
? title
|
||||||
|
: "(" + project.pkey + ") " + title;
|
||||||
const canCopyUrl = !!project && user.userRole < REPORT_MEMBER_ROLE;
|
const canCopyUrl = !!project && user.userRole < REPORT_MEMBER_ROLE;
|
||||||
const copy = useMutation({
|
const copy = useMutation({
|
||||||
mutationFn: async (mode: "P" | "U") => {
|
mutationFn: async (mode: "P" | "U") => {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { Fragment, Suspense, useEffect, useState, type ReactNode } from "react";
|
|||||||
import { usePathname, useRouter } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||||
import { AppHeader } from "./AppHeader";
|
import { AppHeader } from "./AppHeader";
|
||||||
|
import { ProjectEntry } from "@/components/project/ProjectEntry";
|
||||||
import { AppSidebar } from "./AppSidebar";
|
import { AppSidebar } from "./AppSidebar";
|
||||||
import { sideMenus } from "@/config/menu.data";
|
import { sideMenus } from "@/config/menu.data";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
@@ -19,20 +20,18 @@ export function AppMainLayout({ children }: { children: ReactNode }) {
|
|||||||
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
|
const externalAllowed = !external || (!!auth.external && externalPageAllowed(auth.external, pathname));
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hydrated && !auth.user) router.replace("/logout");
|
if (hydrated && !auth.user) router.replace("/logout");
|
||||||
|
else if (hydrated && external && !auth.accessToken) router.replace("/logout");
|
||||||
|
// Legacy Main sends shared-link users (isAdmin > 8) to Logout, ending the External session.
|
||||||
|
else if (hydrated && external && pathname === "/") router.replace("/logout");
|
||||||
else if (hydrated && !externalAllowed)
|
else if (hydrated && !externalAllowed)
|
||||||
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
|
router.replace((auth.external ? reportUrl(auth.external.realUrl) : "/logout") as Route);
|
||||||
}, [hydrated, auth.user, auth.external, externalAllowed, router]);
|
}, [hydrated, auth.user, auth.external, auth.accessToken, external, externalAllowed, pathname, router]);
|
||||||
const hasSidebar = sideMenus.length > 0;
|
const hasSidebar = sideMenus.length > 0;
|
||||||
if (!hydrated || !auth.user || !externalAllowed)
|
if (!hydrated || !auth.user || !externalAllowed || (external && !auth.accessToken))
|
||||||
return (
|
return null;
|
||||||
<p
|
|
||||||
role="status"
|
|
||||||
className="p-8 text-center text-sm text-muted-foreground"
|
|
||||||
>
|
|
||||||
로그인 정보를 확인하는 중입니다.
|
|
||||||
</p>
|
|
||||||
);
|
|
||||||
return (
|
return (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<ProjectEntry>
|
||||||
<KriMainLayout
|
<KriMainLayout
|
||||||
className="bg-kart-bg text-kart-text"
|
className="bg-kart-bg text-kart-text"
|
||||||
sidebarOpen={hasSidebar && menuOpen}
|
sidebarOpen={hasSidebar && menuOpen}
|
||||||
@@ -54,7 +53,11 @@ export function AppMainLayout({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
mainClassName="bg-kart-bg px-[1.0416vw] pt-2.5 pb-6"
|
mainClassName="bg-kart-bg px-[1.0416vw] pt-2.5 pb-6"
|
||||||
>
|
>
|
||||||
<Fragment key={auth.user.userId + ":" + auth.user.userRole}>{children}</Fragment>
|
<Fragment key={auth.user.userId + ":" + auth.user.userRole}>
|
||||||
|
{children}
|
||||||
|
</Fragment>
|
||||||
</KriMainLayout>
|
</KriMainLayout>
|
||||||
|
</ProjectEntry>
|
||||||
|
</Suspense>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
19
src/components/app-shell/AuthSessionGate.tsx
Normal file
19
src/components/app-shell/AuthSessionGate.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useAuthSession } from "@/hooks/useAuthSession";
|
||||||
|
|
||||||
|
export function AuthSessionGate({ children }: { children: ReactNode }) {
|
||||||
|
const session = useAuthSession();
|
||||||
|
const user = session.data;
|
||||||
|
const checking = session.isPending || session.isFetching;
|
||||||
|
const identity = user && JSON.stringify([user.userId, user.userRole, user.userTeam, user.userCmpn]);
|
||||||
|
|
||||||
|
return <>
|
||||||
|
{session.isError && !checking && <div role="alert" className="p-8 text-center text-sm">
|
||||||
|
<p>로그인 정보를 확인하지 못했습니다.</p>
|
||||||
|
<button type="button" onClick={() => { void session.refetch(); }}>다시 시도</button>
|
||||||
|
</div>}
|
||||||
|
{user && <div key={identity} hidden={session.isError}>{children}</div>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -3,14 +3,25 @@
|
|||||||
import * as React from 'react'
|
import * as React from 'react'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { MultiSelect } from '@/components/common/multi-select'
|
import { MultiSelect } from '@/components/common/multi-select'
|
||||||
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
import type {
|
||||||
|
MultiSelectOption,
|
||||||
|
MultiSelectOptionTooltip,
|
||||||
|
MultiSelectRef,
|
||||||
|
MultiSelectSearchMatch,
|
||||||
|
} from '@/components/common/multi-select'
|
||||||
|
|
||||||
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
export type {
|
||||||
|
MultiSelectOption,
|
||||||
|
MultiSelectOptionTooltip,
|
||||||
|
MultiSelectRef,
|
||||||
|
MultiSelectSearchMatch,
|
||||||
|
} from '@/components/common/multi-select'
|
||||||
|
|
||||||
export interface KriAutoCompleteBaseProps<T> {
|
export interface KriAutoCompleteBaseProps<T> {
|
||||||
items: T[]
|
items: T[]
|
||||||
searchable?: boolean
|
searchable?: boolean
|
||||||
searchMode?: 'filter' | 'inputOnly'
|
searchMode?: 'filter' | 'inputOnly'
|
||||||
|
searchMatch?: MultiSelectSearchMatch
|
||||||
resetScrollOnSearch?: boolean
|
resetScrollOnSearch?: boolean
|
||||||
defaultSearchValue?: string
|
defaultSearchValue?: string
|
||||||
onSearchValueChange?: (value: string) => void
|
onSearchValueChange?: (value: string) => void
|
||||||
@@ -26,6 +37,8 @@ export interface KriAutoCompleteBaseProps<T> {
|
|||||||
disabled?: boolean
|
disabled?: boolean
|
||||||
'aria-invalid'?: boolean
|
'aria-invalid'?: boolean
|
||||||
modalPopover?: boolean
|
modalPopover?: boolean
|
||||||
|
optionTooltip?: MultiSelectOptionTooltip
|
||||||
|
optionTooltipClassName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
export interface KriMultiSelectProps<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||||
@@ -57,6 +70,7 @@ export function KriMultiSelect<T = unknown>({
|
|||||||
onChange,
|
onChange,
|
||||||
searchable = true,
|
searchable = true,
|
||||||
searchMode = 'filter',
|
searchMode = 'filter',
|
||||||
|
searchMatch = 'fuzzy',
|
||||||
resetScrollOnSearch = false,
|
resetScrollOnSearch = false,
|
||||||
defaultSearchValue = '',
|
defaultSearchValue = '',
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
@@ -77,6 +91,8 @@ export function KriMultiSelect<T = unknown>({
|
|||||||
disabled,
|
disabled,
|
||||||
'aria-invalid': ariaInvalid,
|
'aria-invalid': ariaInvalid,
|
||||||
modalPopover = true,
|
modalPopover = true,
|
||||||
|
optionTooltip,
|
||||||
|
optionTooltipClassName,
|
||||||
}: KriMultiSelectProps<T>) {
|
}: KriMultiSelectProps<T>) {
|
||||||
const options = React.useMemo(
|
const options = React.useMemo(
|
||||||
() => toOptions(items, getValue, getLabel, withInfo),
|
() => toOptions(items, getValue, getLabel, withInfo),
|
||||||
@@ -98,6 +114,7 @@ export function KriMultiSelect<T = unknown>({
|
|||||||
badgeClassName={badgeClassName}
|
badgeClassName={badgeClassName}
|
||||||
searchable={searchable}
|
searchable={searchable}
|
||||||
searchMode={searchMode}
|
searchMode={searchMode}
|
||||||
|
searchMatch={searchMatch}
|
||||||
resetScrollOnSearch={resetScrollOnSearch}
|
resetScrollOnSearch={resetScrollOnSearch}
|
||||||
defaultSearchValue={defaultSearchValue}
|
defaultSearchValue={defaultSearchValue}
|
||||||
onSearchValueChange={onSearchValueChange}
|
onSearchValueChange={onSearchValueChange}
|
||||||
@@ -110,6 +127,8 @@ export function KriMultiSelect<T = unknown>({
|
|||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
aria-invalid={ariaInvalid}
|
aria-invalid={ariaInvalid}
|
||||||
modalPopover={modalPopover}
|
modalPopover={modalPopover}
|
||||||
|
optionTooltip={optionTooltip}
|
||||||
|
optionTooltipClassName={optionTooltipClassName}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -134,6 +153,7 @@ function KriSingleSelectInner<T>({
|
|||||||
onChange,
|
onChange,
|
||||||
searchable = true,
|
searchable = true,
|
||||||
searchMode = 'filter',
|
searchMode = 'filter',
|
||||||
|
searchMatch = 'fuzzy',
|
||||||
resetScrollOnSearch = false,
|
resetScrollOnSearch = false,
|
||||||
defaultSearchValue = '',
|
defaultSearchValue = '',
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
@@ -157,6 +177,8 @@ function KriSingleSelectInner<T>({
|
|||||||
disabled,
|
disabled,
|
||||||
'aria-invalid': ariaInvalid,
|
'aria-invalid': ariaInvalid,
|
||||||
modalPopover = true,
|
modalPopover = true,
|
||||||
|
optionTooltip,
|
||||||
|
optionTooltipClassName,
|
||||||
}: KriSingleSelectProps<T>, forwardedRef: React.ForwardedRef<MultiSelectRef>) {
|
}: KriSingleSelectProps<T>, forwardedRef: React.ForwardedRef<MultiSelectRef>) {
|
||||||
const ref = React.useRef<MultiSelectRef>(null)
|
const ref = React.useRef<MultiSelectRef>(null)
|
||||||
React.useImperativeHandle(
|
React.useImperativeHandle(
|
||||||
@@ -212,6 +234,7 @@ function KriSingleSelectInner<T>({
|
|||||||
badgeClassName={badgeClassName}
|
badgeClassName={badgeClassName}
|
||||||
searchable={searchable}
|
searchable={searchable}
|
||||||
searchMode={searchMode}
|
searchMode={searchMode}
|
||||||
|
searchMatch={searchMatch}
|
||||||
resetScrollOnSearch={resetScrollOnSearch}
|
resetScrollOnSearch={resetScrollOnSearch}
|
||||||
defaultSearchValue={defaultSearchValue}
|
defaultSearchValue={defaultSearchValue}
|
||||||
onSearchValueChange={onSearchValueChange}
|
onSearchValueChange={onSearchValueChange}
|
||||||
@@ -227,6 +250,8 @@ function KriSingleSelectInner<T>({
|
|||||||
aria-invalid={ariaInvalid}
|
aria-invalid={ariaInvalid}
|
||||||
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
||||||
modalPopover={modalPopover}
|
modalPopover={modalPopover}
|
||||||
|
optionTooltip={optionTooltip}
|
||||||
|
optionTooltipClassName={optionTooltipClassName}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ function MultiSelectInner<T>(
|
|||||||
hideSelectAll = false,
|
hideSelectAll = false,
|
||||||
searchable = true,
|
searchable = true,
|
||||||
searchMode = 'filter',
|
searchMode = 'filter',
|
||||||
|
searchMatch = 'fuzzy',
|
||||||
resetScrollOnSearch = false,
|
resetScrollOnSearch = false,
|
||||||
defaultSearchValue = '',
|
defaultSearchValue = '',
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
@@ -46,6 +47,8 @@ function MultiSelectInner<T>(
|
|||||||
closeOnSelect = false,
|
closeOnSelect = false,
|
||||||
preventDeselect = false,
|
preventDeselect = false,
|
||||||
hideOptionCheck = false,
|
hideOptionCheck = false,
|
||||||
|
optionTooltip,
|
||||||
|
optionTooltipClassName,
|
||||||
style,
|
style,
|
||||||
...buttonProps
|
...buttonProps
|
||||||
}: MultiSelectProps<T>,
|
}: MultiSelectProps<T>,
|
||||||
@@ -200,11 +203,14 @@ function MultiSelectInner<T>(
|
|||||||
selectedValues={selectedValues}
|
selectedValues={selectedValues}
|
||||||
searchable={searchable}
|
searchable={searchable}
|
||||||
searchMode={searchMode}
|
searchMode={searchMode}
|
||||||
|
searchMatch={searchMatch}
|
||||||
resetScrollOnSearch={resetScrollOnSearch}
|
resetScrollOnSearch={resetScrollOnSearch}
|
||||||
searchValue={searchValue}
|
searchValue={searchValue}
|
||||||
onSearchValueChange={handleSearchChange}
|
onSearchValueChange={handleSearchChange}
|
||||||
hideSelectAll={hideSelectAll}
|
hideSelectAll={hideSelectAll}
|
||||||
hideOptionCheck={hideOptionCheck}
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
optionTooltip={optionTooltip}
|
||||||
|
optionTooltipClassName={optionTooltipClassName}
|
||||||
selectionMode={selectionMode}
|
selectionMode={selectionMode}
|
||||||
emptyIndicator={emptyIndicator}
|
emptyIndicator={emptyIndicator}
|
||||||
onToggleOption={toggleOption}
|
onToggleOption={toggleOption}
|
||||||
|
|||||||
@@ -11,39 +11,84 @@ import {
|
|||||||
CommandList,
|
CommandList,
|
||||||
CommandSeparator,
|
CommandSeparator,
|
||||||
} from '@/components/ui/command'
|
} from '@/components/ui/command'
|
||||||
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
import type {
|
||||||
|
MultiSelectGroup,
|
||||||
|
MultiSelectOption,
|
||||||
|
MultiSelectOptionTooltip,
|
||||||
|
MultiSelectOptions,
|
||||||
|
MultiSelectSearchMatch,
|
||||||
|
} from './types'
|
||||||
import { isGroupedOptions } from './utils'
|
import { isGroupedOptions } from './utils'
|
||||||
|
|
||||||
|
// Case-insensitive substring match; equal scores keep the original option order.
|
||||||
|
function containsFilter(value: string, search: string) {
|
||||||
|
return value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0
|
||||||
|
}
|
||||||
|
|
||||||
interface MultiSelectContentProps<T> {
|
interface MultiSelectContentProps<T> {
|
||||||
options: MultiSelectOptions<T>
|
options: MultiSelectOptions<T>
|
||||||
selectedValues: string[]
|
selectedValues: string[]
|
||||||
searchable: boolean
|
searchable: boolean
|
||||||
searchMode: 'filter' | 'inputOnly'
|
searchMode: 'filter' | 'inputOnly'
|
||||||
|
searchMatch?: MultiSelectSearchMatch
|
||||||
searchValue: string
|
searchValue: string
|
||||||
resetScrollOnSearch?: boolean
|
resetScrollOnSearch?: boolean
|
||||||
onSearchValueChange: (value: string) => void
|
onSearchValueChange: (value: string) => void
|
||||||
hideSelectAll: boolean
|
hideSelectAll: boolean
|
||||||
hideOptionCheck: boolean
|
hideOptionCheck: boolean
|
||||||
|
optionTooltip?: MultiSelectOptionTooltip
|
||||||
|
optionTooltipClassName?: string
|
||||||
selectionMode: 'single' | 'multiple'
|
selectionMode: 'single' | 'multiple'
|
||||||
emptyIndicator: React.ReactNode
|
emptyIndicator: React.ReactNode
|
||||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||||
onToggleAll: () => void
|
onToggleAll: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface OptionTooltipSettings {
|
||||||
|
mode: MultiSelectOptionTooltip
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
function OptionItem<T>({
|
function OptionItem<T>({
|
||||||
option,
|
option,
|
||||||
selected,
|
selected,
|
||||||
hideOptionCheck,
|
hideOptionCheck,
|
||||||
|
tooltip,
|
||||||
onToggle,
|
onToggle,
|
||||||
}: {
|
}: {
|
||||||
option: MultiSelectOption<T>
|
option: MultiSelectOption<T>
|
||||||
selected: boolean
|
selected: boolean
|
||||||
hideOptionCheck: boolean
|
hideOptionCheck: boolean
|
||||||
|
tooltip?: OptionTooltipSettings
|
||||||
onToggle: () => void
|
onToggle: () => void
|
||||||
}) {
|
}) {
|
||||||
const Icon = option.icon
|
const Icon = option.icon
|
||||||
|
|
||||||
|
// cmdk's CommandItem overrides onPointerMove, so the label (not the item) is the tooltip trigger.
|
||||||
|
const label = tooltip ? (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="min-w-0 flex-1 truncate">{option.label}</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent
|
||||||
|
side="right"
|
||||||
|
className={cn(
|
||||||
|
'break-words',
|
||||||
|
tooltip.mode === 'wrap'
|
||||||
|
? 'max-w-[min(28rem,var(--radix-tooltip-content-available-width))]'
|
||||||
|
: 'max-w-[var(--radix-tooltip-content-available-width)]',
|
||||||
|
tooltip.className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
) : (
|
||||||
|
<span className="truncate">{option.label}</span>
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
value={`${option.label} ${option.value}`}
|
value={`${option.label} ${option.value}`}
|
||||||
@@ -62,7 +107,7 @@ function OptionItem<T>({
|
|||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
{Icon ? <Icon className="size-4" style={{ color: option.style?.iconColor }} /> : null}
|
||||||
<span className="truncate">{option.label}</span>
|
{label}
|
||||||
</CommandItem>
|
</CommandItem>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -71,11 +116,13 @@ function OptionsGroup<T>({
|
|||||||
group,
|
group,
|
||||||
selectedValues,
|
selectedValues,
|
||||||
hideOptionCheck,
|
hideOptionCheck,
|
||||||
|
tooltip,
|
||||||
onToggleOption,
|
onToggleOption,
|
||||||
}: {
|
}: {
|
||||||
group: MultiSelectGroup<T>
|
group: MultiSelectGroup<T>
|
||||||
selectedValues: string[]
|
selectedValues: string[]
|
||||||
hideOptionCheck: boolean
|
hideOptionCheck: boolean
|
||||||
|
tooltip?: OptionTooltipSettings
|
||||||
onToggleOption: (option: MultiSelectOption<T>) => void
|
onToggleOption: (option: MultiSelectOption<T>) => void
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
@@ -86,6 +133,7 @@ function OptionsGroup<T>({
|
|||||||
option={option}
|
option={option}
|
||||||
selected={selectedValues.includes(option.value)}
|
selected={selectedValues.includes(option.value)}
|
||||||
hideOptionCheck={hideOptionCheck}
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
tooltip={tooltip}
|
||||||
onToggle={() => onToggleOption(option)}
|
onToggle={() => onToggleOption(option)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -98,11 +146,14 @@ export function MultiSelectContent<T>({
|
|||||||
selectedValues,
|
selectedValues,
|
||||||
searchable,
|
searchable,
|
||||||
searchMode,
|
searchMode,
|
||||||
|
searchMatch = 'fuzzy',
|
||||||
searchValue,
|
searchValue,
|
||||||
resetScrollOnSearch = false,
|
resetScrollOnSearch = false,
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
hideSelectAll,
|
hideSelectAll,
|
||||||
hideOptionCheck,
|
hideOptionCheck,
|
||||||
|
optionTooltip,
|
||||||
|
optionTooltipClassName,
|
||||||
selectionMode,
|
selectionMode,
|
||||||
emptyIndicator,
|
emptyIndicator,
|
||||||
onToggleOption,
|
onToggleOption,
|
||||||
@@ -123,9 +174,13 @@ export function MultiSelectContent<T>({
|
|||||||
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
|
const flatOptions = grouped ? options.flatMap((group) => group.options) : options
|
||||||
const selectableOptions = flatOptions.filter((option) => !option.disabled)
|
const selectableOptions = flatOptions.filter((option) => !option.disabled)
|
||||||
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
||||||
|
const tooltip = optionTooltip ? { mode: optionTooltip, className: optionTooltipClassName } : undefined
|
||||||
|
|
||||||
return (
|
const content = (
|
||||||
<Command shouldFilter={searchMode === 'filter'}>
|
<Command
|
||||||
|
shouldFilter={searchMode === 'filter'}
|
||||||
|
filter={searchMatch === 'contains' ? containsFilter : undefined}
|
||||||
|
>
|
||||||
{searchable ? (
|
{searchable ? (
|
||||||
<CommandInput
|
<CommandInput
|
||||||
value={searchValue}
|
value={searchValue}
|
||||||
@@ -161,6 +216,7 @@ export function MultiSelectContent<T>({
|
|||||||
group={group}
|
group={group}
|
||||||
selectedValues={selectedValues}
|
selectedValues={selectedValues}
|
||||||
hideOptionCheck={hideOptionCheck}
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
tooltip={tooltip}
|
||||||
onToggleOption={onToggleOption}
|
onToggleOption={onToggleOption}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
@@ -172,6 +228,7 @@ export function MultiSelectContent<T>({
|
|||||||
option={option}
|
option={option}
|
||||||
selected={selectedValues.includes(option.value)}
|
selected={selectedValues.includes(option.value)}
|
||||||
hideOptionCheck={hideOptionCheck}
|
hideOptionCheck={hideOptionCheck}
|
||||||
|
tooltip={tooltip}
|
||||||
onToggle={() => onToggleOption(option)}
|
onToggle={() => onToggleOption(option)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -180,4 +237,6 @@ export function MultiSelectContent<T>({
|
|||||||
</CommandList>
|
</CommandList>
|
||||||
</Command>
|
</Command>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
return tooltip ? <TooltipProvider delayDuration={0}>{content}</TooltipProvider> : content
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ export type {
|
|||||||
AnimationConfig,
|
AnimationConfig,
|
||||||
MultiSelectGroup,
|
MultiSelectGroup,
|
||||||
MultiSelectOption,
|
MultiSelectOption,
|
||||||
|
MultiSelectOptionTooltip,
|
||||||
MultiSelectOptions,
|
MultiSelectOptions,
|
||||||
MultiSelectProps,
|
MultiSelectProps,
|
||||||
MultiSelectRef,
|
MultiSelectRef,
|
||||||
MultiSelectResponsiveConfig,
|
MultiSelectResponsiveConfig,
|
||||||
MultiSelectResponsiveSettings,
|
MultiSelectResponsiveSettings,
|
||||||
|
MultiSelectSearchMatch,
|
||||||
MultiSelectSelectionMode,
|
MultiSelectSelectionMode,
|
||||||
MultiSelectVariant,
|
MultiSelectVariant,
|
||||||
} from './types'
|
} from './types'
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ export interface MultiSelectGroup<T = unknown> {
|
|||||||
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
||||||
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
||||||
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
||||||
|
export type MultiSelectOptionTooltip = 'singleLine' | 'wrap'
|
||||||
|
export type MultiSelectSearchMatch = 'fuzzy' | 'contains'
|
||||||
|
|
||||||
export interface MultiSelectResponsiveSettings {
|
export interface MultiSelectResponsiveSettings {
|
||||||
maxCount?: number
|
maxCount?: number
|
||||||
@@ -64,6 +66,7 @@ export interface MultiSelectProps<T = unknown>
|
|||||||
hideSelectAll?: boolean
|
hideSelectAll?: boolean
|
||||||
searchable?: boolean
|
searchable?: boolean
|
||||||
searchMode?: 'filter' | 'inputOnly'
|
searchMode?: 'filter' | 'inputOnly'
|
||||||
|
searchMatch?: MultiSelectSearchMatch
|
||||||
resetScrollOnSearch?: boolean
|
resetScrollOnSearch?: boolean
|
||||||
defaultSearchValue?: string
|
defaultSearchValue?: string
|
||||||
onSearchValueChange?: (value: string) => void
|
onSearchValueChange?: (value: string) => void
|
||||||
@@ -79,6 +82,8 @@ export interface MultiSelectProps<T = unknown>
|
|||||||
closeOnSelect?: boolean
|
closeOnSelect?: boolean
|
||||||
preventDeselect?: boolean
|
preventDeselect?: boolean
|
||||||
hideOptionCheck?: boolean
|
hideOptionCheck?: boolean
|
||||||
|
optionTooltip?: MultiSelectOptionTooltip
|
||||||
|
optionTooltipClassName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MultiSelectRef {
|
export interface MultiSelectRef {
|
||||||
|
|||||||
@@ -142,6 +142,7 @@ function Workspace({ project }: { project: ProjectRef }) {
|
|||||||
id="import_data"
|
id="import_data"
|
||||||
title="Data Import"
|
title="Data Import"
|
||||||
info="Data를 교체 할수 있습니다."
|
info="Data를 교체 할수 있습니다."
|
||||||
|
notice="※ 파생변수 데이터는 저장되지 않으며, Data Import 직후 파생변수 값이 재계산됩니다."
|
||||||
formTitle="Export Header"
|
formTitle="Export Header"
|
||||||
onForm={() => save({ kind: "form/data", project, name: { prefix: EXPORT_PREFIX.header, title } })}
|
onForm={() => save({ kind: "form/data", project, name: { prefix: EXPORT_PREFIX.header, title } })}
|
||||||
confirmText={title + " 프로젝트의 모든 완료 데이터를 삭제 후 진행됩니다.\r\n진행 하시겠습니까?"}
|
confirmText={title + " 프로젝트의 모든 완료 데이터를 삭제 후 진행됩니다.\r\n진행 하시겠습니까?"}
|
||||||
@@ -194,11 +195,14 @@ function Column({ icon, title, children }: { icon: string; title: string; childr
|
|||||||
function EximBox({
|
function EximBox({
|
||||||
title,
|
title,
|
||||||
info,
|
info,
|
||||||
|
notice,
|
||||||
action,
|
action,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
info: string;
|
info: string;
|
||||||
|
/** Optional caution shown under the header row. */
|
||||||
|
notice?: string;
|
||||||
action?: ReactNode;
|
action?: ReactNode;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
@@ -211,6 +215,7 @@ function EximBox({
|
|||||||
</div>
|
</div>
|
||||||
{action}
|
{action}
|
||||||
</div>
|
</div>
|
||||||
|
{notice ? <p className="px-4 pt-3 text-sm text-kart-text">{notice}</p> : null}
|
||||||
<div className="flex items-center justify-between gap-5 px-4 py-3.5">{children}</div>
|
<div className="flex items-center justify-between gap-5 px-4 py-3.5">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -247,6 +252,7 @@ function ImportBox({
|
|||||||
id,
|
id,
|
||||||
title,
|
title,
|
||||||
info,
|
info,
|
||||||
|
notice,
|
||||||
formTitle,
|
formTitle,
|
||||||
onForm,
|
onForm,
|
||||||
confirmText,
|
confirmText,
|
||||||
@@ -257,6 +263,7 @@ function ImportBox({
|
|||||||
id: string;
|
id: string;
|
||||||
title: string;
|
title: string;
|
||||||
info: string;
|
info: string;
|
||||||
|
notice?: string;
|
||||||
formTitle: string;
|
formTitle: string;
|
||||||
onForm: () => void;
|
onForm: () => void;
|
||||||
confirmText: string;
|
confirmText: string;
|
||||||
@@ -281,6 +288,7 @@ function ImportBox({
|
|||||||
<EximBox
|
<EximBox
|
||||||
title={title}
|
title={title}
|
||||||
info={info}
|
info={info}
|
||||||
|
notice={notice}
|
||||||
action={
|
action={
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -4,33 +4,31 @@ import { useEffect, useRef, useState } from "react";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import type { Route } from "next";
|
import type { Route } from "next";
|
||||||
import { useSetAtom } from "jotai";
|
import { useSetAtom } from "jotai";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { apiError } from "@kri/common/http";
|
import { apiError } from "@kri/common/http";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { useResetSession } from "@/hooks/useResetSession";
|
||||||
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { authApi } from "@/lib/http-client";
|
||||||
import { isExternalSession, reportUrl, type ExternalSession } from "@/types/share";
|
import { isExternalLoginResponse, reportUrl, type ExternalLoginResponse } from "@/types/share";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
|
|
||||||
export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { hydrated, setAuth, logout } = useAuth();
|
const { hydrated, setAuth } = useAuth();
|
||||||
const setProject = useSetAtom(selectedProjectAtom);
|
const setProject = useSetAtom(selectedProjectAtom);
|
||||||
const queryClient = useQueryClient();
|
const resetSession = useResetSession();
|
||||||
const pending = useRef<Promise<ExternalSession> | null>(null);
|
const pending = useRef<Promise<ExternalLoginResponse> | null>(null);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hydrated) return;
|
if (!hydrated) return;
|
||||||
let active = true;
|
let active = true;
|
||||||
const enter = async () => {
|
const enter = async () => {
|
||||||
logout();
|
setAuth({ mode: "external", user: null });
|
||||||
setProject(null);
|
await resetSession();
|
||||||
await queryClient.cancelQueries();
|
const result = await authApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
||||||
queryClient.clear();
|
|
||||||
const result = await nextApi.post<unknown>(`/external/${encodeURIComponent(urlKey)}/login`, null, {
|
|
||||||
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
||||||
});
|
});
|
||||||
if (!isExternalSession(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
if (!isExternalLoginResponse(result)) throw new Error("공유 링크 로그인 응답을 확인해 주세요.");
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
// Reuse the request during StrictMode effect replay; each entry records one landing.
|
// Reuse the request during StrictMode effect replay; each entry records one landing.
|
||||||
@@ -38,13 +36,15 @@ export function ExternalEntry({ urlKey }: { urlKey: string }) {
|
|||||||
void pending.current.then((result) => {
|
void pending.current.then((result) => {
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
setProject({ userId: result.user.userId, project: { projectType: result.link.projectType, pkey: result.link.pkey } });
|
||||||
setAuth({ user: result.user, external: result.link });
|
setAuth({ mode: "external", user: result.user, external: result.link, accessToken: result.accessToken });
|
||||||
router.replace(reportUrl(result.link.realUrl) as Route);
|
router.replace(reportUrl(result.link.realUrl) as Route);
|
||||||
}).catch((reason: unknown) => {
|
}).catch((reason: unknown) => {
|
||||||
if (active) setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
if (active) {
|
||||||
|
setError(apiError(reason, { fallbackMessage: "공유 링크를 확인해 주세요." }).message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return () => { active = false; };
|
return () => { active = false; };
|
||||||
}, [hydrated, logout, setAuth, setProject, queryClient, router, urlKey]);
|
}, [hydrated, setAuth, setProject, resetSession, router, urlKey]);
|
||||||
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
if (error) return <p role="alert" className="p-8 text-center text-sm">{error}</p>;
|
||||||
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
return <LoadingOverlayAdapter force label="공유 링크를 확인하는 중입니다." />;
|
||||||
}
|
}
|
||||||
|
|||||||
118
src/components/project/ProjectEntry.tsx
Normal file
118
src/components/project/ProjectEntry.tsx
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState, type ReactNode } from "react";
|
||||||
|
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import type { Route } from "next";
|
||||||
|
import { useStore } from "jotai";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { authStateAtom, useAuth } from "@/hooks/useAuth";
|
||||||
|
import { selectedProjectAtom, useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
|
import { projectSelectionAtom } from "@/hooks/useProjectNavigation";
|
||||||
|
import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
|
||||||
|
import { isProjectPage } from "@/lib/report-navigation";
|
||||||
|
import {
|
||||||
|
announceProjectAccess, PROJECT_ACCESS_EVENT, projectFromSearch,
|
||||||
|
type ProjectAccessEvent,
|
||||||
|
} from "@/lib/project-access";
|
||||||
|
import { isExternalUser } from "@/types/share";
|
||||||
|
import { projectKey } from "@/types/kart";
|
||||||
|
|
||||||
|
/** Resolve incoming project parameters before mounting any project data consumers. */
|
||||||
|
export function ProjectEntry({ children }: { children: ReactNode }) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const search = useSearchParams().toString();
|
||||||
|
const router = useRouter();
|
||||||
|
const store = useStore();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { auth } = useAuth();
|
||||||
|
const { project, select } = useSelectedProject();
|
||||||
|
const external = isExternalUser(auth.user);
|
||||||
|
const hasParams = isProjectPage(pathname) &&
|
||||||
|
(new URLSearchParams(search).has("projectType") || new URLSearchParams(search).has("pkey"));
|
||||||
|
const [denied, setDenied] = useState<ProjectAccessEvent | null>(null);
|
||||||
|
const candidate = hasParams ? projectFromSearch(new URLSearchParams(search)) : project;
|
||||||
|
const projectType = candidate?.projectType;
|
||||||
|
const pkey = candidate?.pkey;
|
||||||
|
const needsAccess = isProjectPage(pathname) && !external && !!candidate;
|
||||||
|
const access = useQuery({
|
||||||
|
queryKey: ["kart", auth.user?.userId, auth.user?.userRole, auth.user?.userTeam,
|
||||||
|
"project-access", projectType, pkey],
|
||||||
|
enabled: needsAccess,
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!candidate) throw new Error("Project required");
|
||||||
|
await checkProjectAccess(candidate);
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
staleTime: 0,
|
||||||
|
retry: false,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
meta: { ignoreGlobalLoading: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasParams || (!external && (!access.isSuccess || access.isFetching))) return;
|
||||||
|
let active = true;
|
||||||
|
const id = store.get(projectSelectionAtom).id + 1;
|
||||||
|
store.set(projectSelectionAtom, { id, pending: true });
|
||||||
|
const current = () => active && store.get(projectSelectionAtom).id === id &&
|
||||||
|
store.get(authStateAtom) === auth;
|
||||||
|
const enter = async () => {
|
||||||
|
// External scope always comes from the verified link, never address parameters.
|
||||||
|
if (!external) {
|
||||||
|
if (projectType === undefined || !pkey || !auth.user) return;
|
||||||
|
const incoming = { projectType, pkey };
|
||||||
|
await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), incoming);
|
||||||
|
if (!current()) return;
|
||||||
|
select(incoming);
|
||||||
|
announceProjectAccess({ project: incoming, allowed: true });
|
||||||
|
}
|
||||||
|
if (!current()) return;
|
||||||
|
const params = new URLSearchParams(search);
|
||||||
|
params.delete("projectType");
|
||||||
|
params.delete("pkey");
|
||||||
|
const clean = pathname + (params.size ? "?" + params : "") + window.location.hash;
|
||||||
|
router.replace(clean as Route, { scroll: false });
|
||||||
|
};
|
||||||
|
void Promise.resolve().then(enter).catch(() => {
|
||||||
|
if (current()) router.replace("/");
|
||||||
|
}).finally(() => {
|
||||||
|
if (store.get(projectSelectionAtom).id === id)
|
||||||
|
store.set(projectSelectionAtom, { id, pending: false });
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
if (store.get(projectSelectionAtom).id === id)
|
||||||
|
store.set(projectSelectionAtom, { id: id + 1, pending: false });
|
||||||
|
};
|
||||||
|
}, [hasParams, search, pathname, projectType, pkey, access.isSuccess, access.isFetching,
|
||||||
|
auth, external, select, router, store, queryClient]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onAccess = (event: Event) => {
|
||||||
|
const detail = (event as CustomEvent<ProjectAccessEvent>).detail;
|
||||||
|
if (!project || projectKey(detail.project) !== projectKey(project)) return;
|
||||||
|
setDenied(detail.allowed ? null : detail);
|
||||||
|
if (!detail.allowed) {
|
||||||
|
const predicate = (query: { queryKey: readonly unknown[] }) =>
|
||||||
|
query.queryKey[0] === "kart" && query.queryKey[1] === auth.user?.userId &&
|
||||||
|
query.queryKey.some((part, index, key) =>
|
||||||
|
part === project.projectType && key[index + 1] === project.pkey);
|
||||||
|
void queryClient.cancelQueries({ predicate }).then(() => queryClient.removeQueries({ predicate }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener(PROJECT_ACCESS_EVENT, onAccess);
|
||||||
|
return () => window.removeEventListener(PROJECT_ACCESS_EVENT, onAccess);
|
||||||
|
}, [project, auth.user?.userId, queryClient]);
|
||||||
|
|
||||||
|
const failed = isProjectPage(pathname) && (
|
||||||
|
(needsAccess && access.isError) ||
|
||||||
|
(hasParams && !external && !candidate) ||
|
||||||
|
(!hasParams && !!project && !!denied && !denied.allowed && projectKey(denied.project) === projectKey(project))
|
||||||
|
);
|
||||||
|
useEffect(() => {
|
||||||
|
if (failed) router.replace("/");
|
||||||
|
}, [failed, router]);
|
||||||
|
|
||||||
|
if (hasParams || failed || (needsAccess && !access.isSuccess)) return null;
|
||||||
|
return children;
|
||||||
|
}
|
||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import type { Route } from "next";
|
||||||
|
import { useProjectNavigation } from "@/hooks/useProjectNavigation";
|
||||||
|
import { projectPageUrl } from "@/lib/project-access";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { KriPieChart } from "@/components/chart";
|
import { KriPieChart } from "@/components/chart";
|
||||||
import { useProjectSummaryQuery } from "@/query/project";
|
import { useProjectSummaryQuery } from "@/query/project";
|
||||||
@@ -21,7 +24,8 @@ export function ProjectOverview() {
|
|||||||
const { auth } = useAuth();
|
const { auth } = useAuth();
|
||||||
const summary = useProjectSummaryQuery();
|
const summary = useProjectSummaryQuery();
|
||||||
const fontReady = useChartFontReady(labels.join("") + "0123456789");
|
const fontReady = useChartFontReady(labels.join("") + "0123456789");
|
||||||
const { hydrated, select, clear } = useSelectedProject();
|
const { hydrated, clear } = useSelectedProject();
|
||||||
|
const { navigate, pending } = useProjectNavigation();
|
||||||
useVisitLog("/");
|
useVisitLog("/");
|
||||||
// Legacy Main.js resets the selected project whenever the overview opens.
|
// Legacy Main.js resets the selected project whenever the overview opens.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -47,8 +51,14 @@ export function ProjectOverview() {
|
|||||||
className="relative h-[420px] rounded-[15px] border border-kart-line bg-white"
|
className="relative h-[420px] rounded-[15px] border border-kart-line bg-white"
|
||||||
>
|
>
|
||||||
<Link
|
<Link
|
||||||
href="/Report/Current"
|
href={projectPageUrl("/Report/Current", project) as Route}
|
||||||
onClick={() => select(project)}
|
prefetch={false}
|
||||||
|
aria-disabled={pending}
|
||||||
|
onClick={(event) => {
|
||||||
|
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||||
|
event.preventDefault();
|
||||||
|
if (!pending) void navigate(project, "/Report/Current");
|
||||||
|
}}
|
||||||
title={project.title ?? project.pkey}
|
title={project.title ?? project.pkey}
|
||||||
className="-m-px flex h-[55px] items-center justify-between rounded-[15px] border border-kart-line bg-kart-soft p-4"
|
className="-m-px flex h-[55px] items-center justify-between rounded-[15px] border border-kart-line bg-kart-soft p-4"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,18 +1,26 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter, usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { KriSingleSelect } from "@/components/common/KriAutoComplete";
|
import { KriSingleSelect } from "@/components/common/KriAutoComplete";
|
||||||
import { useProjectListQuery } from "@/query/project";
|
import { useProjectListQuery } from "@/query/project";
|
||||||
|
import { useProjectNavigation } from "@/hooks/useProjectNavigation";
|
||||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { projectKey } from "@/types/kart";
|
import { projectKey } from "@/types/kart";
|
||||||
import { projectPagePath } from "@/lib/report-navigation";
|
import { projectPagePath } from "@/lib/report-navigation";
|
||||||
import { QueryState } from "./QueryState";
|
import { QueryState } from "./QueryState";
|
||||||
|
|
||||||
|
function getProjectPlaceholder(checkingAccess: boolean, loading: boolean, projectCount: number): string {
|
||||||
|
if (checkingAccess) return "접근 권한을 확인하는 중...";
|
||||||
|
if (loading) return "목록을 불러오는 중...";
|
||||||
|
if (projectCount > 0) return "프로젝트 선택";
|
||||||
|
return "조회 가능한 프로젝트가 없습니다.";
|
||||||
|
}
|
||||||
|
|
||||||
/** Legacy ProjectSelect: search dropdown that always reads "프로젝트 선택". */
|
/** Legacy ProjectSelect: search dropdown that always reads "프로젝트 선택". */
|
||||||
export function ProjectSelector() {
|
export function ProjectSelector() {
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { project: selected, select } = useSelectedProject();
|
const { project: selected } = useSelectedProject();
|
||||||
|
const { navigate, pending } = useProjectNavigation();
|
||||||
const projects = useProjectListQuery();
|
const projects = useProjectListQuery();
|
||||||
if (projects.isError)
|
if (projects.isError)
|
||||||
return (
|
return (
|
||||||
@@ -35,24 +43,22 @@ export function ProjectSelector() {
|
|||||||
);
|
);
|
||||||
if (!project) return;
|
if (!project) return;
|
||||||
// Same page for the new project (legacy keeps the current menu), progress from home.
|
// Same page for the new project (legacy keeps the current menu), progress from home.
|
||||||
select(project);
|
void navigate(project, projectPagePath(pathname));
|
||||||
router.push(projectPagePath(pathname));
|
|
||||||
}}
|
}}
|
||||||
placeholder={
|
placeholder={getProjectPlaceholder(pending, projects.isPending, projects.data?.length ?? 0)}
|
||||||
projects.isPending
|
|
||||||
? "목록을 불러오는 중..."
|
|
||||||
: projects.data?.length
|
|
||||||
? "프로젝트 선택"
|
|
||||||
: "조회 가능한 프로젝트가 없습니다."
|
|
||||||
}
|
|
||||||
widthClassName="w-full"
|
widthClassName="w-full"
|
||||||
className="h-8 min-h-8 rounded-[39px] border-[#d0d0d0] bg-kart-soft px-[22px] py-0 text-sm shadow-none"
|
className="h-8 min-h-8 rounded-[39px] border-[#d0d0d0] bg-kart-soft px-[22px] py-0 text-sm shadow-none"
|
||||||
spanClassName="text-sm [&_span]:text-kart-text"
|
spanClassName="text-sm [&_span]:text-kart-text"
|
||||||
searchable
|
searchable
|
||||||
|
// Legacy Dropdown search: case-insensitive substring, not fuzzy.
|
||||||
|
searchMatch="contains"
|
||||||
resetScrollOnSearch
|
resetScrollOnSearch
|
||||||
|
// Legacy react-tooltip: full "(pkey) title" on hover, right side, 65% opacity.
|
||||||
|
optionTooltip="singleLine"
|
||||||
|
optionTooltipClassName="opacity-65"
|
||||||
preventDeselect
|
preventDeselect
|
||||||
hideOptionCheck
|
hideOptionCheck
|
||||||
disabled={projects.isPending}
|
disabled={projects.isPending || pending}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
import { Provider as JotaiProvider } from "jotai";
|
import { Provider as JotaiProvider } from "jotai";
|
||||||
import { QueryProvider } from "@kri/common/query";
|
import { QueryProvider } from "@kri/common/query";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
import { QueryLoadingSync } from "./QueryLoadingSync";
|
import { QueryLoadingSync } from "./QueryLoadingSync";
|
||||||
|
import { subscribeToAuthChanges } from "@/lib/auth-change";
|
||||||
|
|
||||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
useEffect(() => subscribeToAuthChanges(), []);
|
||||||
return (
|
return (
|
||||||
<JotaiProvider>
|
<JotaiProvider>
|
||||||
<QueryProvider>
|
<QueryProvider>
|
||||||
|
|||||||
@@ -243,8 +243,13 @@ function FilterLineRow({
|
|||||||
className="h-[38px] min-h-[38px] rounded-[4px] border-[#d0d0d0] text-sm"
|
className="h-[38px] min-h-[38px] rounded-[4px] border-[#d0d0d0] text-sm"
|
||||||
spanClassName="text-sm"
|
spanClassName="text-sm"
|
||||||
searchable
|
searchable
|
||||||
|
// Legacy Dropdown search: case-insensitive substring, not fuzzy.
|
||||||
|
searchMatch="contains"
|
||||||
preventDeselect
|
preventDeselect
|
||||||
hideOptionCheck
|
hideOptionCheck
|
||||||
|
// Legacy QuestionSelect tooltip: full title on hover.
|
||||||
|
optionTooltip="singleLine"
|
||||||
|
optionTooltipClassName="opacity-65"
|
||||||
onChange={(qid) => {
|
onChange={(qid) => {
|
||||||
const selected = questions.find((item) => item.qid === qid);
|
const selected = questions.find((item) => item.qid === qid);
|
||||||
if (!selected) return;
|
if (!selected) return;
|
||||||
@@ -302,6 +307,11 @@ function FilterLineRow({
|
|||||||
badgeClassName="text-xs"
|
badgeClassName="text-xs"
|
||||||
maxSelected={multi ? undefined : 1}
|
maxSelected={multi ? undefined : 1}
|
||||||
hideSelectAll={!multi}
|
hideSelectAll={!multi}
|
||||||
|
// Legacy ValueSelect search: case-insensitive substring.
|
||||||
|
searchMatch="contains"
|
||||||
|
// Legacy ValueSelect tooltip: full label on hover.
|
||||||
|
optionTooltip="singleLine"
|
||||||
|
optionTooltipClassName="opacity-65"
|
||||||
onChange={(next) => {
|
onChange={(next) => {
|
||||||
// Legacy keeps codes sorted and comma-joined.
|
// Legacy keeps codes sorted and comma-joined.
|
||||||
const value = [...next].sort().join(",");
|
const value = [...next].sort().join(",");
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { atom, useAtom, useAtomValue } from "jotai";
|
||||||
|
import type { SetStateAction } from "react";
|
||||||
import type { LoginUser } from "@kri/common";
|
import type { LoginUser } from "@kri/common";
|
||||||
import { isRecord, isLoginUser } from "@/types/kart";
|
import { isRecord, isLoginUser } from "@/types/kart";
|
||||||
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
|
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
|
||||||
@@ -10,25 +11,27 @@ import {
|
|||||||
getLocalStorage,
|
getLocalStorage,
|
||||||
removeLocalStorage,
|
removeLocalStorage,
|
||||||
setLocalStorage,
|
setLocalStorage,
|
||||||
|
getSessionStorage,
|
||||||
|
setSessionStorage,
|
||||||
|
removeSessionStorage,
|
||||||
} from "@/store/storage/secure-storage";
|
} from "@/store/storage/secure-storage";
|
||||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||||
import { isExternalSession, isExternalUser, type ShareLink } from "@/types/share";
|
import { isExternalUser, type ShareLink } from "@/types/share";
|
||||||
|
import { isExternalAuth, type ExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
export type AuthState = CommonAuthState<LoginUser> & { external?: ShareLink };
|
export type AuthState = CommonAuthState<LoginUser> & { external?: ShareLink; accessToken?: string; mode?: "external" };
|
||||||
const initialAuthState: AuthState = { user: null };
|
const initialAuthState: AuthState = { user: null };
|
||||||
|
|
||||||
const isPersistedAuthState = (value: unknown): value is AuthState =>
|
const isPersistedAuthState = (value: unknown): value is AuthState =>
|
||||||
isRecord(value) && isLoginUser(value.user) &&
|
isRecord(value) && isLoginUser(value.user) && !isExternalUser(value.user) &&
|
||||||
(isExternalUser(value.user)
|
value.accessToken === undefined && value.external === undefined;
|
||||||
? isExternalSession({ user: value.user, link: value.external })
|
|
||||||
: value.external === undefined);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
|
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
|
||||||
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
|
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
|
||||||
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
|
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
|
||||||
*/
|
*/
|
||||||
export const authStateAtom = createPersistentAtom<AuthState>(
|
const normalAuthStateAtom = createPersistentAtom<AuthState>(
|
||||||
StorageKeys.AuthState,
|
StorageKeys.AuthState,
|
||||||
initialAuthState,
|
initialAuthState,
|
||||||
{
|
{
|
||||||
@@ -43,6 +46,48 @@ export const authStateAtom = createPersistentAtom<AuthState>(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const sessionStorage = { get: getSessionStorage, set: setSessionStorage, remove: removeSessionStorage };
|
||||||
|
const authModeAtom = createPersistentAtom<"normal" | "external">(StorageKeys.AuthMode, "normal", {
|
||||||
|
storage: sessionStorage,
|
||||||
|
validate: (value): value is "normal" | "external" => value === "normal" || value === "external",
|
||||||
|
shouldRemove: (value) => value === "normal",
|
||||||
|
});
|
||||||
|
const externalAuthStateAtom = createPersistentAtom<ExternalAuth | null>(StorageKeys.ExternalAuth, null, {
|
||||||
|
storage: sessionStorage,
|
||||||
|
validate: (value): value is ExternalAuth | null => value === null || isExternalAuth(value),
|
||||||
|
});
|
||||||
|
const emptyExternalAuth: ExternalAuth = { mode: "external", user: null };
|
||||||
|
|
||||||
|
export const authStateAtom = Object.assign(atom(
|
||||||
|
(get): AuthState => {
|
||||||
|
const normal = get(normalAuthStateAtom);
|
||||||
|
const mode = get(authModeAtom);
|
||||||
|
const external = get(externalAuthStateAtom);
|
||||||
|
if (mode === "external") return external ?? emptyExternalAuth;
|
||||||
|
return normal;
|
||||||
|
},
|
||||||
|
(get, set, action: SetStateAction<AuthState>) => {
|
||||||
|
const previous = get(authStateAtom);
|
||||||
|
const next = typeof action === "function" ? action(previous) : action;
|
||||||
|
if (next.mode === "external" || isExternalUser(next.user)) {
|
||||||
|
set(authModeAtom, "external");
|
||||||
|
set(externalAuthStateAtom, { ...next, mode: "external" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!next.user && previous.mode === "external") {
|
||||||
|
set(authModeAtom, "external");
|
||||||
|
set(externalAuthStateAtom, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
set(authModeAtom, "normal");
|
||||||
|
set(externalAuthStateAtom, null);
|
||||||
|
set(normalAuthStateAtom, { user: next.user });
|
||||||
|
},
|
||||||
|
), {
|
||||||
|
hydratedAtom: atom((get) => get(normalAuthStateAtom.hydratedAtom) &&
|
||||||
|
get(authModeAtom.hydratedAtom) && get(externalAuthStateAtom.hydratedAtom)),
|
||||||
|
});
|
||||||
|
|
||||||
export function useAuth() {
|
export function useAuth() {
|
||||||
const [auth, setAuth] = useAtom(authStateAtom);
|
const [auth, setAuth] = useAtom(authStateAtom);
|
||||||
const hydrated = useAtomValue(authStateAtom.hydratedAtom);
|
const hydrated = useAtomValue(authStateAtom.hydratedAtom);
|
||||||
|
|||||||
85
src/hooks/useAuthSession.ts
Normal file
85
src/hooks/useAuthSession.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useAtomValue, useStore } from "jotai";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { apiError } from "@kri/common/http";
|
||||||
|
import { authStateAtom, useAuth } from "@/hooks/useAuth";
|
||||||
|
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||||
|
import { authApi } from "@/lib/http-client";
|
||||||
|
import { isLoginUser } from "@/types/kart";
|
||||||
|
import { isExternalSession, isExternalUser } from "@/types/share";
|
||||||
|
|
||||||
|
const SESSION_QUERY_KEY = ["auth-session"] as const;
|
||||||
|
|
||||||
|
export function useAuthSession() {
|
||||||
|
const store = useStore();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const router = useRouter();
|
||||||
|
const { setAuth, hydrated } = useAuth();
|
||||||
|
useAtomValue(selectedProjectAtom);
|
||||||
|
const projectHydrated = useAtomValue(selectedProjectAtom.hydratedAtom);
|
||||||
|
const otherQueries = { predicate: (query: { queryKey: readonly unknown[] }) => query.queryKey[0] !== SESSION_QUERY_KEY[0] };
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const refresh = () => {
|
||||||
|
void queryClient.refetchQueries({ queryKey: SESSION_QUERY_KEY, exact: true, type: "active" }, { cancelRefetch: false });
|
||||||
|
};
|
||||||
|
window.addEventListener("focus", refresh);
|
||||||
|
return () => window.removeEventListener("focus", refresh);
|
||||||
|
}, [queryClient]);
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: SESSION_QUERY_KEY,
|
||||||
|
enabled: hydrated && projectHydrated,
|
||||||
|
staleTime: 0,
|
||||||
|
gcTime: 0,
|
||||||
|
retry: false,
|
||||||
|
refetchOnMount: "always",
|
||||||
|
refetchOnWindowFocus: "always",
|
||||||
|
meta: { ignoreGlobalLoading: true },
|
||||||
|
queryFn: async ({ signal }) => {
|
||||||
|
const previous = store.get(authStateAtom);
|
||||||
|
try {
|
||||||
|
const user = await authApi.get<unknown>("/auth/my-info", {
|
||||||
|
cache: "no-store",
|
||||||
|
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
|
||||||
|
headers: previous.mode === "external" ? { Authorization: `Bearer ${previous.accessToken ?? ""}` } : undefined,
|
||||||
|
});
|
||||||
|
signal.throwIfAborted();
|
||||||
|
if (!isLoginUser(user)) throw new Error("Invalid user response");
|
||||||
|
if (previous.mode === "external" && !isExternalSession({ user, link: previous.external })) throw new Error("Invalid link session");
|
||||||
|
if (previous.mode !== "external" && isExternalUser(user)) throw new Error("Invalid normal session");
|
||||||
|
const before = previous.user;
|
||||||
|
const changed = !before || before.userId !== user.userId || before.userRole !== user.userRole ||
|
||||||
|
before.userTeam !== user.userTeam || before.userCmpn !== user.userCmpn;
|
||||||
|
if (changed) {
|
||||||
|
await queryClient.cancelQueries(otherQueries);
|
||||||
|
signal.throwIfAborted();
|
||||||
|
queryClient.removeQueries(otherQueries);
|
||||||
|
queryClient.getMutationCache().clear();
|
||||||
|
if (previous.mode !== "external") {
|
||||||
|
const selected = store.get(selectedProjectAtom);
|
||||||
|
if (selected) store.set(selectedProjectAtom, { ...selected, userId: user.userId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed || before?.userName !== user.userName) setAuth(previous.mode === "external" ? { ...previous, user } : { user });
|
||||||
|
return user;
|
||||||
|
} catch (reason) {
|
||||||
|
signal.throwIfAborted();
|
||||||
|
const status = apiError(reason).status;
|
||||||
|
if (status === 401 || status === 403) {
|
||||||
|
await queryClient.cancelQueries(otherQueries);
|
||||||
|
signal.throwIfAborted();
|
||||||
|
queryClient.removeQueries(otherQueries);
|
||||||
|
queryClient.getMutationCache().clear();
|
||||||
|
store.set(selectedProjectAtom, null);
|
||||||
|
setAuth({ user: null });
|
||||||
|
router.replace(previous.mode === "external" ? "/logout" : "/login");
|
||||||
|
}
|
||||||
|
throw reason;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
54
src/hooks/useProjectNavigation.ts
Normal file
54
src/hooks/useProjectNavigation.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useRef } from "react";
|
||||||
|
import { atom, useAtomValue, useStore } from "jotai";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import type { Route } from "next";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { authStateAtom } from "@/hooks/useAuth";
|
||||||
|
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||||
|
import { cancelPreviousProjectQueries, checkProjectAccess } from "@/query/project";
|
||||||
|
import { announceProjectAccess, projectAccessMessage } from "@/lib/project-access";
|
||||||
|
import { isExternalUser } from "@/types/share";
|
||||||
|
import type { ProjectRef } from "@/types/kart";
|
||||||
|
|
||||||
|
// Both the overview and header share one selection lock in this Jotai provider.
|
||||||
|
export const projectSelectionAtom = atom({ id: 0, pending: false });
|
||||||
|
|
||||||
|
export function useProjectNavigation() {
|
||||||
|
const store = useStore();
|
||||||
|
const router = useRouter();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const selection = useAtomValue(projectSelectionAtom);
|
||||||
|
const request = useRef<number | null>(null);
|
||||||
|
useEffect(() => () => {
|
||||||
|
if (request.current === store.get(projectSelectionAtom).id)
|
||||||
|
store.set(projectSelectionAtom, (value) => ({ id: value.id + 1, pending: false }));
|
||||||
|
}, [store]);
|
||||||
|
|
||||||
|
const navigate = useCallback(async (project: ProjectRef, path: Route) => {
|
||||||
|
const auth = store.get(authStateAtom);
|
||||||
|
if (!auth.user || isExternalUser(auth.user) || store.get(projectSelectionAtom).pending) return;
|
||||||
|
const id = store.get(projectSelectionAtom).id + 1;
|
||||||
|
request.current = id;
|
||||||
|
store.set(projectSelectionAtom, { id, pending: true });
|
||||||
|
const current = () => store.get(projectSelectionAtom).id === id && store.get(authStateAtom) === auth;
|
||||||
|
try {
|
||||||
|
await checkProjectAccess(project);
|
||||||
|
if (!current()) return;
|
||||||
|
await cancelPreviousProjectQueries(queryClient, auth.user, store.get(selectedProjectAtom), project);
|
||||||
|
if (!current()) return;
|
||||||
|
store.set(selectedProjectAtom, { userId: auth.user.userId, project: { projectType: project.projectType, pkey: project.pkey } });
|
||||||
|
announceProjectAccess({ project, allowed: true });
|
||||||
|
router.push(path);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
if (current()) toast.error(projectAccessMessage(error));
|
||||||
|
} finally {
|
||||||
|
if (store.get(projectSelectionAtom).id === id)
|
||||||
|
store.set(projectSelectionAtom, { id, pending: false });
|
||||||
|
}
|
||||||
|
}, [store, router, queryClient]);
|
||||||
|
|
||||||
|
return { navigate, pending: selection.pending };
|
||||||
|
}
|
||||||
17
src/hooks/useResetSession.ts
Normal file
17
src/hooks/useResetSession.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useSetAtom } from "jotai";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
||||||
|
|
||||||
|
/** Clear cached queries and the selected project before applying a new identity. */
|
||||||
|
export function useResetSession() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const setProject = useSetAtom(selectedProjectAtom);
|
||||||
|
return useCallback(async () => {
|
||||||
|
await queryClient.cancelQueries();
|
||||||
|
queryClient.clear();
|
||||||
|
setProject(null);
|
||||||
|
}, [queryClient, setProject]);
|
||||||
|
}
|
||||||
@@ -1,19 +1,17 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect } from "react";
|
import { useCallback } from "react";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { useAtom, useAtomValue } from "jotai";
|
||||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
|
||||||
import type { Route } from "next";
|
|
||||||
import { createPersistentAtom } from "@kri/common/jotai";
|
import { createPersistentAtom } from "@kri/common/jotai";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { isExternalUser } from "@/types/share";
|
import { isExternalUser } from "@/types/share";
|
||||||
import {
|
import {
|
||||||
getLocalStorage,
|
getSessionStorage,
|
||||||
removeLocalStorage,
|
removeSessionStorage,
|
||||||
setLocalStorage,
|
setSessionStorage,
|
||||||
} from "@/store/storage/secure-storage";
|
} from "@/store/storage/secure-storage";
|
||||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||||
import { isProjectRef, isRecord, readProjectParams, type ProjectRef } from "@/types/kart";
|
import { isProjectRef, isRecord, type ProjectRef } from "@/types/kart";
|
||||||
|
|
||||||
/** The project chosen for the project pages, owned by the user who chose it. */
|
/** The project chosen for the project pages, owned by the user who chose it. */
|
||||||
export type SelectedProject = { userId: string; project: ProjectRef } | null;
|
export type SelectedProject = { userId: string; project: ProjectRef } | null;
|
||||||
@@ -25,19 +23,15 @@ const isSelectedProject = (value: unknown): value is SelectedProject =>
|
|||||||
value.userId !== "" &&
|
value.userId !== "" &&
|
||||||
isProjectRef(value.project));
|
isProjectRef(value.project));
|
||||||
|
|
||||||
/**
|
/** Each tab owns its selection. */
|
||||||
* Legacy KART kept the selected project in ptokenState (recoil-persist, localStorage) instead of
|
|
||||||
* the URL. Like authStateAtom, the stored value is applied after mount, so server and first
|
|
||||||
* client renders agree.
|
|
||||||
*/
|
|
||||||
export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
||||||
StorageKeys.SelectedProject,
|
StorageKeys.SelectedProject,
|
||||||
null,
|
null,
|
||||||
{
|
{
|
||||||
storage: {
|
storage: {
|
||||||
get: getLocalStorage,
|
get: getSessionStorage,
|
||||||
set: setLocalStorage,
|
set: setSessionStorage,
|
||||||
remove: removeLocalStorage,
|
remove: removeSessionStorage,
|
||||||
},
|
},
|
||||||
validate: isSelectedProject,
|
validate: isSelectedProject,
|
||||||
shouldRemove: (value) => value === null,
|
shouldRemove: (value) => value === null,
|
||||||
@@ -46,16 +40,14 @@ export const selectedProjectAtom = createPersistentAtom<SelectedProject>(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Current project for the signed-in user. An old `?projectType=&pkey=` link takes precedence
|
* Current project for the signed-in user. Incoming address parameters are applied only
|
||||||
* until ProjectParamsMigration stores it and removes the parameters from the address.
|
* after ProjectEntry verifies normal-user access; External scope comes from the link.
|
||||||
*/
|
*/
|
||||||
export function useSelectedProject() {
|
export function useSelectedProject() {
|
||||||
const { auth, hydrated: authHydrated } = useAuth();
|
const { auth, hydrated: authHydrated } = useAuth();
|
||||||
const [selected, setSelected] = useAtom(selectedProjectAtom);
|
const [selected, setSelected] = useAtom(selectedProjectAtom);
|
||||||
const storeHydrated = useAtomValue(selectedProjectAtom.hydratedAtom);
|
const storeHydrated = useAtomValue(selectedProjectAtom.hydratedAtom);
|
||||||
const urlProject = readProjectParams(useSearchParams());
|
|
||||||
const external = isExternalUser(auth.user);
|
const external = isExternalUser(auth.user);
|
||||||
const fromUrl = external ? null : urlProject;
|
|
||||||
const userId = auth.user?.userId;
|
const userId = auth.user?.userId;
|
||||||
const stored =
|
const stored =
|
||||||
selected && userId && selected.userId === userId
|
selected && userId && selected.userId === userId
|
||||||
@@ -73,30 +65,10 @@ export function useSelectedProject() {
|
|||||||
);
|
);
|
||||||
const clear = useCallback(() => setSelected(null), [setSelected]);
|
const clear = useCallback(() => setSelected(null), [setSelected]);
|
||||||
return {
|
return {
|
||||||
project: external ? auth.external ?? null : fromUrl ?? stored,
|
project: external ? auth.external ?? null : stored,
|
||||||
fromUrl,
|
|
||||||
/** False until both the login state and the stored selection have been read. */
|
/** False until both the login state and the stored selection have been read. */
|
||||||
hydrated: authHydrated && storeHydrated,
|
hydrated: authHydrated && storeHydrated,
|
||||||
select,
|
select,
|
||||||
clear,
|
clear,
|
||||||
} as const;
|
} as const;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Old bookmarks and shared links still carry `?projectType=&pkey=`: store that project and
|
|
||||||
* replace the address with the bare path. Mounted once in the app header.
|
|
||||||
*/
|
|
||||||
export function useProjectParamsMigration() {
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
const { auth, hydrated } = useAuth();
|
|
||||||
const { fromUrl, select } = useSelectedProject();
|
|
||||||
const projectType = fromUrl?.projectType;
|
|
||||||
const pkey = fromUrl?.pkey;
|
|
||||||
const signedIn = hydrated && !!auth.user;
|
|
||||||
useEffect(() => {
|
|
||||||
if (!signedIn || projectType === undefined || pkey === undefined) return;
|
|
||||||
select({ projectType, pkey });
|
|
||||||
router.replace(pathname as Route);
|
|
||||||
}, [signedIn, projectType, pkey, select, router, pathname]);
|
|
||||||
}
|
|
||||||
|
|||||||
36
src/lib/auth-change.ts
Normal file
36
src/lib/auth-change.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { readExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
|
// Set false to disable only cross-tab notifications and their listener.
|
||||||
|
const AUTH_CHANGE_SYNC_ENABLED = true;
|
||||||
|
const CHANNEL = "kart:internal-auth-change";
|
||||||
|
let channel: BroadcastChannel | undefined;
|
||||||
|
|
||||||
|
function authChannel() {
|
||||||
|
if (!AUTH_CHANGE_SYNC_ENABLED || typeof BroadcastChannel === "undefined") return;
|
||||||
|
try {
|
||||||
|
return channel ??= new BroadcastChannel(CHANNEL);
|
||||||
|
} catch {
|
||||||
|
// Cross-tab sync is optional when the browser disallows messaging.
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function notifyAuthChange(path: "/" | "/login") {
|
||||||
|
authChannel()?.postMessage(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeToAuthChanges() {
|
||||||
|
const listener = authChannel();
|
||||||
|
if (!listener) return;
|
||||||
|
listener.onmessage = (event: MessageEvent<unknown>) => {
|
||||||
|
// A normal-login change must not navigate an independently authenticated link tab.
|
||||||
|
if (readExternalAuth()) return;
|
||||||
|
if (event.data !== "/" && event.data !== "/login") return;
|
||||||
|
// A full navigation discards this tab's cache/state without clearing the new cookie.
|
||||||
|
window.location.replace(event.data);
|
||||||
|
};
|
||||||
|
return () => {
|
||||||
|
listener.close();
|
||||||
|
channel = undefined;
|
||||||
|
};
|
||||||
|
}
|
||||||
33
src/lib/auth-cookie.ts
Normal file
33
src/lib/auth-cookie.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
|
||||||
|
import { serverEnv } from "@/lib/env.server";
|
||||||
|
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||||
|
|
||||||
|
/** Issue/renew the normal-login cookie, or expire it when the token is empty. */
|
||||||
|
export function setAuthCookie(response: NextResponse, token: string): void {
|
||||||
|
const production = serverEnv.ENV === "prod";
|
||||||
|
const domain = serverEnv.AUTH_COOKIE_DOMAIN;
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: production,
|
||||||
|
sameSite: "lax" as const,
|
||||||
|
path: "/",
|
||||||
|
};
|
||||||
|
// Serialize each cookie separately: ResponseCookies indexes cookies by name,
|
||||||
|
// so setting the shared and host-only variants on one instance loses a header.
|
||||||
|
const append = (value: string, cookieDomain: string | undefined, maxAge: number) => {
|
||||||
|
const cookieResponse = new NextResponse(null);
|
||||||
|
cookieResponse.cookies.set(CookieKeys.AuthToken, value, {
|
||||||
|
...options,
|
||||||
|
...(cookieDomain ? { domain: cookieDomain } : {}),
|
||||||
|
maxAge,
|
||||||
|
});
|
||||||
|
for (const header of cookieResponse.headers.getSetCookie())
|
||||||
|
response.headers.append("Set-Cookie", header);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (domain) append("", undefined, 0);
|
||||||
|
append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0);
|
||||||
|
}
|
||||||
@@ -4,4 +4,8 @@ import { createEnv, env } from "@kri/common/config";
|
|||||||
export const serverEnv = createEnv({
|
export const serverEnv = createEnv({
|
||||||
ENV: env.required("ENV", process.env.ENV),
|
ENV: env.required("ENV", process.env.ENV),
|
||||||
API_SERVER: env.required("API_SERVER", process.env.API_SERVER),
|
API_SERVER: env.required("API_SERVER", process.env.API_SERVER),
|
||||||
|
AUTH_COOKIE_DOMAIN: env.optional(
|
||||||
|
"AUTH_COOKIE_DOMAIN",
|
||||||
|
process.env.AUTH_COOKIE_DOMAIN,
|
||||||
|
),
|
||||||
});
|
});
|
||||||
|
|||||||
29
src/lib/external-auth.ts
Normal file
29
src/lib/external-auth.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { LoginUser } from "@kri/common";
|
||||||
|
import { getSessionStorage } from "@/store/storage/secure-storage";
|
||||||
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||||
|
import { isRecord } from "@/types/kart";
|
||||||
|
import { isExternalSession, type ShareLink } from "@/types/share";
|
||||||
|
|
||||||
|
export type ExternalAuth = {
|
||||||
|
mode: "external";
|
||||||
|
user: LoginUser | null;
|
||||||
|
external?: ShareLink;
|
||||||
|
accessToken?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isExternalAuth(value: unknown): value is ExternalAuth {
|
||||||
|
if (!isRecord(value) || value.mode !== "external") return false;
|
||||||
|
if (value.user === null) return value.external === undefined && value.accessToken === undefined;
|
||||||
|
return isExternalSession({ user: value.user, link: value.external }) &&
|
||||||
|
(value.accessToken === undefined || typeof value.accessToken === "string");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The mode survives missing/invalid token data so requests never fall back to the normal cookie. */
|
||||||
|
export function readExternalAuth(): ExternalAuth | null {
|
||||||
|
if (getSessionStorage(StorageKeys.AuthMode) !== "external") return null;
|
||||||
|
const value = getSessionStorage(StorageKeys.ExternalAuth);
|
||||||
|
if (isExternalAuth(value)) return value;
|
||||||
|
return { mode: "external", user: null };
|
||||||
|
}
|
||||||
220
src/lib/filter-expression.ts
Normal file
220
src/lib/filter-expression.ts
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
import type { ReportFilter } from "@/types/report";
|
||||||
|
|
||||||
|
type Token = { text: string; position: number } & (
|
||||||
|
| { kind: "word" | "symbol" | "end" }
|
||||||
|
| { kind: "value"; value: string | number }
|
||||||
|
);
|
||||||
|
|
||||||
|
const fail = (position: number, message: string): never => {
|
||||||
|
throw new Error(`필터 ${position + 1}번째 문자: ${message}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A bounded expression grammar, never SQL or JavaScript execution. */
|
||||||
|
function tokenize(source: string): Token[] {
|
||||||
|
if (source.length > 8192) fail(0, "조건식은 8192자 이내로 작성해 주세요.");
|
||||||
|
const tokens: Token[] = [];
|
||||||
|
let position = 0;
|
||||||
|
while (position < source.length) {
|
||||||
|
if (/\s/.test(source[position])) {
|
||||||
|
position++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (tokens.length >= 2048) fail(position, "조건식이 너무 복잡합니다.");
|
||||||
|
const start = position;
|
||||||
|
const char = source[position];
|
||||||
|
if (char === "'" || char === '"') {
|
||||||
|
position++;
|
||||||
|
let value = "",
|
||||||
|
closed = false;
|
||||||
|
while (position < source.length) {
|
||||||
|
const next = source[position++];
|
||||||
|
if (next !== char) {
|
||||||
|
value += next;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (source[position] === char) {
|
||||||
|
value += char;
|
||||||
|
position++;
|
||||||
|
} else {
|
||||||
|
closed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!closed) fail(start, "문자열의 닫는 따옴표가 필요합니다.");
|
||||||
|
tokens.push({
|
||||||
|
kind: "value",
|
||||||
|
text: source.slice(start, position),
|
||||||
|
value,
|
||||||
|
position: start,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const rest = source.slice(position);
|
||||||
|
const number = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest);
|
||||||
|
if (number) {
|
||||||
|
const value = Number(number[0]);
|
||||||
|
if (
|
||||||
|
!Number.isFinite(value) ||
|
||||||
|
(Number.isInteger(value) && !Number.isSafeInteger(value))
|
||||||
|
)
|
||||||
|
fail(
|
||||||
|
start,
|
||||||
|
"숫자 범위를 확인해 주세요. 큰 코드값은 따옴표로 감싸 주세요.",
|
||||||
|
);
|
||||||
|
tokens.push({ kind: "value", text: number[0], value, position: start });
|
||||||
|
position += number[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest);
|
||||||
|
const symbol = /^(?:>=|<=|<>|!=|[=><(),])/.exec(rest);
|
||||||
|
const match = word ?? symbol;
|
||||||
|
if (!match)
|
||||||
|
return fail(
|
||||||
|
start,
|
||||||
|
"지원하지 않는 문자입니다. 문항 ID, 비교식, AND·OR·괄호를 사용해 주세요.",
|
||||||
|
);
|
||||||
|
tokens.push({
|
||||||
|
kind: word ? "word" : "symbol",
|
||||||
|
text: match[0],
|
||||||
|
position: start,
|
||||||
|
});
|
||||||
|
position += match[0].length;
|
||||||
|
}
|
||||||
|
tokens.push({ kind: "end", text: "", position });
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Precedence: parentheses, NOT, AND, OR. Identifiers refer to QIDs. */
|
||||||
|
export function parseFilterExpression(source: string): ReportFilter | null {
|
||||||
|
const tokens = tokenize(source);
|
||||||
|
let cursor = 0;
|
||||||
|
const peek = () => tokens[cursor];
|
||||||
|
const take = (text: string) => {
|
||||||
|
const token = peek();
|
||||||
|
if (token.kind !== "value" && token.text.toUpperCase() === text) {
|
||||||
|
cursor++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
const expect = (text: string) => {
|
||||||
|
if (!take(text)) fail(peek().position, `${text} 토큰이 필요합니다.`);
|
||||||
|
};
|
||||||
|
const value = (): string | number => {
|
||||||
|
const token = peek();
|
||||||
|
if (token.kind !== "value")
|
||||||
|
return fail(
|
||||||
|
token.position,
|
||||||
|
"비교할 숫자 또는 따옴표로 감싼 문자열이 필요합니다.",
|
||||||
|
);
|
||||||
|
cursor++;
|
||||||
|
return token.value;
|
||||||
|
};
|
||||||
|
const group = (
|
||||||
|
operator: "AND" | "OR",
|
||||||
|
children: ReportFilter[],
|
||||||
|
): ReportFilter =>
|
||||||
|
children.length === 1 ? children[0] : { operator, children };
|
||||||
|
|
||||||
|
function condition(): ReportFilter {
|
||||||
|
const id = peek();
|
||||||
|
if (
|
||||||
|
id.kind !== "word" ||
|
||||||
|
/^(AND|OR|NOT|IN|BETWEEN|IS|NULL)$/i.test(id.text)
|
||||||
|
)
|
||||||
|
return fail(id.position, "비교할 문항 ID가 필요합니다.");
|
||||||
|
cursor++;
|
||||||
|
const base = { dimensionId: id.text, reference: "QID" as const };
|
||||||
|
if (take("IS")) {
|
||||||
|
const not = take("NOT");
|
||||||
|
expect("NULL");
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
operator: not ? "IS_ANSWERED" : "IS_UNANSWERED",
|
||||||
|
values: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const not = take("NOT");
|
||||||
|
if (take("IN")) {
|
||||||
|
expect("(");
|
||||||
|
const values = [value()];
|
||||||
|
while (take(",")) {
|
||||||
|
if (values.length >= 128)
|
||||||
|
fail(peek().position, "IN 목록은 128개 이내로 작성해 주세요.");
|
||||||
|
values.push(value());
|
||||||
|
}
|
||||||
|
expect(")");
|
||||||
|
return { ...base, operator: not ? "NOT_IN" : "IN", values };
|
||||||
|
}
|
||||||
|
if (take("BETWEEN")) {
|
||||||
|
const low = value();
|
||||||
|
expect("AND");
|
||||||
|
const result: ReportFilter = {
|
||||||
|
...base,
|
||||||
|
operator: "BETWEEN",
|
||||||
|
values: [low, value()],
|
||||||
|
};
|
||||||
|
return not ? { operator: "NOT", children: [result] } : result;
|
||||||
|
}
|
||||||
|
if (not)
|
||||||
|
return fail(peek().position, "NOT 뒤에는 IN 또는 BETWEEN이 필요합니다.");
|
||||||
|
const token = peek();
|
||||||
|
const operators: Record<string, ReportFilter["operator"]> = {
|
||||||
|
"=": "EQ",
|
||||||
|
"!=": "NE",
|
||||||
|
"<>": "NE",
|
||||||
|
">": "GT",
|
||||||
|
">=": "GE",
|
||||||
|
"<": "LT",
|
||||||
|
"<=": "LE",
|
||||||
|
};
|
||||||
|
const operator =
|
||||||
|
token.kind === "symbol" ? operators[token.text] : undefined;
|
||||||
|
if (!operator)
|
||||||
|
return fail(
|
||||||
|
token.position,
|
||||||
|
"비교 연산자(=, !=, <>, >, >=, <, <=, IN 등)가 필요합니다.",
|
||||||
|
);
|
||||||
|
cursor++;
|
||||||
|
return { ...base, operator, values: [value()] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function primary(depth: number): ReportFilter {
|
||||||
|
if (depth > 32)
|
||||||
|
return fail(peek().position, "괄호와 NOT은 32단계 이내로 작성해 주세요.");
|
||||||
|
if (take("NOT")) return { operator: "NOT", children: [primary(depth + 1)] };
|
||||||
|
if (!take("(")) return condition();
|
||||||
|
const result = expression(depth + 1);
|
||||||
|
expect(")");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
function and(depth: number): ReportFilter {
|
||||||
|
const children = [primary(depth)];
|
||||||
|
while (take("AND")) {
|
||||||
|
if (children.length >= 128)
|
||||||
|
fail(
|
||||||
|
peek().position,
|
||||||
|
"AND 조건은 한 그룹에 128개 이내로 작성해 주세요.",
|
||||||
|
);
|
||||||
|
children.push(primary(depth));
|
||||||
|
}
|
||||||
|
return group("AND", children);
|
||||||
|
}
|
||||||
|
function expression(depth: number): ReportFilter {
|
||||||
|
const children = [and(depth)];
|
||||||
|
while (take("OR")) {
|
||||||
|
if (children.length >= 128)
|
||||||
|
fail(
|
||||||
|
peek().position,
|
||||||
|
"OR 조건은 한 그룹에 128개 이내로 작성해 주세요.",
|
||||||
|
);
|
||||||
|
children.push(and(depth));
|
||||||
|
}
|
||||||
|
return group("OR", children);
|
||||||
|
}
|
||||||
|
if (peek().kind === "end") return null;
|
||||||
|
const result = expression(0);
|
||||||
|
if (peek().kind !== "end")
|
||||||
|
fail(peek().position, "조건 사이의 AND·OR 또는 괄호를 확인해 주세요.");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { createHttpClient } from "@kri/common/http";
|
import { apiError, createHttpClient, HttpError, redirectToLogout } from "@kri/common/http";
|
||||||
import { clientEnv } from "@/lib/env.client";
|
import { clientEnv } from "@/lib/env.client";
|
||||||
|
import { announceProjectAccess, projectFromRequest } from "@/lib/project-access";
|
||||||
|
import { readExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
const resolveBaseUrl = () =>
|
const resolveBaseUrl = () =>
|
||||||
typeof window === "undefined"
|
typeof window === "undefined"
|
||||||
@@ -7,6 +9,31 @@ const resolveBaseUrl = () =>
|
|||||||
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
: new URL(clientEnv.API_BASE, window.location.origin).toString();
|
||||||
|
|
||||||
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
export const nextApi = createHttpClient(resolveBaseUrl(), {
|
||||||
|
getToken: () => {
|
||||||
|
const external = readExternalAuth();
|
||||||
|
if (!external) return null;
|
||||||
|
if (!external.accessToken) {
|
||||||
|
redirectToLogout();
|
||||||
|
throw new HttpError(401, { message: "공유 링크 인증이 필요합니다." }, "");
|
||||||
|
}
|
||||||
|
return external.accessToken;
|
||||||
|
},
|
||||||
|
onForbidden: (error) => {
|
||||||
|
const info = apiError(error);
|
||||||
|
if (readExternalAuth() || info.code === "EXTERNAL_SCOPE_DENIED" || info.code === "PROJECT_IDENTITY_REQUIRED") {
|
||||||
|
redirectToLogout();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const project = projectFromRequest(error.url);
|
||||||
|
if (info.code === "PROJECT_ACCESS_DENIED" && project && !new URL(error.url).pathname.endsWith("/access"))
|
||||||
|
announceProjectAccess({ project, allowed: false, message: info.message });
|
||||||
|
},
|
||||||
|
onResponseError: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Login/logout BFF operations must also work before an External JWT is available.
|
||||||
|
export const authApi = createHttpClient(resolveBaseUrl(), {
|
||||||
|
onUnauthorized: false,
|
||||||
onForbidden: false,
|
onForbidden: false,
|
||||||
onResponseError: false,
|
onResponseError: false,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
import { cookies } from "next/headers";
|
import { cookies, headers } from "next/headers";
|
||||||
import { createHttpClient } from "@kri/common/http";
|
import { createHttpClient } from "@kri/common/http";
|
||||||
import { serverEnv } from "@/lib/env.server";
|
import { serverEnv } from "@/lib/env.server";
|
||||||
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
import { CookieKeys } from "@/store/cookie/cookie-keys";
|
||||||
|
|
||||||
|
export async function getServerAccessToken(): Promise<string | null> {
|
||||||
|
const authorization = (await headers()).get("authorization");
|
||||||
|
// Explicit credentials take precedence even when malformed; never use the normal
|
||||||
|
// cookie as a fallback for an External request. The backend verifies the JWT.
|
||||||
|
if (authorization !== null) return /^Bearer ([^\s]+)$/i.exec(authorization)?.[1] ?? null;
|
||||||
|
return (await cookies()).get(CookieKeys.AuthToken)?.value ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
export async function createServerApi(authenticated = true) {
|
export async function createServerApi(authenticated = true) {
|
||||||
const cookieStore = await cookies();
|
let accessToken: string | null = null;
|
||||||
const accessToken = authenticated ? cookieStore.get(CookieKeys.AuthToken)?.value ?? null : null;
|
if (authenticated) accessToken = await getServerAccessToken();
|
||||||
return createHttpClient(serverEnv.API_SERVER, {
|
return createHttpClient(serverEnv.API_SERVER, {
|
||||||
getToken: () => accessToken,
|
getToken: () => accessToken,
|
||||||
defaultHeaders: { "content-type": "application/json" },
|
defaultHeaders: { "content-type": "application/json" },
|
||||||
@@ -14,3 +22,13 @@ export async function createServerApi(authenticated = true) {
|
|||||||
onResponseError: false,
|
onResponseError: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Internal integrations authenticate with their supplied key, never the browser session. */
|
||||||
|
export function createServerApiWithApiKey(apiKey: string) {
|
||||||
|
return createHttpClient(serverEnv.API_SERVER, {
|
||||||
|
defaultHeaders: { "content-type": "application/json", "X-API-Key": apiKey },
|
||||||
|
onUnauthorized: false,
|
||||||
|
onForbidden: false,
|
||||||
|
onResponseError: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
116
src/lib/kric-internal-policy.ts
Normal file
116
src/lib/kric-internal-policy.ts
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
import {
|
||||||
|
exportTarget,
|
||||||
|
isQuotaListPath,
|
||||||
|
isQuotaResultPath,
|
||||||
|
isReportStreamPath,
|
||||||
|
isProjectReadPath,
|
||||||
|
projectReadQuery,
|
||||||
|
} from "@/lib/project-proxy-policy";
|
||||||
|
import { isRecord, validDateRange } from "@/types/kart";
|
||||||
|
import { readReportBatch } from "@/lib/report-contract";
|
||||||
|
import { parseFilterExpression } from "@/lib/filter-expression";
|
||||||
|
import { reportUrl } from "@/types/share";
|
||||||
|
|
||||||
|
type Target = {
|
||||||
|
path: string;
|
||||||
|
kind: "list" | "projects" | "quota" | "report" | "excel" | "respondent" | "share";
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Linked lookup only: without all three keys the server would list the API key owner's projects. */
|
||||||
|
export function readInternalProjectListQuery(search: URLSearchParams) {
|
||||||
|
const query = projectReadQuery(["list"], search);
|
||||||
|
if (
|
||||||
|
!["0", "1"].includes(query.projectType ?? "") ||
|
||||||
|
!query.intranetCode?.trim() ||
|
||||||
|
!query.userTeam?.trim()
|
||||||
|
)
|
||||||
|
throw new Error("projectType(0|1), intranetCode, userTeam을 함께 입력해 주세요.");
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** URL Copy only: the server resolves the project from the authenticated path. */
|
||||||
|
export function readInternalShareRequest(value: unknown) {
|
||||||
|
if (!isRecord(value) || value.mode !== "U")
|
||||||
|
throw new Error("URL Copy 요청은 mode를 U로 지정해 주세요.");
|
||||||
|
const realUrl = reportUrl(value.realUrl);
|
||||||
|
if (!realUrl) throw new Error("공유할 보고서 화면 경로를 확인해 주세요.");
|
||||||
|
return { realUrl, mode: "U" as const };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adapt integration input to the existing report contract without coupling the parser to HTTP. */
|
||||||
|
export function readInternalReportBatch(value: unknown) {
|
||||||
|
return readReportBatch(
|
||||||
|
isRecord(value) && typeof value.filter === "string"
|
||||||
|
? { ...value, filter: parseFilterExpression(value.filter) }
|
||||||
|
: value,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fixed integration operations only; no arbitrary upstream forwarding. */
|
||||||
|
export function internalTarget(method: string, slug: string[]): Target | null {
|
||||||
|
const [area, ...parts] = slug;
|
||||||
|
const path = "/" + slug.map(encodeURIComponent).join("/");
|
||||||
|
if (method === "GET" && area === "quota" && isQuotaListPath(parts))
|
||||||
|
return { path, kind: "list" };
|
||||||
|
if (method === "GET" && area === "project" && parts.length === 1 && parts[0] === "list")
|
||||||
|
return { path, kind: "projects" };
|
||||||
|
if (method !== "POST") return null;
|
||||||
|
if (
|
||||||
|
area === "project" &&
|
||||||
|
parts.length === 3 &&
|
||||||
|
parts[2] === "share" &&
|
||||||
|
isProjectReadPath([parts[0], parts[1], "question", "list"])
|
||||||
|
)
|
||||||
|
return { path, kind: "share" };
|
||||||
|
if (
|
||||||
|
area === "project" &&
|
||||||
|
parts.length === 6 &&
|
||||||
|
parts[2] === "derived" &&
|
||||||
|
parts[3] === "respondent" &&
|
||||||
|
parts[5] === "recalculate" &&
|
||||||
|
isProjectReadPath([parts[0], parts[1], "question", "list"])
|
||||||
|
) {
|
||||||
|
const id = parts[4];
|
||||||
|
if (
|
||||||
|
id.trim() &&
|
||||||
|
id.length <= 512 &&
|
||||||
|
id !== "." &&
|
||||||
|
id !== ".." &&
|
||||||
|
!/[\/\\]/.test(id) &&
|
||||||
|
!Array.from(id).some(
|
||||||
|
(char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return { path, kind: "respondent" };
|
||||||
|
}
|
||||||
|
if (area === "project" && isReportStreamPath(parts))
|
||||||
|
return { path, kind: "report" };
|
||||||
|
if (area === "quota" && isQuotaResultPath(parts))
|
||||||
|
return { path, kind: "quota" };
|
||||||
|
if (
|
||||||
|
area === "export" &&
|
||||||
|
parts.length === 3 &&
|
||||||
|
["table", "quota"].includes(parts[2])
|
||||||
|
) {
|
||||||
|
const target = exportTarget("POST", parts);
|
||||||
|
if (target) return { path: target.path, kind: "excel" };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Broader backend quota contract, without changing the ordinary screen's request policy. */
|
||||||
|
export function readInternalQuotaRequest(value: unknown) {
|
||||||
|
if (!isRecord(value)) throw new Error("쿼터 조회 조건을 확인해 주세요.");
|
||||||
|
const dataScope = value.dataScope ?? "ACTUAL";
|
||||||
|
const startDate = value.startDate ?? "";
|
||||||
|
const endDate = value.endDate ?? "";
|
||||||
|
if (
|
||||||
|
!["ACTUAL", "TEST", "ALL"].includes(String(dataScope)) ||
|
||||||
|
typeof dataScope !== "string" ||
|
||||||
|
typeof startDate !== "string" ||
|
||||||
|
typeof endDate !== "string" ||
|
||||||
|
!validDateRange({ startDate, endDate })
|
||||||
|
)
|
||||||
|
throw new Error("쿼터 데이터 범위와 조회 날짜를 확인해 주세요.");
|
||||||
|
return { dataScope, ...(startDate ? { startDate, endDate } : {}) };
|
||||||
|
}
|
||||||
47
src/lib/project-access.ts
Normal file
47
src/lib/project-access.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { apiError } from "@kri/common/http";
|
||||||
|
import { isProjectRef, type ProjectRef } from "@/types/kart";
|
||||||
|
|
||||||
|
export const PROJECT_ACCESS_EVENT = "kart:project-access";
|
||||||
|
export type ProjectAccessEvent = {
|
||||||
|
project: ProjectRef;
|
||||||
|
allowed: boolean;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function announceProjectAccess(detail: ProjectAccessEvent) {
|
||||||
|
if (typeof window !== "undefined")
|
||||||
|
window.dispatchEvent(new CustomEvent(PROJECT_ACCESS_EVENT, { detail }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Match the project in a BFF request, not whichever project is selected later. */
|
||||||
|
export function projectFromRequest(url: string): ProjectRef | null {
|
||||||
|
try {
|
||||||
|
const path = new URL(url, "https://kart.invalid").pathname;
|
||||||
|
const match = path.match(/\/(?:project|quota|derived|bookmark|export|import|share)\/([01])\/([^/]+)(?:\/|$)/);
|
||||||
|
if (!match) return null;
|
||||||
|
const project = { projectType: Number(match[1]), pkey: decodeURIComponent(match[2]) };
|
||||||
|
return isProjectRef(project) ? project : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectAccessMessage(error: unknown): string {
|
||||||
|
const info = apiError(error, { fallbackMessage: "프로젝트 접근 권한을 확인하지 못했습니다. 다시 시도해 주세요." });
|
||||||
|
return info.code === "PROJECT_ACCESS_DENIED"
|
||||||
|
? "프로젝트에 접근할 권한이 없습니다."
|
||||||
|
: info.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectFromSearch(search: URLSearchParams): ProjectRef | null {
|
||||||
|
const type = search.get("projectType");
|
||||||
|
if (search.getAll("projectType").length !== 1 || search.getAll("pkey").length !== 1 ||
|
||||||
|
(type !== "0" && type !== "1")) return null;
|
||||||
|
const project = { projectType: Number(type), pkey: search.get("pkey") };
|
||||||
|
return isProjectRef(project) ? project : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectPageUrl(pathname: string, project: ProjectRef): string {
|
||||||
|
const search = new URLSearchParams({ projectType: String(project.projectType), pkey: project.pkey });
|
||||||
|
return pathname + "?" + search;
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ const progress = new Set(["day", "type", "loi", "screen"]);
|
|||||||
/** Browser inputs select only these implemented read operations, never an arbitrary upstream URL. */
|
/** Browser inputs select only these implemented read operations, never an arbitrary upstream URL. */
|
||||||
export function isProjectReadPath(slug: string[]): boolean {
|
export function isProjectReadPath(slug: string[]): boolean {
|
||||||
if (slug.length === 1) return slug[0] === "list" || slug[0] === "summary";
|
if (slug.length === 1) return slug[0] === "list" || slug[0] === "summary";
|
||||||
|
if (slug.length === 3 && slug[2] === "access")
|
||||||
|
return isProjectReadPath([slug[0], slug[1], "question", "list"]);
|
||||||
return (
|
return (
|
||||||
slug.length === 4 &&
|
slug.length === 4 &&
|
||||||
(slug[0] === "0" || slug[0] === "1") &&
|
(slug[0] === "0" || slug[0] === "1") &&
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ export function isProjectPage(path: string): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Project pages carry no project in the address (legacy KART kept it in client state); the
|
* ProjectEntry verifies and consumes incoming project parameters. Subsequent navigation
|
||||||
* selected project lives in useSelectedProject. Other paths open the progress page.
|
* uses the tab's selected project; other paths open the progress page.
|
||||||
*/
|
*/
|
||||||
export function projectPagePath(path: string): Route {
|
export function projectPagePath(path: string): Route {
|
||||||
return (isProjectPage(path) ? path : "/Report/Current") as Route;
|
return (isProjectPage(path) ? path : "/Report/Current") as Route;
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { LoginRequest } from "@kri/common";
|
import type { LoginRequest } from "@kri/common";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation } from "@tanstack/react-query";
|
||||||
import { useSetAtom } from "jotai";
|
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { selectedProjectAtom } from "@/hooks/useSelectedProject";
|
import { useResetSession } from "@/hooks/useResetSession";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { notifyAuthChange } from "@/lib/auth-change";
|
||||||
|
import { authApi } from "@/lib/http-client";
|
||||||
import { isLoginUser } from "@/types/kart";
|
import { isLoginUser } from "@/types/kart";
|
||||||
|
import { readExternalAuth } from "@/lib/external-auth";
|
||||||
|
|
||||||
export function useLoginMutation() {
|
export function useLoginMutation() {
|
||||||
const { setFromLoginResponse } = useAuth();
|
const { setFromLoginResponse } = useAuth();
|
||||||
const setSelectedProject = useSetAtom(selectedProjectAtom);
|
const resetSession = useResetSession();
|
||||||
const queryClient = useQueryClient();
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (request: LoginRequest) => {
|
mutationFn: async (request: LoginRequest) => {
|
||||||
const user = await nextApi.post<unknown>("/login", request, {
|
const user = await authApi.post<unknown>("/login", request, {
|
||||||
skipUnauthorizedHandler: true,
|
skipUnauthorizedHandler: true,
|
||||||
skipForbiddenHandler: true,
|
skipForbiddenHandler: true,
|
||||||
skipResponseErrorHandler: true,
|
skipResponseErrorHandler: true,
|
||||||
@@ -22,29 +22,32 @@ export function useLoginMutation() {
|
|||||||
if (!isLoginUser(user)) throw new Error("로그인 응답을 확인해 주세요.");
|
if (!isLoginUser(user)) throw new Error("로그인 응답을 확인해 주세요.");
|
||||||
return user;
|
return user;
|
||||||
},
|
},
|
||||||
onSuccess: (user) => {
|
onSuccess: async (user) => {
|
||||||
queryClient.clear();
|
|
||||||
// Legacy Login.js starts every session without a selected project.
|
// Legacy Login.js starts every session without a selected project.
|
||||||
setSelectedProject(null);
|
await resetSession();
|
||||||
setFromLoginResponse(user);
|
setFromLoginResponse(user);
|
||||||
|
notifyAuthChange("/");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
export function useLogoutMutation() {
|
export function useLogoutMutation() {
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { logout } = useAuth();
|
const { logout } = useAuth();
|
||||||
const setSelectedProject = useSetAtom(selectedProjectAtom);
|
const resetSession = useResetSession();
|
||||||
|
const externalSession = () => !!readExternalAuth();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: () =>
|
onMutate: () => ({ external: externalSession() }),
|
||||||
nextApi.post("/logout", null, {
|
mutationFn: async () => {
|
||||||
|
if (externalSession()) return;
|
||||||
|
await authApi.post("/logout", null, {
|
||||||
skipUnauthorizedHandler: true,
|
skipUnauthorizedHandler: true,
|
||||||
skipForbiddenHandler: true,
|
skipForbiddenHandler: true,
|
||||||
skipResponseErrorHandler: true,
|
skipResponseErrorHandler: true,
|
||||||
}),
|
});
|
||||||
onSettled: () => {
|
},
|
||||||
|
onSettled: async (_data, _error, _variables, context) => {
|
||||||
|
await resetSession();
|
||||||
logout();
|
logout();
|
||||||
setSelectedProject(null);
|
if (!context?.external) notifyAuthChange("/login");
|
||||||
queryClient.clear();
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery, type QueryClient } from "@tanstack/react-query";
|
||||||
|
import type { LoginUser } from "@kri/common";
|
||||||
|
import type { SelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { HttpError } from "@kri/common/http";
|
import { HttpError } from "@kri/common/http";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { isExternalUser } from "@/types/share";
|
import { isExternalUser } from "@/types/share";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { nextApi } from "@/lib/http-client";
|
||||||
import { queryKeys } from "@/query/key/keys";
|
import { queryKeys } from "@/query/key/keys";
|
||||||
import {
|
import {
|
||||||
|
isRecord,
|
||||||
isProject,
|
isProject,
|
||||||
isProjectSummary,
|
isProjectSummary,
|
||||||
isProgressDay,
|
isProgressDay,
|
||||||
@@ -18,6 +21,37 @@ import {
|
|||||||
type DateRange,
|
type DateRange,
|
||||||
} from "@/types/kart";
|
} from "@/types/kart";
|
||||||
|
|
||||||
|
export async function cancelPreviousProjectQueries(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
user: LoginUser,
|
||||||
|
selected: SelectedProject,
|
||||||
|
next: ProjectRef,
|
||||||
|
): Promise<void> {
|
||||||
|
if (!selected || selected.userId !== user.userId) return;
|
||||||
|
const previous = selected.project;
|
||||||
|
if (previous.projectType === next.projectType && previous.pkey === next.pkey) return;
|
||||||
|
|
||||||
|
await queryClient.cancelQueries({
|
||||||
|
predicate: ({ queryKey }) => {
|
||||||
|
if (queryKey[0] !== "kart" || queryKey[1] !== user.userId ||
|
||||||
|
queryKey[2] !== user.userRole || queryKey[3] !== user.userTeam) return false;
|
||||||
|
// Project-scoped keys put type/pkey at positions 4/5 or 5/6.
|
||||||
|
return (queryKey[4] === previous.projectType && queryKey[5] === previous.pkey) ||
|
||||||
|
(queryKey[5] === previous.projectType && queryKey[6] === previous.pkey);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Always check the server; a cached permission is not an authorization decision. */
|
||||||
|
export async function checkProjectAccess(project: ProjectRef): Promise<void> {
|
||||||
|
const result = await nextApi.get<unknown>(
|
||||||
|
"/project/" + project.projectType + "/" + encodeURIComponent(project.pkey) + "/access",
|
||||||
|
{ cache: "no-store" },
|
||||||
|
);
|
||||||
|
if (!isRecord(result) || result.allowed !== true)
|
||||||
|
throw new Error("프로젝트 접근 권한 응답을 확인해 주세요.");
|
||||||
|
}
|
||||||
|
|
||||||
export function useProjectListQuery() {
|
export function useProjectListQuery() {
|
||||||
const { auth, hydrated } = useAuth();
|
const { auth, hydrated } = useAuth();
|
||||||
const user = auth.user;
|
const user = auth.user;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export const CookieKeys = {
|
export const CookieKeys = {
|
||||||
AuthToken: "kri_authToken",
|
AuthToken: "kri_internal_authToken",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];
|
export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
export const StorageKeys = {
|
export const StorageKeys = {
|
||||||
AuthState: "kri:authState",
|
AuthState: "kri:authState",
|
||||||
|
AuthMode: "kart:authMode",
|
||||||
|
ExternalAuth: "kart:externalAuth",
|
||||||
SelectedProject: "kart:selectedProject",
|
SelectedProject: "kart:selectedProject",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
||||||
export const StorageType: Record<StorageKey, "local" | "session"> = {
|
export const StorageType: Record<StorageKey, "local" | "session"> = {
|
||||||
[StorageKeys.AuthState]: "local",
|
[StorageKeys.AuthState]: "local",
|
||||||
[StorageKeys.SelectedProject]: "local",
|
[StorageKeys.AuthMode]: "session",
|
||||||
|
[StorageKeys.ExternalAuth]: "session",
|
||||||
|
[StorageKeys.SelectedProject]: "session",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -141,16 +141,6 @@ export function readRows<T>(
|
|||||||
export function projectKey(project: ProjectRef): string {
|
export function projectKey(project: ProjectRef): string {
|
||||||
return project.projectType + ":" + project.pkey;
|
return project.projectType + ":" + project.pkey;
|
||||||
}
|
}
|
||||||
export function readProjectParams(
|
|
||||||
params: Pick<URLSearchParams, "get">,
|
|
||||||
): ProjectRef | null {
|
|
||||||
const type = params.get("projectType");
|
|
||||||
const project = {
|
|
||||||
projectType: type === "0" ? 0 : type === "1" ? 1 : null,
|
|
||||||
pkey: params.get("pkey"),
|
|
||||||
};
|
|
||||||
return isProjectRef(project) ? project : null;
|
|
||||||
}
|
|
||||||
export function validDateRange(range: DateRange): boolean {
|
export function validDateRange(range: DateRange): boolean {
|
||||||
const validDate = (date: string) =>
|
const validDate = (date: string) =>
|
||||||
/^\d{4}-\d{2}-\d{2}$/.test(date) &&
|
/^\d{4}-\d{2}-\d{2}$/.test(date) &&
|
||||||
|
|||||||
@@ -15,6 +15,12 @@ export type ShareLink = ProjectRef & {
|
|||||||
pageOnly: boolean;
|
pageOnly: boolean;
|
||||||
};
|
};
|
||||||
export type ExternalSession = { user: LoginUser; link: ShareLink };
|
export type ExternalSession = { user: LoginUser; link: ShareLink };
|
||||||
|
export type ExternalLoginResponse = ExternalSession & { accessToken: string };
|
||||||
|
|
||||||
|
export function isExternalLoginResponse(value: unknown): value is ExternalLoginResponse {
|
||||||
|
return isRecord(value) && typeof value.accessToken === "string" &&
|
||||||
|
value.accessToken.length > 0 && isExternalSession(value);
|
||||||
|
}
|
||||||
|
|
||||||
export function isExternalUser(user: LoginUser | null | undefined): boolean {
|
export function isExternalUser(user: LoginUser | null | undefined): boolean {
|
||||||
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
|
return !!user && (user.userRole === EXTERNAL_URL_COPY_ROLE ||
|
||||||
|
|||||||
Reference in New Issue
Block a user