add-identity-and-access: Authentik login, roles, org admin
- Company login via Authentik OIDC (openid-client, PKCE/state/nonce, employee_number scope); AUTH_MODE=dev alternative login at /login/dev, refused at startup when platform OIDC_ISSUER is present - provisionOnLogin: accounts created on first login (employee role, pending department), inactive accounts rejected, bootstrap sysadmins - DB sessions (hashed tokens, 8h idle timeout, revoked on deactivate) - Authorization: ROUTE_RULES + requireRouteAccess/requireRole per page and action, forbidden() 403 page, proxy.ts cookie redirect, scopeApplications/canReview/requireDepartment, role-based navigation - Admin: departments (code, type, deactivate, managers), accounts (pending filter, department assignment with effective date, roles, deactivate), roster CSV import with two-phase preview/commit - departmentMembersAt for headcount snapshots - Tests: 168 unit/integration (incl. mock OIDC provider), 12 e2e - CI: e2e job; CLAUDE.md: auth rules and commands Tasks 15/17 done. Pending: 5.1 (confirm CI run once a remote exists), 5.3 (manual verification with real Authentik after first deploy). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e03ed0b2df
commit
5b43dd192b
@@ -11,3 +11,13 @@ TZ_APP=Asia/Taipei
|
||||
# 備份輸出目錄與保留份數
|
||||
BACKUP_DIR=./backups
|
||||
BACKUP_KEEP=14
|
||||
|
||||
# 登入模式:oidc(公司 Authentik 登入,正式環境預設)或 dev(非正式環境的替代登入,以員工編號直接登入)。
|
||||
# 本機開發與 e2e 用 dev。在 vibe 平台上(有 OIDC_ISSUER)設 dev 會拒絕啟動。
|
||||
AUTH_MODE=dev
|
||||
# 本系統對外網址,用來組 OIDC redirect URI(${APP_URL}/api/auth/callback/authentik)。oidc 模式必填且須為 https。
|
||||
APP_URL=
|
||||
# 這些員工編號登入時自動取得系統管理員角色(逗號分隔),讓全新系統有人能開始設定。
|
||||
BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS=
|
||||
# OIDC_ISSUER、OIDC_CLIENT_ID、OIDC_CLIENT_SECRET 由 vibe 平台部署時注入(保留字),
|
||||
# 不要寫在這裡或任何進版控的檔案。
|
||||
|
||||
@@ -19,4 +19,24 @@ jobs:
|
||||
- run: npm run format:check
|
||||
- run: npm run typecheck
|
||||
- run: npm test
|
||||
# e2e 暫不在 CI 執行(需安裝瀏覽器),於 add-identity-and-access 開啟。
|
||||
|
||||
e2e:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npx playwright install --with-deps chromium
|
||||
# 以 AUTH_MODE=dev(tests/e2e/env.ts)建置並建立 e2e 專用資料庫,再對 next start 跑測試。
|
||||
- run: npm run test:e2e:prepare
|
||||
- run: npm run test:e2e
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
|
||||
@@ -14,7 +14,7 @@ Git repository on branch `main` (no remote yet). Files use LF line endings (`.gi
|
||||
|
||||
## Commands
|
||||
|
||||
First-time setup: `npm ci` → copy `.env.example` to `.env` and set `SESSION_SECRET` (≥32 chars) → `npm run db:migrate` → `npm run db:seed` → `npm run dev`.
|
||||
First-time setup: `npm ci` → copy `.env.example` to `.env` and set `SESSION_SECRET` (≥32 chars; keep `AUTH_MODE=dev`) → `npm run db:migrate` → `npm run db:seed` (dev mode also creates demo departments and users `D0001`–`D0006`) → `npm run dev` → log in at `/login/dev` with a demo employee number.
|
||||
|
||||
| Command | Purpose |
|
||||
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
||||
@@ -29,9 +29,19 @@ First-time setup: `npm ci` → copy `.env.example` to `.env` and set `SESSION_SE
|
||||
| `npm run db:migrate` · `npm run db:seed` | Apply migrations · idempotent seed |
|
||||
| `npm run backup` | Online SQLite backup + attachments copy to `BACKUP_DIR`; see `docs/operations/backup.md` |
|
||||
|
||||
CI (`.github/workflows/ci.yml`) runs `npm ci`, lint, format:check, typecheck, test. E2E is not in CI yet (enable in `add-identity-and-access`).
|
||||
CI (`.github/workflows/ci.yml`): job `check` runs `npm ci`, lint, format:check, typecheck, test; job `e2e` installs Chromium and runs `test:e2e:prepare` + `test:e2e` (with `AUTH_MODE=dev`, see `tests/e2e/env.ts`). E2E helpers: `tests/e2e/helpers.ts` (`loginAs(page, employeeNo)`, demo users). Parallel e2e tests share one DB — use fresh employee numbers/department names instead of mutating demo users.
|
||||
|
||||
If Playwright's browser download fails (CDN returns 403 on this machine), set `PLAYWRIGHT_CHANNEL=chrome` (or `msedge`) to use the installed browser.
|
||||
If Playwright's browser download fails (CDN returns 403 on this machine), set `PLAYWRIGHT_CHANNEL=chrome` (or `msedge`) to use the installed browser. On this machine Playwright may hang after the tests finish (Chrome profile cleanup); results are already printed by then.
|
||||
|
||||
## Authentication & authorization
|
||||
|
||||
- Login is company Authentik OIDC only (`AUTH_MODE=oidc`, default). The vibe platform injects `OIDC_ISSUER` / `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` (reserved names — never put them in the repo); `APP_URL` builds the redirect URI `${APP_URL}/api/auth/callback/authentik`. No passwords anywhere.
|
||||
- `AUTH_MODE=dev` enables `/login/dev` (log in by employee number) for local dev and e2e. Startup refuses `AUTH_MODE=dev` when `OIDC_ISSUER` is present; in `oidc` mode `/login/dev` and its action return 404. Never key behavior off `NODE_ENV` for this.
|
||||
- Accounts are created on first login by `provisionOnLogin` (`src/server/auth/provision.ts`): employee role, department pending until a sysadmin assigns one or a roster CSV pre-assigns it. `BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS` grants sysadmin on login.
|
||||
- **Every page** must start with `await requireRouteAccess("<route pattern>")` (`src/server/auth/current-user.ts`); the pattern must exist in `ROUTE_RULES` (`src/lib/access.ts`) — unlisted routes are denied, and the sidebar (`buildNavigation`) is generated from the same table. Don't rely on a shared layout for the check (layouts don't re-run on client navigation). `src/proxy.ts` only redirects requests without a session cookie.
|
||||
- **Every Server Action / Route Handler** must call `requireRole(...)` itself — actions can be invoked directly. Denials use `forbidden()` → `src/app/forbidden.tsx` (HTTP 403; `experimental.authInterrupts` is on).
|
||||
- Application queries **must** go through `scopeApplications(user, managedDepartmentIds(db, user))` (`src/server/auth/scope.ts`); review permission through `canReview` (only managers of the application's department; self-review allowed but flagged 「主管自行審核」). Creating an application **must** call `requireDepartment(user)`.
|
||||
- Org data lives in `src/server/org/` (departments, accounts, roster CSV import). Department membership on a date (for headcount snapshots) is `departmentMembersAt(db, departmentId, "YYYY-MM-DD")`, based on `user_department_history`.
|
||||
|
||||
## Code layout
|
||||
|
||||
@@ -49,7 +59,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
|
||||
- `AI補助申請系統_表單結構與前端介面規劃_v1.0.docx` — frontend IA, per-field validation, page layouts, routes, shared components, MVP priorities (P0/P1/P2), frontend acceptance criteria.
|
||||
- `風格2_首頁.png`, `風格2_新增申請頁.png` — chosen visual style mockups (dashboard, new application page).
|
||||
|
||||
Python 3.12 is installed (user scope, `%LOCALAPPDATA%\Programs\Python\Python312`); `.docx` text can be extracted with Python or with PowerShell (`System.IO.Compression.ZipFile` → read `word/document.xml`, strip tags).
|
||||
Python is available via the `py -3` launcher (also `C:\Python\Python310`); `.docx` text can be extracted with Python (`zipfile` → `word/document.xml`, strip tags) or PowerShell (`System.IO.Compression.ZipFile`). Write extracted Chinese text to a UTF-8 file and read that — piping it through the console garbles it (cp950).
|
||||
|
||||
## Workflow: OpenSpec (spec-driven)
|
||||
|
||||
|
||||
+6
-1
@@ -1,5 +1,10 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {/* config options here */};
|
||||
const nextConfig: NextConfig = {
|
||||
experimental: {
|
||||
// 讓 requireRole 可用 forbidden() 回應 403 無權限頁(src/app/forbidden.tsx)。
|
||||
authInterrupts: true,
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
@@ -89,7 +89,9 @@
|
||||
|
||||
- `requireUser()`、`requireRole(...roles)`、`requireDepartment(user)` 用於頁面、Server Action、Route Handler 入口。
|
||||
- `scopeApplications(user)` 產生申請查詢條件:員工 → 本人;主管 → 所轄部門(`department_managers`);管理者 → 全部。後續 change 查詢申請 MUST 經過此 helper。
|
||||
- `src/proxy.ts`(Next.js 16 的 Proxy,舊稱 middleware)只檢查是否有 session cookie 並導向 `/login`(不讀 SQLite);完整 session 驗證與角色檢查在各 route group 的 server layout 與每個 action 內執行。
|
||||
- `src/proxy.ts`(Next.js 16 的 Proxy,舊稱 middleware)只檢查是否有 session cookie 並導向 `/login?returnTo=…`(不讀 SQLite)。
|
||||
- 完整 session 驗證與角色檢查在**每個頁面**(`requireRouteAccess("<該路由>")`)與每個 Server Action/Route Handler 內執行。不放在共用 layout:App Router 在同一 layout 下切換頁面時 layout 不會重新執行,且同一資料夾內的頁面角色不同(例如 `/admin/settlements` 與 `/admin/accounts`)。
|
||||
- 無權限以 `forbidden()` 回應 HTTP 403 並顯示 `src/app/forbidden.tsx`(需開啟 `experimental.authInterrupts`)。
|
||||
- 導覽項目與路由權限由同一份「路由 → 允許角色」設定產生,避免兩者不一致。
|
||||
|
||||
### 資料模型
|
||||
|
||||
@@ -2,32 +2,32 @@
|
||||
|
||||
## 1. 資料模型與設定
|
||||
|
||||
- [ ] 1.1 建立 departments(含 code)、users(email、department_id 可為空、first/last_login_at)、user_roles、department_managers、user_department_history、sessions 的 Drizzle schema 與 migration,確認 `npm run db:migrate` 成功且員工編號唯一、email 有值時唯一
|
||||
- [ ] 1.2 擴充 `src/server/env.ts` 與 `.env.example`:`AUTH_MODE`、`APP_URL`、`BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS`、`OIDC_ISSUER`/`OIDC_CLIENT_ID`/`OIDC_CLIENT_SECRET`(註明由平台注入),並在 `runStartupChecks` 加入模式交叉檢查,單元測試 design 表格的四種情況(含 dev 模式遇到 `OIDC_ISSUER` 拒絕啟動)
|
||||
- [ ] 1.3 擴充 `db:seed`:dev 模式建立示範部門(一般、研發)與四種角色的示範使用者,確認重複執行不會重複建立
|
||||
- [x] 1.1 建立 departments(含 code)、users(email、department_id 可為空、first/last_login_at)、user_roles、department_managers、user_department_history、sessions 的 Drizzle schema 與 migration,確認 `npm run db:migrate` 成功且員工編號唯一、email 有值時唯一
|
||||
- [x] 1.2 擴充 `src/server/env.ts` 與 `.env.example`:`AUTH_MODE`、`APP_URL`、`BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS`、`OIDC_ISSUER`/`OIDC_CLIENT_ID`/`OIDC_CLIENT_SECRET`(註明由平台注入),並在 `runStartupChecks` 加入模式交叉檢查,單元測試 design 表格的四種情況(含 dev 模式遇到 `OIDC_ISSUER` 拒絕啟動)
|
||||
- [x] 1.3 擴充 `db:seed`:dev 模式建立示範部門(一般、研發)與四種角色的示範使用者,確認重複執行不會重複建立
|
||||
|
||||
## 2. 認證
|
||||
|
||||
- [ ] 2.1 實作 `provisionOnLogin(claims)`(單一交易:建立/更新使用者、停用拒絕、初始系統管理員授權、email 衝突不阻擋),整合測試涵蓋首次登入、名冊已匯入者首次登入、停用拒絕、bootstrap 授權、缺員工編號拒絕
|
||||
- [ ] 2.2 實作 session 建立、驗證、更新 last_seen_at、閒置 8 小時失效、登出與停用時刪除全部 session,整合測試涵蓋逾時、登出、停用後失效
|
||||
- [ ] 2.3 安裝 `openid-client`,實作 `/login` 頁、`/api/auth/login`(state、nonce、PKCE 暫存 cookie)與 `/api/auth/callback/authentik`(驗證後呼叫 `provisionOnLogin`),整合測試以模擬的 OIDC provider 驗證 state 不符被拒、缺 `employee_number` 被拒、成功登入導向原頁面
|
||||
- [ ] 2.4 實作 `/login/dev` 與其 action(僅 `AUTH_MODE=dev`,否則 404)與「開發登入模式」警示條,整合測試 `oidc` 模式下頁面與 action 皆回 404
|
||||
- [x] 2.1 實作 `provisionOnLogin(claims)`(單一交易:建立/更新使用者、停用拒絕、初始系統管理員授權、email 衝突不阻擋),整合測試涵蓋首次登入、名冊已匯入者首次登入、停用拒絕、bootstrap 授權、缺員工編號拒絕
|
||||
- [x] 2.2 實作 session 建立、驗證、更新 last_seen_at、閒置 8 小時失效、登出與停用時刪除全部 session,整合測試涵蓋逾時、登出、停用後失效
|
||||
- [x] 2.3 安裝 `openid-client`,實作 `/login` 頁、`/api/auth/login`(state、nonce、PKCE 暫存 cookie)與 `/api/auth/callback/authentik`(驗證後呼叫 `provisionOnLogin`),整合測試以模擬的 OIDC provider 驗證 state 不符被拒、缺 `employee_number` 被拒、成功登入導向原頁面
|
||||
- [x] 2.4 實作 `/login/dev` 與其 action(僅 `AUTH_MODE=dev`,否則 404)與「開發登入模式」警示條,整合測試 `oidc` 模式下頁面與 action 皆回 404
|
||||
|
||||
## 3. 授權
|
||||
|
||||
- [ ] 3.1 實作 `requireUser`、`requireRole`、`requireDepartment` 與「路由 → 允許角色」設定,單元測試四種角色對前端規劃 §11 每條路由的允許/拒絕結果,以及待指派部門者被 `requireDepartment` 拒絕
|
||||
- [ ] 3.2 實作 `scopeApplications` 與部門範圍 helper(員工本人、主管所轄部門、管理者全部)及「僅部門主管可審核」判斷,單元測試涵蓋一般員工審核被拒、主管審本人案件允許且標示「主管自行審核」
|
||||
- [ ] 3.3 建立 `src/proxy.ts`(無 session cookie 導向 `/login`)、各 route group layout 的角色檢查與無權限頁,e2e 測試員工直接輸入 `/admin/settlements` 看到無權限頁
|
||||
- [ ] 3.4 依角色產生側欄導覽資料(供 `add-app-shell` 使用),單元測試四種角色及兼任時的項目;首頁對待指派部門者顯示提示
|
||||
- [x] 3.1 實作 `requireUser`、`requireRole`、`requireDepartment` 與「路由 → 允許角色」設定,單元測試四種角色對前端規劃 §11 每條路由的允許/拒絕結果,以及待指派部門者被 `requireDepartment` 拒絕
|
||||
- [x] 3.2 實作 `scopeApplications` 與部門範圍 helper(員工本人、主管所轄部門、管理者全部)及「僅部門主管可審核」判斷,單元測試涵蓋一般員工審核被拒、主管審本人案件允許且標示「主管自行審核」
|
||||
- [x] 3.3 建立 `src/proxy.ts`(無 session cookie 導向 `/login`)、各 route group layout 的角色檢查與無權限頁,e2e 測試員工直接輸入 `/admin/settlements` 看到無權限頁
|
||||
- [x] 3.4 依角色產生側欄導覽資料(供 `add-app-shell` 使用),單元測試四種角色及兼任時的項目;首頁對待指派部門者顯示提示
|
||||
|
||||
## 4. 組織與帳號管理
|
||||
|
||||
- [ ] 4.1 實作部門管理頁 `/admin/departments`(新增、編輯代碼與類型、停用、指派/移除主管),整合測試停用部門不出現在選項、部門代碼重複被拒、指派主管後取得部門範圍
|
||||
- [ ] 4.2 實作帳號與角色頁 `/admin/accounts`(列表含「待指派部門」篩選、指派部門並記錄生效日、停用/啟用、指派角色),整合測試非系統管理員無法改角色、指派部門後可通過 `requireDepartment`
|
||||
- [ ] 4.3 實作名冊 CSV 匯入(範本下載、全量驗證預覽、單一交易寫入、以員工編號 upsert、建立未登入人員),整合測試含錯誤列時完全不寫入、未登入人員計入部門在職成員查詢
|
||||
- [x] 4.1 實作部門管理頁 `/admin/departments`(新增、編輯代碼與類型、停用、指派/移除主管),整合測試停用部門不出現在選項、部門代碼重複被拒、指派主管後取得部門範圍
|
||||
- [x] 4.2 實作帳號與角色頁 `/admin/accounts`(列表含「待指派部門」篩選、指派部門並記錄生效日、停用/啟用、指派角色),整合測試非系統管理員無法改角色、指派部門後可通過 `requireDepartment`
|
||||
- [x] 4.3 實作名冊 CSV 匯入(範本下載、全量驗證預覽、單一交易寫入、以員工編號 upsert、建立未登入人員),整合測試含錯誤列時完全不寫入、未登入人員計入部門在職成員查詢
|
||||
|
||||
## 5. 整合驗收
|
||||
|
||||
- [ ] 5.1 在 CI 開啟 Playwright e2e(安裝瀏覽器,以 `AUTH_MODE=dev` 執行),以 e2e 測試四種角色經替代登入後的導覽、跨範圍存取被拒、待指派部門者無法新增申請,確認 CI 通過
|
||||
- [ ] 5.2 更新 `CLAUDE.md`:授權入口(頁面與 action 必須用 `requireRole`,申請查詢必須用 `scopeApplications`,建立申請必須用 `requireDepartment`)、`AUTH_MODE` 與本機登入方式,確認內容與程式一致
|
||||
- [x] 5.2 更新 `CLAUDE.md`:授權入口(頁面與 action 必須用 `requireRole`,申請查詢必須用 `scopeApplications`,建立申請必須用 `requireDepartment`)、`AUTH_MODE` 與本機登入方式,確認內容與程式一致
|
||||
- [ ] 5.3 首次部署到 vibe 平台後(`vibe.yaml` 宣告 `auth.mode: oidc`、`callback_path: /api/auth/callback/authentik`),以真實公司帳號手動驗證:登入、首次建帳號、登出、`/login/dev` 回 404,並記錄結果
|
||||
|
||||
Generated
+32
@@ -11,6 +11,7 @@
|
||||
"better-sqlite3": "^13.0.3",
|
||||
"drizzle-orm": "^0.45.3",
|
||||
"next": "16.3.8",
|
||||
"openid-client": "^6.8.8",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"zod": "^4.6.5"
|
||||
@@ -6315,6 +6316,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/jose": {
|
||||
"version": "6.2.12",
|
||||
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
|
||||
"integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
@@ -6977,6 +6987,15 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/oauth4webapi": {
|
||||
"version": "3.8.8",
|
||||
"resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
|
||||
"integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
@@ -7114,6 +7133,19 @@
|
||||
"node": ">=12.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/openid-client": {
|
||||
"version": "6.8.8",
|
||||
"resolved": "https://registry.npmjs.org/openid-client/-/openid-client-6.8.8.tgz",
|
||||
"integrity": "sha512-ZsucJA5Ad04Uv7YN4ql+s4GXNmb9uAYQwyJTsJx7CH/MX3JZioLE2pVKi1SC+YrbSLA4Px3Gi30dMjgOZtb6pA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jose": "^6.2.12",
|
||||
"oauth4webapi": "^3.8.8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"better-sqlite3": "^13.0.3",
|
||||
"drizzle-orm": "^0.45.3",
|
||||
"next": "16.3.8",
|
||||
"openid-client": "^6.8.8",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"zod": "^4.6.5"
|
||||
|
||||
+4
-2
@@ -1,8 +1,10 @@
|
||||
import "./load-env";
|
||||
import { getDatabase } from "@/server/db/client";
|
||||
import { seed } from "@/server/db/seed";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
const env = getEnv();
|
||||
const { db, sqlite } = getDatabase();
|
||||
seed(db);
|
||||
console.log("seed 完成");
|
||||
seed(db, new Date(), { demo: env.AUTH_MODE === "dev", timeZone: env.TZ_APP });
|
||||
console.log(env.AUTH_MODE === "dev" ? "seed 完成(含示範部門與使用者)" : "seed 完成");
|
||||
sqlite.close();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { localDate } from "@/domain/calendar";
|
||||
import type { Role } from "@/lib/roles";
|
||||
import { requireRole } from "@/server/auth/current-user";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { getEnv } from "@/server/env";
|
||||
import { assignDepartment, setAccountActive, setRoles } from "@/server/org/accounts";
|
||||
import type { Result } from "@/server/org/result";
|
||||
|
||||
const PAGE = "/admin/accounts";
|
||||
|
||||
function finish(result: Result<unknown>, back: string) {
|
||||
const url = new URL(back, "http://x");
|
||||
if (!result.ok) url.searchParams.set("error", result.error);
|
||||
else url.searchParams.delete("error");
|
||||
revalidatePath(PAGE);
|
||||
redirect(url.pathname + url.search);
|
||||
}
|
||||
|
||||
const today = () => localDate(new Date(), getEnv().TZ_APP);
|
||||
const back = (form: FormData) => {
|
||||
const value = String(form.get("back") ?? PAGE);
|
||||
return value.startsWith(PAGE) ? value : PAGE;
|
||||
};
|
||||
|
||||
// 每個 action 都自行檢查系統管理員權限:action 可被直接呼叫,不能只靠頁面擋。
|
||||
|
||||
export async function assignDepartmentAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
const effectiveFrom = String(form.get("effectiveFrom") || today());
|
||||
finish(
|
||||
assignDepartment(
|
||||
getDb(),
|
||||
Number(form.get("userId")),
|
||||
Number(form.get("departmentId")),
|
||||
effectiveFrom,
|
||||
today(),
|
||||
),
|
||||
back(form),
|
||||
);
|
||||
}
|
||||
|
||||
export async function setAccountActiveAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
finish(
|
||||
setAccountActive(getDb(), Number(form.get("userId")), form.get("active") === "true", today()),
|
||||
back(form),
|
||||
);
|
||||
}
|
||||
|
||||
export async function setRolesAction(form: FormData) {
|
||||
const actor = await requireRole("sysadmin");
|
||||
const roles = form.getAll("roles").map(String) as Role[];
|
||||
finish(setRoles(getDb(), actor, Number(form.get("userId")), roles), back(form));
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { localDate } from "@/domain/calendar";
|
||||
import { requireRole } from "@/server/auth/current-user";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { getEnv } from "@/server/env";
|
||||
import { commitRoster, validateRoster, type RosterRowError } from "@/server/org/roster-import";
|
||||
|
||||
const MAX_BYTES = 1024 * 1024;
|
||||
|
||||
export type ImportState =
|
||||
| { step: "upload"; error?: string }
|
||||
| {
|
||||
step: "preview";
|
||||
csvText: string;
|
||||
fileName: string;
|
||||
create: number;
|
||||
update: number;
|
||||
errors: RosterRowError[];
|
||||
};
|
||||
|
||||
/** 第一階段:讀檔並全量驗證,回傳預覽(不寫入)。 */
|
||||
export async function previewRosterAction(
|
||||
_prev: ImportState,
|
||||
form: FormData,
|
||||
): Promise<ImportState> {
|
||||
await requireRole("sysadmin");
|
||||
const file = form.get("file");
|
||||
if (!(file instanceof File) || file.size === 0)
|
||||
return { step: "upload", error: "請選擇 CSV 檔案" };
|
||||
if (file.size > MAX_BYTES) return { step: "upload", error: "檔案超過 1 MB" };
|
||||
// File.text() 以 UTF-8 解碼;非 UTF-8 的位元組會變成 U+FFFD,由驗證提示改存 UTF-8。
|
||||
const csvText = await file.text();
|
||||
const preview = validateRoster(getDb(), csvText);
|
||||
return {
|
||||
step: "preview",
|
||||
csvText,
|
||||
fileName: file.name,
|
||||
create: preview.create,
|
||||
update: preview.update,
|
||||
errors: preview.errors,
|
||||
};
|
||||
}
|
||||
|
||||
/** 第二階段:確認後在單一交易內重新驗證並寫入。 */
|
||||
export async function commitRosterAction(_prev: ImportState, form: FormData): Promise<ImportState> {
|
||||
await requireRole("sysadmin");
|
||||
const csvText = String(form.get("csvText") ?? "");
|
||||
const result = commitRoster(getDb(), csvText, localDate(new Date(), getEnv().TZ_APP));
|
||||
if (!result.ok) {
|
||||
return {
|
||||
step: "preview",
|
||||
csvText,
|
||||
fileName: String(form.get("fileName") ?? ""),
|
||||
create: 0,
|
||||
update: 0,
|
||||
errors: result.errors,
|
||||
};
|
||||
}
|
||||
revalidatePath("/admin/accounts");
|
||||
redirect(
|
||||
`/admin/accounts?notice=${encodeURIComponent(`已匯入:新增 ${result.create} 筆、更新 ${result.update} 筆`)}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import { commitRosterAction, previewRosterAction, type ImportState } from "./actions";
|
||||
|
||||
// 暫時樣式:FileUploader、ErrorSummary 等共用元件由 add-app-shell 建立。
|
||||
export function ImportForm() {
|
||||
const [previewState, preview, previewing] = useActionState<ImportState, FormData>(
|
||||
previewRosterAction,
|
||||
{ step: "upload" },
|
||||
);
|
||||
const [commitState, commit, committing] = useActionState<ImportState, FormData>(
|
||||
commitRosterAction,
|
||||
{ step: "upload" },
|
||||
);
|
||||
// 確認時若重新驗證失敗,以確認結果為準顯示錯誤。
|
||||
const state = commitState.step === "preview" ? commitState : previewState;
|
||||
|
||||
return (
|
||||
<>
|
||||
<form action={preview}>
|
||||
<label htmlFor="roster-file">名冊檔案(CSV,UTF-8)</label>
|
||||
<input id="roster-file" name="file" type="file" accept=".csv,text/csv" required />
|
||||
<button type="submit" disabled={previewing}>
|
||||
{previewing ? "檢查中…" : "上傳並檢查"}
|
||||
</button>
|
||||
</form>
|
||||
{state.step === "upload" && state.error && <p role="alert">{state.error}</p>}
|
||||
|
||||
{state.step === "preview" && (
|
||||
<section aria-labelledby="preview-title">
|
||||
<h2 id="preview-title">檢查結果:{state.fileName}</h2>
|
||||
{state.errors.length > 0 ? (
|
||||
<div role="alert">
|
||||
<p>有 {state.errors.length} 列錯誤,未匯入任何資料。請修正後重新上傳。</p>
|
||||
<ul>
|
||||
{state.errors.map((e) => (
|
||||
<li key={e.line}>
|
||||
第 {e.line} 列:{e.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<form action={commit}>
|
||||
<p>
|
||||
將新增 {state.create} 筆、更新 {state.update} 筆人員資料。
|
||||
</p>
|
||||
<input type="hidden" name="csvText" value={state.csvText} />
|
||||
<input type="hidden" name="fileName" value={state.fileName} />
|
||||
<button type="submit" disabled={committing}>
|
||||
{committing ? "匯入中…" : "確認匯入"}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Link from "next/link";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
import { ImportForm } from "./import-form";
|
||||
|
||||
export default async function ImportRosterPage() {
|
||||
await requireRouteAccess("/admin/accounts/import");
|
||||
return (
|
||||
<main>
|
||||
<h1>匯入名冊</h1>
|
||||
<p>
|
||||
欄位:員工編號(必填)、姓名、部門(部門代碼或名稱,必填)、角色(選填,多個以「、」分隔)。
|
||||
以員工編號比對:已存在者更新部門與角色,不存在者建立尚未登入的人員。角色欄留空不變更既有角色。
|
||||
</p>
|
||||
<p>
|
||||
{/* 範本由 route handler 產生 CSV 下載,不是頁面,用一般連結。 */}
|
||||
<a href="/admin/accounts/import/template" download>
|
||||
下載範本
|
||||
</a>
|
||||
{" ・ "}
|
||||
<Link href="/admin/accounts">回帳號與角色</Link>
|
||||
</p>
|
||||
<ImportForm />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { toCsv } from "@/lib/csv";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
import { ROSTER_TEMPLATE } from "@/server/org/roster-import";
|
||||
|
||||
/** 名冊範本下載(UTF-8 BOM,Excel 可直接開啟)。 */
|
||||
export async function GET() {
|
||||
await requireRouteAccess("/admin/accounts/import/template");
|
||||
return new Response(toCsv(ROSTER_TEMPLATE), {
|
||||
headers: {
|
||||
"content-type": "text/csv; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="roster-template.csv"; filename*=UTF-8''${encodeURIComponent("名冊範本.csv")}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import Link from "next/link";
|
||||
import { localDate } from "@/domain/calendar";
|
||||
import { ROLES, ROLE_LABELS } from "@/lib/roles";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { getEnv } from "@/server/env";
|
||||
import { listAccounts, type AccountFilter } from "@/server/org/accounts";
|
||||
import { listActiveDepartments } from "@/server/org/departments";
|
||||
import { assignDepartmentAction, setAccountActiveAction, setRolesAction } from "./actions";
|
||||
|
||||
const FILTERS: { value: AccountFilter; label: string }[] = [
|
||||
{ value: "all", label: "全部" },
|
||||
{ value: "pending", label: "待指派部門" },
|
||||
{ value: "inactive", label: "已停用" },
|
||||
];
|
||||
|
||||
// 暫時樣式:表格、表單元件與確認視窗由 add-app-shell 統一。
|
||||
export default async function AccountsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ filter?: string; error?: string; notice?: string }>;
|
||||
}) {
|
||||
await requireRouteAccess("/admin/accounts");
|
||||
const { filter: rawFilter, error, notice } = await searchParams;
|
||||
const filter: AccountFilter = FILTERS.some((f) => f.value === rawFilter)
|
||||
? (rawFilter as AccountFilter)
|
||||
: "all";
|
||||
const db = getDb();
|
||||
const accounts = listAccounts(db, filter);
|
||||
const departmentOptions = listActiveDepartments(db);
|
||||
const today = localDate(new Date(), getEnv().TZ_APP);
|
||||
const back = `/admin/accounts?filter=${filter}`;
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>帳號與角色</h1>
|
||||
<p>
|
||||
<Link href="/admin/accounts/import">匯入名冊 CSV</Link>
|
||||
</p>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
<nav aria-label="帳號篩選">
|
||||
{FILTERS.map((f) =>
|
||||
f.value === filter ? (
|
||||
<strong key={f.value}>{f.label}</strong>
|
||||
) : (
|
||||
<Link key={f.value} href={`/admin/accounts?filter=${f.value}`}>
|
||||
{f.label}
|
||||
</Link>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
|
||||
{accounts.length === 0 ? (
|
||||
<p>沒有符合條件的帳號。</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>員工編號</th>
|
||||
<th>姓名/Email</th>
|
||||
<th>部門</th>
|
||||
<th>角色</th>
|
||||
<th>狀態</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{accounts.map((a) => (
|
||||
<tr key={a.id} data-testid={`account-${a.employeeNo}`}>
|
||||
<td>{a.employeeNo}</td>
|
||||
<td>
|
||||
{a.name ?? "(尚未登入)"}
|
||||
<br />
|
||||
{a.email ?? ""}
|
||||
</td>
|
||||
<td>
|
||||
{a.departmentName ?? "待指派部門"}
|
||||
{a.active && (
|
||||
<form action={assignDepartmentAction}>
|
||||
<input type="hidden" name="userId" value={a.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<select
|
||||
name="departmentId"
|
||||
defaultValue={a.departmentId ?? ""}
|
||||
aria-label="所屬部門"
|
||||
required
|
||||
>
|
||||
<option value="" disabled>
|
||||
選擇部門
|
||||
</option>
|
||||
{departmentOptions.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
type="date"
|
||||
name="effectiveFrom"
|
||||
defaultValue={today}
|
||||
max={today}
|
||||
aria-label="生效日"
|
||||
/>
|
||||
<button type="submit">指派部門</button>
|
||||
</form>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<form action={setRolesAction}>
|
||||
<input type="hidden" name="userId" value={a.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
{ROLES.map((role) => (
|
||||
<label key={role}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="roles"
|
||||
value={role}
|
||||
defaultChecked={a.roles.includes(role)}
|
||||
disabled={role === "employee"}
|
||||
/>
|
||||
{ROLE_LABELS[role]}
|
||||
</label>
|
||||
))}
|
||||
<button type="submit">更新角色</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
{a.active ? "在職" : "已停用"}
|
||||
<form action={setAccountActiveAction}>
|
||||
<input type="hidden" name="userId" value={a.id} />
|
||||
<input type="hidden" name="back" value={back} />
|
||||
<input type="hidden" name="active" value={String(!a.active)} />
|
||||
<button type="submit">{a.active ? "停用" : "啟用"}</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/admin/audit-log");
|
||||
return <RoutePlaceholder title="操作紀錄" change="add-audit-trail" />;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireRole } from "@/server/auth/current-user";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import {
|
||||
assignManager,
|
||||
createDepartment,
|
||||
removeManager,
|
||||
setDepartmentActive,
|
||||
updateDepartment,
|
||||
} from "@/server/org/departments";
|
||||
import type { Result } from "@/server/org/result";
|
||||
|
||||
const PAGE = "/admin/departments";
|
||||
|
||||
function finish(result: Result<unknown>) {
|
||||
if (!result.ok) redirect(`${PAGE}?error=${encodeURIComponent(result.error)}`);
|
||||
revalidatePath(PAGE);
|
||||
redirect(PAGE);
|
||||
}
|
||||
|
||||
const text = (form: FormData, key: string) => String(form.get(key) ?? "");
|
||||
const id = (form: FormData, key: string) => Number(form.get(key));
|
||||
const departmentFields = (form: FormData) => ({
|
||||
name: text(form, "name"),
|
||||
code: text(form, "code"),
|
||||
type: text(form, "type") as "general" | "rnd",
|
||||
});
|
||||
|
||||
// 每個 action 都自行檢查系統管理員權限:action 可被直接呼叫,不能只靠頁面擋。
|
||||
|
||||
export async function createDepartmentAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
finish(createDepartment(getDb(), departmentFields(form)));
|
||||
}
|
||||
|
||||
export async function updateDepartmentAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
finish(updateDepartment(getDb(), id(form, "id"), departmentFields(form)));
|
||||
}
|
||||
|
||||
export async function setDepartmentActiveAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
finish(setDepartmentActive(getDb(), id(form, "id"), text(form, "active") === "true"));
|
||||
}
|
||||
|
||||
export async function assignManagerAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
finish(assignManager(getDb(), id(form, "departmentId"), text(form, "employeeNo")));
|
||||
}
|
||||
|
||||
export async function removeManagerAction(form: FormData) {
|
||||
await requireRole("sysadmin");
|
||||
finish(removeManager(getDb(), id(form, "departmentId"), id(form, "userId")));
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { DEPARTMENT_TYPES, DEPARTMENT_TYPE_LABELS } from "@/lib/department-types";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { listDepartments } from "@/server/org/departments";
|
||||
import {
|
||||
assignManagerAction,
|
||||
createDepartmentAction,
|
||||
removeManagerAction,
|
||||
setDepartmentActiveAction,
|
||||
updateDepartmentAction,
|
||||
} from "./actions";
|
||||
|
||||
function TypeSelect({ defaultValue }: { defaultValue?: string }) {
|
||||
return (
|
||||
<select name="type" defaultValue={defaultValue ?? "general"} aria-label="部門類型">
|
||||
{DEPARTMENT_TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{DEPARTMENT_TYPE_LABELS[type]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
// 暫時樣式:表格、表單元件與確認視窗由 add-app-shell 統一。
|
||||
export default async function DepartmentsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ error?: string }>;
|
||||
}) {
|
||||
await requireRouteAccess("/admin/departments");
|
||||
const { error } = await searchParams;
|
||||
const departments = listDepartments(getDb());
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>部門管理</h1>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
|
||||
<section aria-labelledby="new-department">
|
||||
<h2 id="new-department">新增部門</h2>
|
||||
<form action={createDepartmentAction}>
|
||||
<label>
|
||||
部門名稱 <input name="name" required />
|
||||
</label>
|
||||
<label>
|
||||
部門代碼(選填) <input name="code" />
|
||||
</label>
|
||||
<label>
|
||||
部門類型 <TypeSelect />
|
||||
</label>
|
||||
<button type="submit">新增</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="department-list">
|
||||
<h2 id="department-list">部門清單</h2>
|
||||
{departments.length === 0 ? (
|
||||
<p>尚未建立部門。</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>部門</th>
|
||||
<th>狀態</th>
|
||||
<th>部門主管</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{departments.map((d) => (
|
||||
<tr key={d.id} data-testid={`department-${d.id}`}>
|
||||
<td>
|
||||
<form action={updateDepartmentAction}>
|
||||
<input type="hidden" name="id" value={d.id} />
|
||||
<input name="name" defaultValue={d.name} aria-label="部門名稱" required />
|
||||
<input name="code" defaultValue={d.code ?? ""} aria-label="部門代碼" />
|
||||
<TypeSelect defaultValue={d.type} />
|
||||
<button type="submit">儲存</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
{d.active ? "啟用" : "已停用"}
|
||||
<form action={setDepartmentActiveAction}>
|
||||
<input type="hidden" name="id" value={d.id} />
|
||||
<input type="hidden" name="active" value={String(!d.active)} />
|
||||
<button type="submit">{d.active ? "停用" : "啟用"}</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<ul>
|
||||
{d.managers.map((m) => (
|
||||
<li key={m.userId}>
|
||||
{m.name ?? ""}({m.employeeNo})
|
||||
<form action={removeManagerAction}>
|
||||
<input type="hidden" name="departmentId" value={d.id} />
|
||||
<input type="hidden" name="userId" value={m.userId} />
|
||||
<button type="submit">移除</button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<form action={assignManagerAction}>
|
||||
<input type="hidden" name="departmentId" value={d.id} />
|
||||
<input name="employeeNo" aria-label="主管員工編號" required />
|
||||
<button type="submit">指派主管</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/admin/payments");
|
||||
return <RoutePlaceholder title="發放管理" change="add-company-settlement-and-payout" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/admin/settings");
|
||||
return <RoutePlaceholder title="後台設定" change="add-rule-settings" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/admin/settlements");
|
||||
return <RoutePlaceholder title="全公司月結" change="add-company-settlement-and-payout" />;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import {
|
||||
SESSION_COOKIE,
|
||||
appOrigin,
|
||||
cookieSecure,
|
||||
getOidcConfig,
|
||||
oidcRedirectUri,
|
||||
} from "@/server/auth/config";
|
||||
import { OIDC_TX_COOKIE, completeOidcLogin } from "@/server/auth/oidc";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
/** Authentik 登入完成後的 callback(路徑與 vibe.yaml 的 `auth.callback_path` 一致)。 */
|
||||
export async function GET(request: NextRequest) {
|
||||
const env = getEnv();
|
||||
if (env.AUTH_MODE !== "oidc") {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
const origin = appOrigin(env, request.url);
|
||||
// 以 APP_URL 重組 callback 網址:openid-client 會比對它與 redirect_uri。
|
||||
const callbackUrl = new URL(oidcRedirectUri(env));
|
||||
callbackUrl.search = request.nextUrl.search;
|
||||
|
||||
const result = await completeOidcLogin(await getOidcConfig(), {
|
||||
db: getDb(),
|
||||
callbackUrl,
|
||||
txCookie: request.cookies.get(OIDC_TX_COOKIE)?.value,
|
||||
secret: env.SESSION_SECRET,
|
||||
bootstrapSysadmins: env.BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS,
|
||||
now: new Date(),
|
||||
});
|
||||
|
||||
const response = NextResponse.redirect(
|
||||
new URL(result.ok ? result.returnTo : `/login?error=${result.error}`, origin),
|
||||
303,
|
||||
);
|
||||
response.cookies.delete({ name: OIDC_TX_COOKIE, path: "/api/auth" });
|
||||
if (result.ok) {
|
||||
response.cookies.set(SESSION_COOKIE, result.sessionToken, {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: cookieSecure(env),
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { appOrigin, cookieSecure, getOidcConfig, oidcRedirectUri } from "@/server/auth/config";
|
||||
import { OIDC_TX_COOKIE, OIDC_TX_MAX_AGE_SECONDS, startOidcLogin } from "@/server/auth/oidc";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
/** 開始公司登入:導向 Authentik。dev 模式改到替代登入頁。 */
|
||||
export async function GET(request: NextRequest) {
|
||||
const env = getEnv();
|
||||
const returnTo = request.nextUrl.searchParams.get("returnTo");
|
||||
if (env.AUTH_MODE === "dev") {
|
||||
const url = new URL("/login/dev", appOrigin(env, request.url));
|
||||
if (returnTo) url.searchParams.set("returnTo", returnTo);
|
||||
return NextResponse.redirect(url, 303);
|
||||
}
|
||||
|
||||
const { url, txCookie } = await startOidcLogin(await getOidcConfig(), {
|
||||
redirectUri: oidcRedirectUri(env),
|
||||
returnTo,
|
||||
secret: env.SESSION_SECRET,
|
||||
now: new Date(),
|
||||
});
|
||||
const response = NextResponse.redirect(url, 303);
|
||||
response.cookies.set(OIDC_TX_COOKIE, txCookie, {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: cookieSecure(env),
|
||||
path: "/api/auth",
|
||||
maxAge: OIDC_TX_MAX_AGE_SECONDS,
|
||||
});
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as client from "openid-client";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { SESSION_COOKIE, appOrigin, getOidcConfig } from "@/server/auth/config";
|
||||
import { deleteSession } from "@/server/auth/session";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
/**
|
||||
* 登出:結束本系統 session。oidc 模式下若 Authentik 提供 end-session endpoint 就導向它,
|
||||
* 否則回到登入頁。只保證結束本系統的 session。
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const env = getEnv();
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
||||
if (token) deleteSession(getDb(), token);
|
||||
|
||||
let target = new URL("/login", appOrigin(env, request.url));
|
||||
if (env.AUTH_MODE === "oidc") {
|
||||
try {
|
||||
const config = await getOidcConfig();
|
||||
if (config.serverMetadata().end_session_endpoint) {
|
||||
target = client.buildEndSessionUrl(config);
|
||||
}
|
||||
} catch {
|
||||
// discovery 失敗不影響本系統登出。
|
||||
}
|
||||
}
|
||||
const response = NextResponse.redirect(target, 303);
|
||||
response.cookies.delete(SESSION_COOKIE);
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
// 單筆資料範圍(本人/所轄部門/全部)由 add-subsidy-application 以 scopeApplications 檢查。
|
||||
await requireRouteAccess("/applications/:id");
|
||||
return <RoutePlaceholder title="申請詳情" change="add-subsidy-application" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/applications/new");
|
||||
return <RoutePlaceholder title="新增申請" change="add-subsidy-application" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/applications");
|
||||
return <RoutePlaceholder title="我的申請" change="add-subsidy-application" />;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import Link from "next/link";
|
||||
import { buildNavigation } from "@/lib/navigation";
|
||||
import { ROLE_LABELS } from "@/lib/roles";
|
||||
import { DEPARTMENT_REQUIRED_MESSAGE, requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
// 暫時首頁:全站框架(側欄、頂部列)與首頁卡片由 add-app-shell、add-role-dashboards 建立。
|
||||
export default async function DashboardPage() {
|
||||
const user = await requireRouteAccess("/dashboard");
|
||||
const nav = buildNavigation(user.roles);
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>AI 補助申請系統</h1>
|
||||
<p>
|
||||
{user.name ?? user.employeeNo}({user.roles.map((r) => ROLE_LABELS[r]).join("、")})
|
||||
</p>
|
||||
{user.departmentId === null && <p role="alert">{DEPARTMENT_REQUIRED_MESSAGE}。</p>}
|
||||
<nav aria-label="主要導覽">
|
||||
<ul>
|
||||
{nav.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link href={item.href}>{item.label}</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<form action="/api/auth/logout" method="post">
|
||||
<button type="submit">登出</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/department/review");
|
||||
return <RoutePlaceholder title="部門審核" change="add-manager-review" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { RoutePlaceholder } from "@/components/route-placeholder";
|
||||
import { requireRouteAccess } from "@/server/auth/current-user";
|
||||
|
||||
export default async function Page() {
|
||||
await requireRouteAccess("/department/settlement");
|
||||
return <RoutePlaceholder title="部門月結" change="add-department-settlement" />;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import Link from "next/link";
|
||||
|
||||
// requireRole/requireRouteAccess 呼叫 forbidden() 時顯示(HTTP 403)。暫時樣式,由 add-app-shell 統一。
|
||||
export default function Forbidden() {
|
||||
return (
|
||||
<main>
|
||||
<h1>無權限</h1>
|
||||
<p>您沒有權限存取這個頁面。如需權限,請洽系統管理員。</p>
|
||||
<Link href="/dashboard">回首頁</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+5
-1
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { DevModeBanner } from "@/components/dev-mode-banner";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -9,7 +10,10 @@ export const metadata: Metadata = {
|
||||
export default function RootLayout({ children }: LayoutProps<"/">) {
|
||||
return (
|
||||
<html lang="zh-Hant-TW">
|
||||
<body>{children}</body>
|
||||
<body>
|
||||
<DevModeBanner />
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"use server";
|
||||
|
||||
import { cookies } from "next/headers";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { SESSION_COOKIE, cookieSecure } from "@/server/auth/config";
|
||||
import { devLogin, isDevLoginEnabled } from "@/server/auth/dev-login";
|
||||
import { safeReturnTo } from "@/server/auth/return-to";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
export async function devLoginAction(formData: FormData) {
|
||||
const env = getEnv();
|
||||
// action 可被直接呼叫,不能只靠頁面擋:oidc 模式下一律 404。
|
||||
if (!isDevLoginEnabled(env)) notFound();
|
||||
|
||||
const employeeNo = String(formData.get("employeeNo") ?? "");
|
||||
const returnTo = safeReturnTo(String(formData.get("returnTo") ?? ""));
|
||||
const result = devLogin(getDb(), env, employeeNo, new Date());
|
||||
if (!result.ok) {
|
||||
redirect(`/login/dev?error=${result.reason}`);
|
||||
}
|
||||
(await cookies()).set(SESSION_COOKIE, result.sessionToken, {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: cookieSecure(env),
|
||||
path: "/",
|
||||
});
|
||||
redirect(returnTo);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { asc } from "drizzle-orm";
|
||||
import { notFound } from "next/navigation";
|
||||
import { isDevLoginEnabled } from "@/server/auth/dev-login";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { users } from "@/server/db/schema";
|
||||
import { getEnv } from "@/server/env";
|
||||
import { devLoginAction } from "./actions";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const ERROR_MESSAGES: Record<string, string> = {
|
||||
missing_employee_number: "請輸入員工編號。",
|
||||
inactive: "帳號已停用,請洽人資。",
|
||||
};
|
||||
|
||||
// 暫時樣式:全站框架與設計 tokens 由 add-app-shell 建立。
|
||||
export default async function DevLoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ error?: string; returnTo?: string }>;
|
||||
}) {
|
||||
if (!isDevLoginEnabled(getEnv())) notFound();
|
||||
const { error, returnTo } = await searchParams;
|
||||
const existing = getDb()
|
||||
.select({ employeeNo: users.employeeNo, name: users.name, active: users.active })
|
||||
.from(users)
|
||||
.orderBy(asc(users.employeeNo))
|
||||
.all();
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>開發登入</h1>
|
||||
<p>只在非正式環境提供:以員工編號直接登入,不經公司帳號驗證。</p>
|
||||
{error && <p role="alert">{ERROR_MESSAGES[error] ?? "登入失敗。"}</p>}
|
||||
<form action={devLoginAction}>
|
||||
<input type="hidden" name="returnTo" value={returnTo ?? ""} />
|
||||
<label htmlFor="employeeNo">員工編號</label>
|
||||
<input id="employeeNo" name="employeeNo" list="known-employees" required />
|
||||
<datalist id="known-employees">
|
||||
{existing.map((u) => (
|
||||
<option key={u.employeeNo} value={u.employeeNo}>
|
||||
{u.name ?? ""}
|
||||
{u.active ? "" : "(已停用)"}
|
||||
</option>
|
||||
))}
|
||||
</datalist>
|
||||
<button type="submit">登入</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Link from "next/link";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const ERROR_MESSAGES: Record<string, string> = {
|
||||
failed: "登入失敗,請重新登入。",
|
||||
missing_employee_number: "無法取得員工編號,請洽系統管理員。",
|
||||
inactive: "帳號已停用,請洽人資。",
|
||||
};
|
||||
|
||||
// 暫時樣式:全站框架與設計 tokens 由 add-app-shell 建立。
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ error?: string; returnTo?: string }>;
|
||||
}) {
|
||||
const { error, returnTo } = await searchParams;
|
||||
const devMode = getEnv().AUTH_MODE === "dev";
|
||||
const loginHref = returnTo
|
||||
? `/api/auth/login?returnTo=${encodeURIComponent(returnTo)}`
|
||||
: "/api/auth/login";
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>AI 補助申請系統</h1>
|
||||
{error && <p role="alert">{ERROR_MESSAGES[error] ?? ERROR_MESSAGES.failed}</p>}
|
||||
{devMode ? (
|
||||
<p>
|
||||
目前為開發登入模式。
|
||||
<Link
|
||||
href={returnTo ? `/login/dev?returnTo=${encodeURIComponent(returnTo)}` : "/login/dev"}
|
||||
>
|
||||
以員工編號登入
|
||||
</Link>
|
||||
</p>
|
||||
) : (
|
||||
// 一般連結即可:/api/auth/login 會 303 導向 Authentik。
|
||||
<a href={loginHref}>以公司帳號登入</a>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+4
-7
@@ -1,9 +1,6 @@
|
||||
// 暫時首頁:全站框架與 Dashboard 由 add-app-shell、add-role-dashboards 建立。
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// 根路徑:未登入時由 proxy 導向 /login,已登入則進首頁。
|
||||
export default function Home() {
|
||||
return (
|
||||
<main>
|
||||
<h1>AI 補助申請系統</h1>
|
||||
<p>AI Subsidy Application System</p>
|
||||
</main>
|
||||
);
|
||||
redirect("/dashboard");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { connection } from "next/server";
|
||||
import { getEnv } from "@/server/env";
|
||||
|
||||
/**
|
||||
* 開發登入模式警示條。layout 會在 build 時預先渲染,那時沒有執行環境的設定,
|
||||
* 所以先 `connection()` 讓它在請求時才渲染。
|
||||
*/
|
||||
export async function DevModeBanner() {
|
||||
await connection();
|
||||
if (getEnv().AUTH_MODE !== "dev") return null;
|
||||
return (
|
||||
<div role="status" data-testid="dev-mode-banner">
|
||||
開發登入模式:可用員工編號直接登入,僅限非正式環境。
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// 路由已受權限保護、但頁面內容尚未建立時的佔位畫面;由各功能 change 替換。
|
||||
export function RoutePlaceholder({ title, change }: { title: string; change: string }) {
|
||||
return (
|
||||
<main>
|
||||
<h1>{title}</h1>
|
||||
<p>此頁面將於 {change} 建立。</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { localDate } from "./calendar";
|
||||
|
||||
describe("localDate", () => {
|
||||
it("以指定時區決定日期", () => {
|
||||
// UTC 10/31 16:30 = 台北 11/01 00:30
|
||||
const instant = new Date("2026-10-31T16:30:00Z");
|
||||
expect(localDate(instant, "Asia/Taipei")).toBe("2026-11-01");
|
||||
expect(localDate(instant, "UTC")).toBe("2026-10-31");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* 某個時間點在指定時區的日期(`YYYY-MM-DD`)。業務上的「今天」、生效日都以 Asia/Taipei 計算,
|
||||
* 不能用 UTC 日期——台北 00:00~07:59 時 UTC 還是前一天。
|
||||
*/
|
||||
export function localDate(instant: Date, timeZone: string): string {
|
||||
// en-CA 的日期格式就是 YYYY-MM-DD。
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(instant);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { canAccessRoute, findRouteRule } from "./access";
|
||||
import type { Role } from "./roles";
|
||||
|
||||
// 前端規劃 §11 的每條路由,四種角色各自的預期結果(Y = 允許)。
|
||||
const MATRIX: [
|
||||
path: string,
|
||||
employee: boolean,
|
||||
manager: boolean,
|
||||
admin: boolean,
|
||||
sysadmin: boolean,
|
||||
][] = [
|
||||
["/dashboard", true, true, true, true],
|
||||
["/applications/new", true, false, false, false],
|
||||
["/applications", true, false, false, false],
|
||||
["/applications/42", true, true, true, false],
|
||||
["/department/review", false, true, false, false],
|
||||
["/department/settlement", false, true, false, false],
|
||||
["/admin/settlements", false, false, true, false],
|
||||
["/admin/payments", false, false, true, false],
|
||||
["/admin/settings", false, false, true, true],
|
||||
["/admin/audit-log", false, false, false, true],
|
||||
["/admin/accounts", false, false, false, true],
|
||||
["/admin/accounts/import", false, false, false, true],
|
||||
["/admin/accounts/import/template", false, false, false, true],
|
||||
["/admin/departments", false, false, false, true],
|
||||
];
|
||||
|
||||
const ROLE_ORDER: Role[] = ["employee", "manager", "admin", "sysadmin"];
|
||||
|
||||
describe("canAccessRoute", () => {
|
||||
for (const [path, ...expected] of MATRIX) {
|
||||
ROLE_ORDER.forEach((role, i) => {
|
||||
it(`${role} ${expected[i] ? "可" : "不可"}進入 ${path}`, () => {
|
||||
expect(canAccessRoute(path, [role])).toBe(expected[i]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
it("兼任角色取聯集", () => {
|
||||
expect(canAccessRoute("/department/review", ["employee", "manager"])).toBe(true);
|
||||
expect(canAccessRoute("/applications/new", ["employee", "manager"])).toBe(true);
|
||||
});
|
||||
|
||||
it("未列出的路由一律拒絕", () => {
|
||||
expect(canAccessRoute("/admin/secret", ["sysadmin", "admin", "manager", "employee"])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("/applications/new 精確比對,不會被當成詳情頁", () => {
|
||||
expect(findRouteRule("/applications/new")?.pattern).toBe("/applications/new");
|
||||
});
|
||||
|
||||
it("忽略 query string", () => {
|
||||
expect(canAccessRoute("/admin/settlements?month=2026-10", ["admin"])).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Role } from "./roles";
|
||||
|
||||
/**
|
||||
* 路由 → 允許角色(前端規劃 §11,加上本系統的帳號與部門管理頁)。
|
||||
* 伺服器端的路由檢查與側欄導覽都由這份設定產生,兩者不會不一致。
|
||||
* `:id` 比對任一段。未列出的路由一律拒絕(fail closed)。
|
||||
*/
|
||||
export const ROUTE_RULES: readonly { pattern: string; roles: readonly Role[] }[] = [
|
||||
{ pattern: "/", roles: ["employee", "manager", "admin", "sysadmin"] },
|
||||
{ pattern: "/dashboard", roles: ["employee", "manager", "admin", "sysadmin"] },
|
||||
{ pattern: "/applications", roles: ["employee"] },
|
||||
{ pattern: "/applications/new", roles: ["employee"] },
|
||||
// 詳情頁的資料範圍另由 scopeApplications 檢查。
|
||||
{ pattern: "/applications/:id", roles: ["employee", "manager", "admin"] },
|
||||
{ pattern: "/department/review", roles: ["manager"] },
|
||||
{ pattern: "/department/settlement", roles: ["manager"] },
|
||||
{ pattern: "/admin/settlements", roles: ["admin"] },
|
||||
{ pattern: "/admin/payments", roles: ["admin"] },
|
||||
{ pattern: "/admin/settings", roles: ["admin", "sysadmin"] },
|
||||
// 「經授權的管理者」由 add-audit-trail 擴充。
|
||||
{ pattern: "/admin/audit-log", roles: ["sysadmin"] },
|
||||
{ pattern: "/admin/accounts", roles: ["sysadmin"] },
|
||||
{ pattern: "/admin/accounts/import", roles: ["sysadmin"] },
|
||||
{ pattern: "/admin/accounts/import/template", roles: ["sysadmin"] },
|
||||
{ pattern: "/admin/departments", roles: ["sysadmin"] },
|
||||
];
|
||||
|
||||
function segments(path: string): string[] {
|
||||
return path.split("?")[0].split("/").filter(Boolean);
|
||||
}
|
||||
|
||||
function matches(pattern: string, path: string): boolean {
|
||||
const p = segments(pattern);
|
||||
const s = segments(path);
|
||||
return p.length === s.length && p.every((seg, i) => seg === ":id" || seg === s[i]);
|
||||
}
|
||||
|
||||
/** 找出路由對應的規則;精確比對優先於 `:id`(`/applications/new` 不會被當成詳情頁)。 */
|
||||
export function findRouteRule(path: string) {
|
||||
const candidates = ROUTE_RULES.filter((rule) => matches(rule.pattern, path));
|
||||
return candidates.find((rule) => !rule.pattern.includes(":id")) ?? candidates[0];
|
||||
}
|
||||
|
||||
export function canAccessRoute(path: string, roles: readonly Role[]): boolean {
|
||||
const rule = findRouteRule(path);
|
||||
return rule !== undefined && rule.roles.some((role) => roles.includes(role));
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseCsv, toCsv } from "./csv";
|
||||
|
||||
describe("parseCsv", () => {
|
||||
it("一般欄位、CRLF 與結尾換行", () => {
|
||||
expect(parseCsv("a,b\r\n1,2\r\n")).toEqual([
|
||||
["a", "b"],
|
||||
["1", "2"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("去除 UTF-8 BOM", () => {
|
||||
expect(parseCsv("員工編號,姓名\nE1,王")).toEqual([
|
||||
["員工編號", "姓名"],
|
||||
["E1", "王"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("引號內的逗號、換行與跳脫的雙引號", () => {
|
||||
expect(parseCsv('a,"b,c","line1\nline2","say ""hi"""')).toEqual([
|
||||
["a", "b,c", "line1\nline2", 'say "hi"'],
|
||||
]);
|
||||
});
|
||||
|
||||
it("略過空白列,保留空欄位", () => {
|
||||
expect(parseCsv("a,,c\n\n , \nd,e,")).toEqual([
|
||||
["a", "", "c"],
|
||||
["d", "e", ""],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toCsv", () => {
|
||||
it("需要時加引號,且可被 parseCsv 還原", () => {
|
||||
const rows = [
|
||||
["員工編號", "備註"],
|
||||
["E1", '含,逗號與"引號"'],
|
||||
];
|
||||
expect(parseCsv(toCsv(rows))).toEqual(rows);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* 最小的 RFC 4180 CSV 解析:支援雙引號欄位(含逗號、換行、`""` 跳脫)、CRLF/LF、UTF-8 BOM。
|
||||
* 回傳每列欄位陣列,略過完全空白的列。
|
||||
*/
|
||||
export function parseCsv(input: string): string[][] {
|
||||
const text = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = "";
|
||||
let quoted = false;
|
||||
|
||||
const endField = () => {
|
||||
row.push(field);
|
||||
field = "";
|
||||
};
|
||||
const endRow = () => {
|
||||
endField();
|
||||
if (row.some((cell) => cell.trim() !== "")) rows.push(row);
|
||||
row = [];
|
||||
};
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (quoted) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else {
|
||||
quoted = false;
|
||||
}
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
} else if (ch === '"' && field === "") {
|
||||
quoted = true;
|
||||
} else if (ch === ",") {
|
||||
endField();
|
||||
} else if (ch === "\n" || ch === "\r") {
|
||||
if (ch === "\r" && text[i + 1] === "\n") i++;
|
||||
endRow();
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
}
|
||||
if (field !== "" || row.length > 0) endRow();
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 產生 CSV 文字(必要時加引號),開頭加 BOM 讓 Excel 以 UTF-8 開啟。 */
|
||||
export function toCsv(rows: readonly (readonly string[])[]): string {
|
||||
const cell = (v: string) => (/[",\r\n]/.test(v) ? `"${v.replaceAll('"', '""')}"` : v);
|
||||
return "" + rows.map((r) => r.map(cell).join(",")).join("\r\n") + "\r\n";
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// 部門類型決定適用的每人月額度(一般 NT$500、研發 NT$1,000,實際值由後台參數設定)。
|
||||
export const DEPARTMENT_TYPES = ["general", "rnd"] as const;
|
||||
export type DepartmentType = (typeof DEPARTMENT_TYPES)[number];
|
||||
|
||||
export const DEPARTMENT_TYPE_LABELS: Record<DepartmentType, string> = {
|
||||
general: "一般",
|
||||
rnd: "研發",
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildNavigation } from "./navigation";
|
||||
import type { Role } from "./roles";
|
||||
|
||||
const labels = (roles: Role[]) => buildNavigation(roles).map((item) => item.label);
|
||||
|
||||
describe("buildNavigation", () => {
|
||||
it("員工:首頁、新增申請、我的申請", () => {
|
||||
expect(labels(["employee"])).toEqual(["首頁", "新增申請", "我的申請"]);
|
||||
});
|
||||
|
||||
it("員工看不到部門審核、全公司月結、後台設定等管理項目", () => {
|
||||
const items = labels(["employee"]);
|
||||
for (const label of [
|
||||
"部門審核",
|
||||
"部門月結",
|
||||
"全公司月結",
|
||||
"發放管理",
|
||||
"後台設定",
|
||||
"操作紀錄",
|
||||
]) {
|
||||
expect(items).not.toContain(label);
|
||||
}
|
||||
});
|
||||
|
||||
it("主管(兼員工):加上部門審核、部門月結", () => {
|
||||
expect(labels(["employee", "manager"])).toEqual([
|
||||
"首頁",
|
||||
"新增申請",
|
||||
"我的申請",
|
||||
"部門審核",
|
||||
"部門月結",
|
||||
]);
|
||||
});
|
||||
|
||||
it("管理者(兼員工):加上全公司月結、發放管理、後台設定", () => {
|
||||
expect(labels(["employee", "admin"])).toEqual([
|
||||
"首頁",
|
||||
"新增申請",
|
||||
"我的申請",
|
||||
"全公司月結",
|
||||
"發放管理",
|
||||
"後台設定",
|
||||
]);
|
||||
});
|
||||
|
||||
it("系統管理員(兼員工):加上後台設定、帳號與角色、部門管理、操作紀錄", () => {
|
||||
expect(labels(["employee", "sysadmin"])).toEqual([
|
||||
"首頁",
|
||||
"新增申請",
|
||||
"我的申請",
|
||||
"後台設定",
|
||||
"帳號與角色",
|
||||
"部門管理",
|
||||
"操作紀錄",
|
||||
]);
|
||||
});
|
||||
|
||||
it("同時兼任多個角色時取聯集且不重複", () => {
|
||||
const items = labels(["employee", "manager", "admin", "sysadmin"]);
|
||||
expect(items).toHaveLength(11);
|
||||
expect(new Set(items).size).toBe(items.length);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { canAccessRoute } from "./access";
|
||||
import type { Role } from "./roles";
|
||||
|
||||
export interface NavItem {
|
||||
label: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
/** 側欄項目(前端規劃 §11)。顯示與否完全由 ROUTE_RULES 決定,與伺服器端路由檢查同源。 */
|
||||
const NAV_ITEMS: readonly NavItem[] = [
|
||||
{ label: "首頁", href: "/dashboard" },
|
||||
{ label: "新增申請", href: "/applications/new" },
|
||||
{ label: "我的申請", href: "/applications" },
|
||||
{ label: "部門審核", href: "/department/review" },
|
||||
{ label: "部門月結", href: "/department/settlement" },
|
||||
{ label: "全公司月結", href: "/admin/settlements" },
|
||||
{ label: "發放管理", href: "/admin/payments" },
|
||||
{ label: "後台設定", href: "/admin/settings" },
|
||||
{ label: "帳號與角色", href: "/admin/accounts" },
|
||||
{ label: "部門管理", href: "/admin/departments" },
|
||||
{ label: "操作紀錄", href: "/admin/audit-log" },
|
||||
];
|
||||
|
||||
/** 依角色產生側欄導覽資料(供 add-app-shell 使用)。兼任角色取聯集。 */
|
||||
export function buildNavigation(roles: readonly Role[]): NavItem[] {
|
||||
return NAV_ITEMS.filter((item) => canAccessRoute(item.href, roles));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// 角色定義。放在 src/lib 讓前端(導覽)與伺服器(schema、權限檢查)共用同一份。
|
||||
|
||||
export const ROLES = ["employee", "manager", "admin", "sysadmin"] as const;
|
||||
export type Role = (typeof ROLES)[number];
|
||||
|
||||
export const ROLE_LABELS: Record<Role, string> = {
|
||||
employee: "員工",
|
||||
manager: "部門主管",
|
||||
admin: "管理者",
|
||||
sysadmin: "系統管理員",
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod";
|
||||
import { DEPARTMENT_TYPES } from "@/lib/department-types";
|
||||
|
||||
/** 部門表單驗證(前後端共用)。部門代碼選填;空白視為未填。 */
|
||||
export const departmentInput = z.object({
|
||||
name: z.string().trim().min(1, "請輸入部門名稱").max(50, "部門名稱最多 50 字"),
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(30, "部門代碼最多 30 字")
|
||||
.nullish()
|
||||
.transform((v) => (v ? v : null)),
|
||||
type: z.enum(DEPARTMENT_TYPES, { error: "請選擇部門類型" }),
|
||||
});
|
||||
|
||||
export type DepartmentInput = z.input<typeof departmentInput>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
// 與 src/server/auth/config.ts 的 SESSION_COOKIE 相同;proxy 不 import 伺服器模組,避免拉進資料庫連線。
|
||||
const SESSION_COOKIE = "aisubsidy_session";
|
||||
|
||||
/**
|
||||
* 樂觀檢查:沒有 session cookie 就導向登入頁並記住原本要去的頁面。
|
||||
* 不讀資料庫——session 是否有效、角色是否符合,由每個頁面與 action 的 requireRouteAccess/requireRole 檢查。
|
||||
*/
|
||||
export function proxy(request: NextRequest) {
|
||||
if (request.cookies.has(SESSION_COOKIE)) return NextResponse.next();
|
||||
const login = new URL("/login", request.url);
|
||||
const { pathname, search } = request.nextUrl;
|
||||
if (pathname !== "/") login.searchParams.set("returnTo", pathname + search);
|
||||
return NextResponse.redirect(login);
|
||||
}
|
||||
|
||||
export const config = {
|
||||
// 登入流程、Next.js 內部資源與靜態檔不需要登入。
|
||||
matcher: ["/((?!login|api/auth|_next/static|_next/image|favicon.ico).*)"],
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Configuration } from "openid-client";
|
||||
import type { Env } from "@/server/env";
|
||||
import { getEnv } from "@/server/env";
|
||||
import { OIDC_CALLBACK_PATH, discoverOidc } from "./oidc";
|
||||
|
||||
export const SESSION_COOKIE = "aisubsidy_session";
|
||||
|
||||
/** 平台對 redirect URI 做 strict 比對,所以以 APP_URL 組出,不從請求推測(容器內看到的 host 不同)。 */
|
||||
export function oidcRedirectUri(env: Env): string {
|
||||
return new URL(OIDC_CALLBACK_PATH, env.APP_URL).toString();
|
||||
}
|
||||
|
||||
/** 站內導向的基準網址:oidc 模式用 APP_URL,dev 模式用請求本身的 origin。 */
|
||||
export function appOrigin(env: Env, requestUrl: string): string {
|
||||
return env.AUTH_MODE === "oidc" && env.APP_URL
|
||||
? new URL(env.APP_URL).origin
|
||||
: new URL(requestUrl).origin;
|
||||
}
|
||||
|
||||
export function cookieSecure(env: Env): boolean {
|
||||
return env.APP_URL?.startsWith("https://") ?? false;
|
||||
}
|
||||
|
||||
let configPromise: Promise<Configuration> | undefined;
|
||||
|
||||
/** OIDC discovery 結果在程序內快取;失敗時清掉快取,下次請求重試。 */
|
||||
export function getOidcConfig(): Promise<Configuration> {
|
||||
const env = getEnv();
|
||||
configPromise ??= discoverOidc({
|
||||
issuer: env.OIDC_ISSUER!,
|
||||
clientId: env.OIDC_CLIENT_ID!,
|
||||
clientSecret: env.OIDC_CLIENT_SECRET!,
|
||||
}).catch((error: unknown) => {
|
||||
configPromise = undefined;
|
||||
throw error;
|
||||
});
|
||||
return configPromise;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DepartmentRequiredError, hasAnyRole, requireDepartment } from "./current-user";
|
||||
|
||||
describe("requireDepartment", () => {
|
||||
it("待指派部門者被拒絕,訊息提示洽人資", () => {
|
||||
expect(() => requireDepartment({ departmentId: null })).toThrow(DepartmentRequiredError);
|
||||
expect(() => requireDepartment({ departmentId: null })).toThrow("尚未指派部門,請洽人資");
|
||||
});
|
||||
|
||||
it("已指派部門者通過", () => {
|
||||
expect(requireDepartment({ departmentId: 3 }).departmentId).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasAnyRole", () => {
|
||||
it("具備任一角色即可", () => {
|
||||
expect(hasAnyRole({ roles: ["employee", "manager"] }, ["manager"])).toBe(true);
|
||||
expect(hasAnyRole({ roles: ["employee"] }, ["manager", "admin"])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { cookies } from "next/headers";
|
||||
import { forbidden, redirect } from "next/navigation";
|
||||
import { cache } from "react";
|
||||
import { canAccessRoute } from "@/lib/access";
|
||||
import type { Role } from "@/lib/roles";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { getDb } from "@/server/db/client";
|
||||
import { userRoles } from "@/server/db/schema";
|
||||
import { SESSION_COOKIE } from "./config";
|
||||
import { validateSession, type SessionUser } from "./session";
|
||||
|
||||
export interface CurrentUser extends SessionUser {
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
export function loadRoles(db: Db, userId: number): Role[] {
|
||||
return db
|
||||
.select({ role: userRoles.role })
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, userId))
|
||||
.all()
|
||||
.map((r) => r.role);
|
||||
}
|
||||
|
||||
/** 目前請求的登入者;未登入或 session 失效時為 null。同一個請求內只查一次。 */
|
||||
export const getCurrentUser = cache(async (): Promise<CurrentUser | null> => {
|
||||
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
if (!token) return null;
|
||||
const db = getDb();
|
||||
const user = validateSession(db, token, new Date());
|
||||
return user ? { ...user, roles: loadRoles(db, user.id) } : null;
|
||||
});
|
||||
|
||||
/** 頁面、Server Action、Route Handler 的入口:未登入導向登入頁。 */
|
||||
export async function requireUser(): Promise<CurrentUser> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/login");
|
||||
return user;
|
||||
}
|
||||
|
||||
export function hasAnyRole(user: Pick<CurrentUser, "roles">, roles: readonly Role[]): boolean {
|
||||
return roles.some((role) => user.roles.includes(role));
|
||||
}
|
||||
|
||||
/** 需具備其中一個角色,否則回應 403 無權限頁。 */
|
||||
export async function requireRole(...roles: Role[]): Promise<CurrentUser> {
|
||||
const user = await requireUser();
|
||||
if (!hasAnyRole(user, roles)) forbidden();
|
||||
return user;
|
||||
}
|
||||
|
||||
/** route group layout 用:依 ROUTE_RULES 檢查目前路由。 */
|
||||
export async function requireRouteAccess(pathname: string): Promise<CurrentUser> {
|
||||
const user = await requireUser();
|
||||
if (!canAccessRoute(pathname, user.roles)) forbidden();
|
||||
return user;
|
||||
}
|
||||
|
||||
export const DEPARTMENT_REQUIRED_MESSAGE = "尚未指派部門,請洽人資";
|
||||
|
||||
export class DepartmentRequiredError extends Error {
|
||||
constructor() {
|
||||
super(DEPARTMENT_REQUIRED_MESSAGE);
|
||||
this.name = "DepartmentRequiredError";
|
||||
}
|
||||
}
|
||||
|
||||
/** 建立申請前呼叫:待指派部門的使用者不得建立或送出申請。 */
|
||||
export function requireDepartment<T extends Pick<SessionUser, "departmentId">>(
|
||||
user: T,
|
||||
): T & { departmentId: number } {
|
||||
if (user.departmentId === null) throw new DepartmentRequiredError();
|
||||
return user as T & { departmentId: number };
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { users } from "@/server/db/schema";
|
||||
import { parseEnv } from "@/server/env";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { DevLoginDisabledError, devLogin, isDevLoginEnabled } from "./dev-login";
|
||||
|
||||
const secret = "x".repeat(32);
|
||||
const devEnv = parseEnv({ SESSION_SECRET: secret, AUTH_MODE: "dev" });
|
||||
const oidcEnv = parseEnv({
|
||||
SESSION_SECRET: secret,
|
||||
OIDC_ISSUER: "https://auth.example/application/o/vibe-x/",
|
||||
OIDC_CLIENT_ID: "id",
|
||||
OIDC_CLIENT_SECRET: "secret",
|
||||
APP_URL: "https://x-vibe.example",
|
||||
});
|
||||
|
||||
describe("替代登入", () => {
|
||||
let t: TestDatabase;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
it("dev 模式以員工編號登入,套用首次登入建帳號規則", () => {
|
||||
const result = devLogin(t.db, devEnv, "E1234", new Date());
|
||||
expect(result).toMatchObject({ ok: true, created: true });
|
||||
expect(t.db.select().from(users).get()).toMatchObject({
|
||||
employeeNo: "E1234",
|
||||
departmentId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("oidc 模式下不可用,也不建立帳號", () => {
|
||||
expect(isDevLoginEnabled(oidcEnv)).toBe(false);
|
||||
expect(() => devLogin(t.db, oidcEnv, "E1234", new Date())).toThrow(DevLoginDisabledError);
|
||||
expect(t.db.select().from(users).all()).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Db } from "@/server/db/client";
|
||||
import type { Env } from "@/server/env";
|
||||
import { provisionOnLogin, type ProvisionResult } from "./provision";
|
||||
|
||||
export class DevLoginDisabledError extends Error {
|
||||
constructor() {
|
||||
super("替代登入只在 AUTH_MODE=dev 時開啟");
|
||||
this.name = "DevLoginDisabledError";
|
||||
}
|
||||
}
|
||||
|
||||
export function isDevLoginEnabled(env: Env): boolean {
|
||||
return env.AUTH_MODE === "dev";
|
||||
}
|
||||
|
||||
/**
|
||||
* 非正式環境的替代登入:以員工編號直接登入,套用與公司登入相同的帳號規則。
|
||||
* `AUTH_MODE` 不是 dev 時一律丟出錯誤(頁面與 action 轉為 404)。
|
||||
*/
|
||||
export function devLogin(db: Db, env: Env, employeeNo: string, now: Date): ProvisionResult {
|
||||
if (!isDevLoginEnabled(env)) throw new DevLoginDisabledError();
|
||||
return provisionOnLogin(
|
||||
db,
|
||||
{ employeeNumber: employeeNo },
|
||||
{ bootstrapSysadmins: env.BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS, now },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Configuration } from "openid-client";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { users } from "@/server/db/schema";
|
||||
import { startMockOidcProvider } from "@/server/testing/mock-oidc";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { OIDC_SCOPE, completeOidcLogin, discoverOidc, startOidcLogin } from "./oidc";
|
||||
import { validateSession } from "./session";
|
||||
|
||||
const CLIENT_ID = "vibe-aisubsidy";
|
||||
const secret = "s".repeat(32);
|
||||
const redirectUri = "https://aisubsidy-vibe.moonshine-studio.net/api/auth/callback/authentik";
|
||||
|
||||
describe("公司登入(OIDC)", () => {
|
||||
let provider: Awaited<ReturnType<typeof startMockOidcProvider>>;
|
||||
let config: Configuration;
|
||||
let t: TestDatabase;
|
||||
|
||||
beforeAll(async () => {
|
||||
provider = await startMockOidcProvider(CLIENT_ID);
|
||||
config = await discoverOidc({
|
||||
issuer: provider.issuer,
|
||||
clientId: CLIENT_ID,
|
||||
clientSecret: "client-secret",
|
||||
allowInsecure: true,
|
||||
});
|
||||
});
|
||||
afterAll(() => provider.close());
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
/** 走完整個流程:開始登入 → 使用者在 provider 登入 → callback。 */
|
||||
async function login(
|
||||
claims: Record<string, unknown>,
|
||||
tamper: { state?: string; returnTo?: string | null; txCookie?: string } = {},
|
||||
) {
|
||||
const now = new Date();
|
||||
const start = await startOidcLogin(config, {
|
||||
redirectUri,
|
||||
returnTo: tamper.returnTo === undefined ? "/applications/new" : tamper.returnTo,
|
||||
secret,
|
||||
now,
|
||||
});
|
||||
const code = provider.issueCode(start.url, claims);
|
||||
const callbackUrl = new URL(redirectUri);
|
||||
callbackUrl.searchParams.set("code", code);
|
||||
callbackUrl.searchParams.set("state", tamper.state ?? start.url.searchParams.get("state")!);
|
||||
const result = await completeOidcLogin(config, {
|
||||
db: t.db,
|
||||
callbackUrl,
|
||||
txCookie: tamper.txCookie ?? start.txCookie,
|
||||
secret,
|
||||
bootstrapSysadmins: [],
|
||||
now,
|
||||
});
|
||||
return { start, result };
|
||||
}
|
||||
|
||||
it("授權網址請求 employee_number scope 並使用 PKCE", async () => {
|
||||
const { start } = await login({ employee_number: "E1234" });
|
||||
expect(start.url.searchParams.get("scope")).toBe(OIDC_SCOPE);
|
||||
expect(OIDC_SCOPE.split(" ")).toContain("employee_number");
|
||||
expect(start.url.searchParams.get("code_challenge_method")).toBe("S256");
|
||||
expect(start.url.searchParams.get("redirect_uri")).toBe(redirectUri);
|
||||
});
|
||||
|
||||
it("成功登入:建立帳號與有效 session,導向原本要去的頁面", async () => {
|
||||
const { result } = await login({
|
||||
employee_number: "E1234",
|
||||
name: "王小明",
|
||||
email: "[email protected]",
|
||||
});
|
||||
expect(result).toMatchObject({ ok: true, created: true, returnTo: "/applications/new" });
|
||||
if (!result.ok) return;
|
||||
expect(validateSession(t.db, result.sessionToken, new Date())).toMatchObject({
|
||||
employeeNo: "E1234",
|
||||
name: "王小明",
|
||||
});
|
||||
});
|
||||
|
||||
it("沒有指定頁面時導向 /dashboard;站外網址一律改為 /dashboard", async () => {
|
||||
expect((await login({ employee_number: "E1" }, { returnTo: null })).result).toMatchObject({
|
||||
returnTo: "/dashboard",
|
||||
});
|
||||
expect(
|
||||
(await login({ employee_number: "E1" }, { returnTo: "//evil.example" })).result,
|
||||
).toMatchObject({ returnTo: "/dashboard" });
|
||||
});
|
||||
|
||||
it("state 不符時拒絕,不建立帳號", async () => {
|
||||
const { result } = await login({ employee_number: "E1234" }, { state: "forged" });
|
||||
expect(result).toMatchObject({ ok: false, error: "failed" });
|
||||
expect(t.db.select().from(users).all()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("暫存 cookie 被竄改時拒絕", async () => {
|
||||
const { result } = await login({ employee_number: "E1234" }, { txCookie: "abc.def" });
|
||||
expect(result).toMatchObject({ ok: false, error: "failed" });
|
||||
});
|
||||
|
||||
it("ID token 沒有 employee_number 時拒絕,不建立帳號", async () => {
|
||||
const { result } = await login({ name: "沒有工號" });
|
||||
expect(result).toMatchObject({ ok: false, error: "missing_employee_number" });
|
||||
expect(t.db.select().from(users).all()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("已停用帳號拒絕登入", async () => {
|
||||
t.db.insert(users).values({ employeeNo: "E1234", active: false }).run();
|
||||
const { result } = await login({ employee_number: "E1234" });
|
||||
expect(result).toMatchObject({ ok: false, error: "inactive", employeeNo: "E1234" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import * as client from "openid-client";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { provisionOnLogin, type LoginRejectReason } from "./provision";
|
||||
import { safeReturnTo } from "./return-to";
|
||||
import { signValue, verifyValue } from "./signed-cookie";
|
||||
|
||||
/** 平台要求請求 `employee_number`,ID token 才會帶員工編號。 */
|
||||
export const OIDC_SCOPE = "openid profile email employee_number";
|
||||
export const OIDC_CALLBACK_PATH = "/api/auth/callback/authentik";
|
||||
/** 登入進行中的暫存 cookie(state、nonce、PKCE、導向位置),10 分鐘內有效。 */
|
||||
export const OIDC_TX_COOKIE = "aisubsidy_oidc_tx";
|
||||
export const OIDC_TX_MAX_AGE_SECONDS = 600;
|
||||
|
||||
interface OidcTransaction {
|
||||
state: string;
|
||||
nonce: string;
|
||||
codeVerifier: string;
|
||||
returnTo: string;
|
||||
/** 建立時間(epoch ms),超過有效期即拒絕。 */
|
||||
issuedAt: number;
|
||||
}
|
||||
|
||||
export interface OidcSettings {
|
||||
issuer: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
/** 測試用的模擬 provider 走 http,需要放寬。正式環境不可使用。 */
|
||||
allowInsecure?: boolean;
|
||||
}
|
||||
|
||||
export function discoverOidc(settings: OidcSettings): Promise<client.Configuration> {
|
||||
return client.discovery(
|
||||
new URL(settings.issuer),
|
||||
settings.clientId,
|
||||
settings.clientSecret,
|
||||
undefined,
|
||||
settings.allowInsecure ? { execute: [client.allowInsecureRequests] } : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
/** 開始登入:產生 state、nonce、PKCE,回傳 Authentik 授權網址與要寫入的暫存 cookie 值。 */
|
||||
export async function startOidcLogin(
|
||||
config: client.Configuration,
|
||||
{
|
||||
redirectUri,
|
||||
returnTo,
|
||||
secret,
|
||||
now,
|
||||
}: {
|
||||
redirectUri: string;
|
||||
returnTo: string | null;
|
||||
secret: string;
|
||||
now: Date;
|
||||
},
|
||||
): Promise<{ url: URL; txCookie: string }> {
|
||||
const codeVerifier = client.randomPKCECodeVerifier();
|
||||
const tx: OidcTransaction = {
|
||||
state: client.randomState(),
|
||||
nonce: client.randomNonce(),
|
||||
codeVerifier,
|
||||
returnTo: safeReturnTo(returnTo),
|
||||
issuedAt: now.getTime(),
|
||||
};
|
||||
const url = client.buildAuthorizationUrl(config, {
|
||||
redirect_uri: redirectUri,
|
||||
scope: OIDC_SCOPE,
|
||||
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
|
||||
code_challenge_method: "S256",
|
||||
state: tx.state,
|
||||
nonce: tx.nonce,
|
||||
});
|
||||
return { url, txCookie: signValue(tx, secret) };
|
||||
}
|
||||
|
||||
export type OidcLoginResult =
|
||||
| { ok: true; sessionToken: string; returnTo: string; userId: number; created: boolean }
|
||||
| { ok: false; error: "failed" | LoginRejectReason; employeeNo: string | null };
|
||||
|
||||
/**
|
||||
* 處理 callback:驗證暫存 cookie、state、nonce、PKCE 與 ID token(由 openid-client 負責),
|
||||
* 再以 ID token 的 claims 呼叫 `provisionOnLogin`。任何驗證失敗都回傳 `failed`,不建立帳號。
|
||||
*/
|
||||
export async function completeOidcLogin(
|
||||
config: client.Configuration,
|
||||
{
|
||||
db,
|
||||
callbackUrl,
|
||||
txCookie,
|
||||
secret,
|
||||
bootstrapSysadmins,
|
||||
now,
|
||||
}: {
|
||||
db: Db;
|
||||
callbackUrl: URL;
|
||||
txCookie: string | undefined;
|
||||
secret: string;
|
||||
bootstrapSysadmins: readonly string[];
|
||||
now: Date;
|
||||
},
|
||||
): Promise<OidcLoginResult> {
|
||||
const tx = verifyValue<OidcTransaction>(txCookie, secret);
|
||||
if (!tx || now.getTime() - tx.issuedAt > OIDC_TX_MAX_AGE_SECONDS * 1000) {
|
||||
return { ok: false, error: "failed", employeeNo: null };
|
||||
}
|
||||
|
||||
let claims: client.IDToken | undefined;
|
||||
try {
|
||||
const tokens = await client.authorizationCodeGrant(config, callbackUrl, {
|
||||
pkceCodeVerifier: tx.codeVerifier,
|
||||
expectedState: tx.state,
|
||||
expectedNonce: tx.nonce,
|
||||
idTokenExpected: true,
|
||||
});
|
||||
claims = tokens.claims();
|
||||
} catch (error) {
|
||||
console.warn("公司登入 callback 驗證失敗:", error instanceof Error ? error.message : error);
|
||||
return { ok: false, error: "failed", employeeNo: null };
|
||||
}
|
||||
|
||||
const result = provisionOnLogin(
|
||||
db,
|
||||
{
|
||||
employeeNumber: stringClaim(claims?.employee_number),
|
||||
name: stringClaim(claims?.name),
|
||||
email: stringClaim(claims?.email),
|
||||
},
|
||||
{ bootstrapSysadmins, now },
|
||||
);
|
||||
if (!result.ok) return { ok: false, error: result.reason, employeeNo: result.employeeNo };
|
||||
return {
|
||||
ok: true,
|
||||
sessionToken: result.sessionToken,
|
||||
returnTo: tx.returnTo,
|
||||
userId: result.userId,
|
||||
created: result.created,
|
||||
};
|
||||
}
|
||||
|
||||
function stringClaim(value: unknown): string | null {
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value === "number") return String(value);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { departments, sessions, userRoles, users } from "@/server/db/schema";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { provisionOnLogin, type ProvisionOptions } from "./provision";
|
||||
|
||||
const now = new Date("2026-10-06T02:00:00Z");
|
||||
const opts: ProvisionOptions = { bootstrapSysadmins: ["E0001"], now };
|
||||
|
||||
describe("provisionOnLogin", () => {
|
||||
let t: TestDatabase;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
const user = (employeeNo: string) =>
|
||||
t.db.select().from(users).where(eq(users.employeeNo, employeeNo)).get();
|
||||
const roles = (userId: number) =>
|
||||
t.db
|
||||
.select()
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, userId))
|
||||
.all()
|
||||
.map((r) => r.role)
|
||||
.sort();
|
||||
const sessionCount = () => t.db.select().from(sessions).all().length;
|
||||
|
||||
it("第一次登入:建立員工角色、待指派部門的帳號並建立 session", () => {
|
||||
const result = provisionOnLogin(
|
||||
t.db,
|
||||
{ employeeNumber: "E1234", name: "王小明", email: "[email protected]" },
|
||||
opts,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({ ok: true, created: true });
|
||||
const u = user("E1234")!;
|
||||
expect(u).toMatchObject({
|
||||
name: "王小明",
|
||||
email: "[email protected]",
|
||||
departmentId: null,
|
||||
firstLoginAt: now.toISOString(),
|
||||
lastLoginAt: now.toISOString(),
|
||||
});
|
||||
expect(roles(u.id)).toEqual(["employee"]);
|
||||
expect(sessionCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("名冊已匯入的人第一次登入:沿用部門,補上姓名與 email", () => {
|
||||
const dept = t.db
|
||||
.insert(departments)
|
||||
.values({ name: "設計部", type: "general" })
|
||||
.returning()
|
||||
.get();
|
||||
t.db.insert(users).values({ employeeNo: "E1234", departmentId: dept.id }).run();
|
||||
|
||||
const result = provisionOnLogin(
|
||||
t.db,
|
||||
{ employeeNumber: "E1234", name: "王小明", email: "[email protected]" },
|
||||
opts,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({ ok: true, created: false });
|
||||
expect(user("E1234")).toMatchObject({
|
||||
departmentId: dept.id,
|
||||
name: "王小明",
|
||||
email: "[email protected]",
|
||||
firstLoginAt: now.toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
it("再次登入只更新最近登入時間,保留首次登入時間", () => {
|
||||
provisionOnLogin(t.db, { employeeNumber: "E1234" }, opts);
|
||||
const later = new Date("2026-10-07T02:00:00Z");
|
||||
provisionOnLogin(t.db, { employeeNumber: "E1234" }, { ...opts, now: later });
|
||||
expect(user("E1234")).toMatchObject({
|
||||
firstLoginAt: now.toISOString(),
|
||||
lastLoginAt: later.toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
it("已停用帳號拒絕登入,不建立 session", () => {
|
||||
t.db.insert(users).values({ employeeNo: "E1234", active: false }).run();
|
||||
expect(provisionOnLogin(t.db, { employeeNumber: "E1234" }, opts)).toEqual({
|
||||
ok: false,
|
||||
reason: "inactive",
|
||||
employeeNo: "E1234",
|
||||
});
|
||||
expect(sessionCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each([undefined, null, "", " "])("缺少員工編號(%j)時拒絕,不建立帳號", (employeeNumber) => {
|
||||
expect(provisionOnLogin(t.db, { employeeNumber, name: "X" }, opts)).toMatchObject({
|
||||
ok: false,
|
||||
reason: "missing_employee_number",
|
||||
});
|
||||
expect(t.db.select().from(users).all()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("名單上的員工編號登入時取得系統管理員角色", () => {
|
||||
const result = provisionOnLogin(t.db, { employeeNumber: "E0001" }, opts);
|
||||
if (!result.ok) throw new Error("expected ok");
|
||||
expect(roles(result.userId)).toEqual(["employee", "sysadmin"]);
|
||||
});
|
||||
|
||||
it("email 已屬於其他工號時不更新 email,但照常登入", () => {
|
||||
t.db.insert(users).values({ employeeNo: "E9999", email: "[email protected]" }).run();
|
||||
const result = provisionOnLogin(
|
||||
t.db,
|
||||
{ employeeNumber: "E1234", email: "[email protected]" },
|
||||
opts,
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(user("E1234")!.email).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { and, eq, ne } from "drizzle-orm";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { userRoles, users } from "@/server/db/schema";
|
||||
import { withTransaction } from "@/server/db/transaction";
|
||||
import { createSession } from "./session";
|
||||
|
||||
/** 登入後取得的身分資料:公司登入來自 ID token claims,替代登入由開發者輸入。 */
|
||||
export interface LoginClaims {
|
||||
employeeNumber?: string | null;
|
||||
name?: string | null;
|
||||
email?: string | null;
|
||||
}
|
||||
|
||||
export type LoginRejectReason = "missing_employee_number" | "inactive";
|
||||
|
||||
export type ProvisionResult =
|
||||
| { ok: true; userId: number; created: boolean; sessionToken: string }
|
||||
| { ok: false; reason: LoginRejectReason; employeeNo: string | null };
|
||||
|
||||
export interface ProvisionOptions {
|
||||
/** 登入時自動授予系統管理員角色的員工編號(BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS)。 */
|
||||
bootstrapSysadmins: readonly string[];
|
||||
now: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登入成功後的帳號處理與 session 建立,公司登入與替代登入共用。單一交易內:
|
||||
* 以員工編號找使用者,不存在就建立(員工角色、待指派部門),已停用則拒絕,
|
||||
* 否則以登入資料更新姓名與 email;名單上的員工編號授予系統管理員;最後建立 session。
|
||||
*/
|
||||
export function provisionOnLogin(
|
||||
db: Db,
|
||||
claims: LoginClaims,
|
||||
{ bootstrapSysadmins, now }: ProvisionOptions,
|
||||
): ProvisionResult {
|
||||
const employeeNo = claims.employeeNumber?.trim();
|
||||
if (!employeeNo) {
|
||||
return { ok: false, reason: "missing_employee_number", employeeNo: null };
|
||||
}
|
||||
const name = claims.name?.trim() || null;
|
||||
const email = claims.email?.trim().toLowerCase() || null;
|
||||
const nowIso = now.toISOString();
|
||||
|
||||
return withTransaction(db, (tx): ProvisionResult => {
|
||||
const existing = tx.select().from(users).where(eq(users.employeeNo, employeeNo)).get();
|
||||
if (existing && !existing.active) {
|
||||
return { ok: false, reason: "inactive", employeeNo };
|
||||
}
|
||||
|
||||
// email 不是識別鍵:已被其他工號使用時不更新,也不阻擋登入。
|
||||
const emailTaken =
|
||||
email !== null &&
|
||||
tx
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(
|
||||
existing
|
||||
? and(eq(users.email, email), ne(users.id, existing.id))
|
||||
: eq(users.email, email),
|
||||
)
|
||||
.get() !== undefined;
|
||||
if (emailTaken) {
|
||||
console.warn(`登入 ${employeeNo}:email ${email} 已屬於其他使用者,未更新 email`);
|
||||
}
|
||||
|
||||
let userId: number;
|
||||
if (existing) {
|
||||
userId = existing.id;
|
||||
tx.update(users)
|
||||
.set({
|
||||
...(name !== null && { name }),
|
||||
...(email !== null && !emailTaken && { email }),
|
||||
firstLoginAt: existing.firstLoginAt ?? nowIso,
|
||||
lastLoginAt: nowIso,
|
||||
})
|
||||
.where(eq(users.id, userId))
|
||||
.run();
|
||||
} else {
|
||||
userId = tx
|
||||
.insert(users)
|
||||
.values({
|
||||
employeeNo,
|
||||
name,
|
||||
email: emailTaken ? null : email,
|
||||
departmentId: null,
|
||||
firstLoginAt: nowIso,
|
||||
lastLoginAt: nowIso,
|
||||
})
|
||||
.returning({ id: users.id })
|
||||
.get().id;
|
||||
}
|
||||
|
||||
// 所有在職使用者至少具備員工角色(名冊匯入的人也一樣,重複插入會被忽略)。
|
||||
tx.insert(userRoles).values({ userId, role: "employee" }).onConflictDoNothing().run();
|
||||
if (bootstrapSysadmins.includes(employeeNo)) {
|
||||
tx.insert(userRoles).values({ userId, role: "sysadmin" }).onConflictDoNothing().run();
|
||||
}
|
||||
|
||||
const sessionToken = createSession(tx, userId, now);
|
||||
return { ok: true, userId, created: !existing, sessionToken };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export const DEFAULT_AFTER_LOGIN = "/dashboard";
|
||||
|
||||
/** 登入後的導向位置只接受站內路徑,避免被當成開放式重導向(`//evil.com`、`/\evil.com`)。 */
|
||||
export function safeReturnTo(value: string | null | undefined): string {
|
||||
if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
|
||||
return DEFAULT_AFTER_LOGIN;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { departmentManagers, departments, users } from "@/server/db/schema";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { canReview, isInScope, managedDepartmentIds, scopeApplications } from "./scope";
|
||||
|
||||
// 部門 1 = 設計部、2 = 研發部
|
||||
const DESIGN = 1;
|
||||
const RND = 2;
|
||||
const app = (applicantId: number, departmentId: number) => ({ applicantId, departmentId });
|
||||
|
||||
describe("scopeApplications", () => {
|
||||
it("員工只能存取本人的申請", () => {
|
||||
const scope = scopeApplications({ id: 10, roles: ["employee"] }, []);
|
||||
expect(isInScope(scope, app(10, DESIGN))).toBe(true);
|
||||
expect(isInScope(scope, app(11, DESIGN))).toBe(false);
|
||||
});
|
||||
|
||||
it("主管可存取所轄部門與本人的申請,不能存取其他部門", () => {
|
||||
const scope = scopeApplications({ id: 20, roles: ["employee", "manager"] }, [DESIGN]);
|
||||
expect(isInScope(scope, app(11, DESIGN))).toBe(true);
|
||||
expect(isInScope(scope, app(20, DESIGN))).toBe(true);
|
||||
expect(isInScope(scope, app(30, RND))).toBe(false);
|
||||
});
|
||||
|
||||
it("管理者可存取全公司", () => {
|
||||
const scope = scopeApplications({ id: 40, roles: ["employee", "admin"] }, []);
|
||||
expect(scope).toEqual({ all: true });
|
||||
expect(isInScope(scope, app(30, RND))).toBe(true);
|
||||
});
|
||||
|
||||
it("系統管理員不因角色取得申請資料(只看本人)", () => {
|
||||
const scope = scopeApplications({ id: 50, roles: ["employee", "sysadmin"] }, []);
|
||||
expect(isInScope(scope, app(11, DESIGN))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canReview", () => {
|
||||
const manager = { id: 20, roles: ["employee", "manager"] as const };
|
||||
|
||||
it("一般員工不得審核任何案件,包含本人案件", () => {
|
||||
const employee = { id: 10, roles: ["employee"] as const };
|
||||
expect(canReview(employee, [], app(10, DESIGN))).toEqual({ allowed: false });
|
||||
expect(canReview(employee, [], app(11, DESIGN))).toEqual({ allowed: false });
|
||||
});
|
||||
|
||||
it("主管可審核所轄部門的案件", () => {
|
||||
expect(canReview(manager, [DESIGN], app(11, DESIGN))).toEqual({
|
||||
allowed: true,
|
||||
selfReview: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("主管不得審核其他部門的案件", () => {
|
||||
expect(canReview(manager, [DESIGN], app(30, RND))).toEqual({ allowed: false });
|
||||
});
|
||||
|
||||
it("主管審核本人的申請允許,並標示為自行審核", () => {
|
||||
expect(canReview(manager, [DESIGN], app(20, DESIGN))).toEqual({
|
||||
allowed: true,
|
||||
selfReview: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("管理者不具審核權", () => {
|
||||
expect(canReview({ id: 40, roles: ["employee", "admin"] }, [], app(11, DESIGN))).toEqual({
|
||||
allowed: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managedDepartmentIds", () => {
|
||||
let t: TestDatabase;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
t.db
|
||||
.insert(departments)
|
||||
.values([
|
||||
{ id: DESIGN, name: "設計部", type: "general" },
|
||||
{ id: RND, name: "研發部", type: "rnd" },
|
||||
])
|
||||
.run();
|
||||
t.db.insert(users).values({ id: 20, employeeNo: "E20" }).run();
|
||||
t.db.insert(departmentManagers).values({ departmentId: DESIGN, userId: 20 }).run();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
it("回傳被指派的部門", () => {
|
||||
expect(managedDepartmentIds(t.db, { id: 20, roles: ["employee", "manager"] })).toEqual([
|
||||
DESIGN,
|
||||
]);
|
||||
});
|
||||
|
||||
it("沒有主管角色時即使有指派紀錄也不算", () => {
|
||||
expect(managedDepartmentIds(t.db, { id: 20, roles: ["employee"] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Role } from "@/lib/roles";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { departmentManagers } from "@/server/db/schema";
|
||||
|
||||
/** 使用者實際主管的部門(department_managers),且必須具備主管角色才算數。 */
|
||||
export function managedDepartmentIds(
|
||||
db: Db,
|
||||
user: { id: number; roles: readonly Role[] },
|
||||
): number[] {
|
||||
if (!user.roles.includes("manager")) return [];
|
||||
return db
|
||||
.select({ departmentId: departmentManagers.departmentId })
|
||||
.from(departmentManagers)
|
||||
.where(eq(departmentManagers.userId, user.id))
|
||||
.all()
|
||||
.map((r) => r.departmentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 申請資料的存取範圍。後續 change 查詢申請 MUST 經過 `scopeApplications`,
|
||||
* 再把範圍轉成查詢條件(`all` 不加條件;否則為「申請人在 userIds」OR「申請所屬部門在 departmentIds」)。
|
||||
*/
|
||||
export type ApplicationScope =
|
||||
{ all: true } | { all: false; userIds: number[]; departmentIds: number[] };
|
||||
|
||||
/** 員工 → 本人;主管 → 加上所轄部門;管理者 → 全部。兼任時取聯集。 */
|
||||
export function scopeApplications(
|
||||
user: { id: number; roles: readonly Role[] },
|
||||
managedDepartments: readonly number[],
|
||||
): ApplicationScope {
|
||||
if (user.roles.includes("admin")) return { all: true };
|
||||
return {
|
||||
all: false,
|
||||
userIds: user.roles.includes("employee") ? [user.id] : [],
|
||||
departmentIds: [...managedDepartments],
|
||||
};
|
||||
}
|
||||
|
||||
/** 判斷某筆申請是否在範圍內(詳情頁、單筆操作用)。 */
|
||||
export function isInScope(
|
||||
scope: ApplicationScope,
|
||||
application: { applicantId: number; departmentId: number },
|
||||
): boolean {
|
||||
return (
|
||||
scope.all ||
|
||||
scope.userIds.includes(application.applicantId) ||
|
||||
scope.departmentIds.includes(application.departmentId)
|
||||
);
|
||||
}
|
||||
|
||||
export type ReviewDecision = { allowed: false } | { allowed: true; selfReview: boolean };
|
||||
|
||||
/**
|
||||
* 只有申請所屬部門的主管可以審核(規格 §4),管理者、系統管理員也不行。
|
||||
* 主管可以審核自己的申請,但要標示「主管自行審核」。
|
||||
*/
|
||||
export function canReview(
|
||||
reviewer: { id: number; roles: readonly Role[] },
|
||||
managedDepartments: readonly number[],
|
||||
application: { applicantId: number; departmentId: number },
|
||||
): ReviewDecision {
|
||||
if (!reviewer.roles.includes("manager")) return { allowed: false };
|
||||
if (!managedDepartments.includes(application.departmentId)) return { allowed: false };
|
||||
return { allowed: true, selfReview: application.applicantId === reviewer.id };
|
||||
}
|
||||
|
||||
export const SELF_REVIEW_LABEL = "主管自行審核";
|
||||
@@ -0,0 +1,79 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { sessions, users } from "@/server/db/schema";
|
||||
import { withTransaction } from "@/server/db/transaction";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import {
|
||||
SESSION_IDLE_TIMEOUT_MS,
|
||||
createSession,
|
||||
deleteSession,
|
||||
deleteUserSessions,
|
||||
validateSession,
|
||||
} from "./session";
|
||||
|
||||
const t0 = new Date("2026-10-06T02:00:00Z");
|
||||
const after = (ms: number) => new Date(t0.getTime() + ms);
|
||||
|
||||
describe("session", () => {
|
||||
let t: TestDatabase;
|
||||
let userId: number;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
userId = t.db.insert(users).values({ employeeNo: "E1" }).returning().get().id;
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
const create = (now = t0) => withTransaction(t.db, (tx) => createSession(tx, userId, now));
|
||||
|
||||
it("建立後可驗證,資料庫只存 token 的雜湊", () => {
|
||||
const token = create();
|
||||
expect(validateSession(t.db, token, t0)).toMatchObject({ id: userId, employeeNo: "E1" });
|
||||
const stored = t.db.select().from(sessions).get()!;
|
||||
expect(stored.tokenHash).not.toBe(token);
|
||||
});
|
||||
|
||||
it("不存在的 token 無效", () => {
|
||||
expect(validateSession(t.db, "nope", t0)).toBeNull();
|
||||
});
|
||||
|
||||
it("閒置超過 8 小時失效並被刪除", () => {
|
||||
const token = create();
|
||||
expect(validateSession(t.db, token, after(SESSION_IDLE_TIMEOUT_MS + 1))).toBeNull();
|
||||
expect(t.db.select().from(sessions).all()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("持續使用會延長:每次活動重新計算閒置時間", () => {
|
||||
const token = create();
|
||||
expect(validateSession(t.db, token, after(7 * 3600_000))).not.toBeNull();
|
||||
expect(validateSession(t.db, token, after(14 * 3600_000))).not.toBeNull();
|
||||
});
|
||||
|
||||
it("一分鐘內的請求不更新 last_seen_at", () => {
|
||||
const token = create();
|
||||
validateSession(t.db, token, after(30_000));
|
||||
expect(t.db.select().from(sessions).get()!.lastSeenAt).toBe(t0.toISOString());
|
||||
});
|
||||
|
||||
it("登出後失效", () => {
|
||||
const token = create();
|
||||
deleteSession(t.db, token);
|
||||
expect(validateSession(t.db, token, t0)).toBeNull();
|
||||
});
|
||||
|
||||
it("停用使用者時刪除其全部 session,下一個請求即失效", () => {
|
||||
const a = create();
|
||||
const b = create();
|
||||
withTransaction(t.db, (tx) => {
|
||||
tx.update(users).set({ active: false }).where(eq(users.id, userId)).run();
|
||||
deleteUserSessions(tx, userId);
|
||||
});
|
||||
expect(validateSession(t.db, a, t0)).toBeNull();
|
||||
expect(validateSession(t.db, b, t0)).toBeNull();
|
||||
});
|
||||
|
||||
it("即使 session 還在,使用者已停用時也視為無效", () => {
|
||||
const token = create();
|
||||
t.db.update(users).set({ active: false }).where(eq(users.id, userId)).run();
|
||||
expect(validateSession(t.db, token, t0)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { sessions, users } from "@/server/db/schema";
|
||||
import type { Tx } from "@/server/db/transaction";
|
||||
|
||||
/** 閒置超過這段時間的 session 失效。 */
|
||||
export const SESSION_IDLE_TIMEOUT_MS = 8 * 60 * 60 * 1000;
|
||||
/** last_seen_at 最多每分鐘更新一次,避免每個請求都寫入。 */
|
||||
const TOUCH_INTERVAL_MS = 60 * 1000;
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
/** 建立 session,回傳要放進 cookie 的 token。資料庫只存 token 的雜湊。 */
|
||||
export function createSession(tx: Tx, userId: number, now: Date): string {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
tx.insert(sessions)
|
||||
.values({ tokenHash: hashToken(token), userId, lastSeenAt: now.toISOString() })
|
||||
.run();
|
||||
return token;
|
||||
}
|
||||
|
||||
export interface SessionUser {
|
||||
id: number;
|
||||
employeeNo: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
departmentId: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 驗證 session token:不存在、閒置逾時或使用者已停用時回傳 null(逾時的 session 會被刪除)。
|
||||
* 有效時視需要更新 last_seen_at。
|
||||
*/
|
||||
export function validateSession(db: Db, token: string, now: Date): SessionUser | null {
|
||||
const tokenHash = hashToken(token);
|
||||
const row = db
|
||||
.select({
|
||||
lastSeenAt: sessions.lastSeenAt,
|
||||
id: users.id,
|
||||
employeeNo: users.employeeNo,
|
||||
name: users.name,
|
||||
email: users.email,
|
||||
departmentId: users.departmentId,
|
||||
active: users.active,
|
||||
})
|
||||
.from(sessions)
|
||||
.innerJoin(users, eq(users.id, sessions.userId))
|
||||
.where(eq(sessions.tokenHash, tokenHash))
|
||||
.get();
|
||||
if (!row) return null;
|
||||
|
||||
const idle = now.getTime() - Date.parse(row.lastSeenAt);
|
||||
if (idle > SESSION_IDLE_TIMEOUT_MS || !row.active) {
|
||||
db.delete(sessions).where(eq(sessions.tokenHash, tokenHash)).run();
|
||||
return null;
|
||||
}
|
||||
if (idle > TOUCH_INTERVAL_MS) {
|
||||
db.update(sessions)
|
||||
.set({ lastSeenAt: now.toISOString() })
|
||||
.where(eq(sessions.tokenHash, tokenHash))
|
||||
.run();
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
employeeNo: row.employeeNo,
|
||||
name: row.name,
|
||||
email: row.email,
|
||||
departmentId: row.departmentId,
|
||||
};
|
||||
}
|
||||
|
||||
/** 登出:刪除這個 session。 */
|
||||
export function deleteSession(db: Db | Tx, token: string): void {
|
||||
db.delete(sessions)
|
||||
.where(eq(sessions.tokenHash, hashToken(token)))
|
||||
.run();
|
||||
}
|
||||
|
||||
/** 刪除某使用者的全部 session(停用帳號時呼叫),使其下一個請求即失效。 */
|
||||
export function deleteUserSessions(tx: Tx, userId: number): void {
|
||||
tx.delete(sessions).where(eq(sessions.userId, userId)).run();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
// 以 SESSION_SECRET 做 HMAC 簽章的 cookie 值,防止使用者竄改內容(例如登入後的導向位置)。
|
||||
|
||||
export function signValue(payload: unknown, secret: string): string {
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
||||
return `${body}.${createHmac("sha256", secret).update(body).digest("base64url")}`;
|
||||
}
|
||||
|
||||
export function verifyValue<T>(value: string | undefined, secret: string): T | null {
|
||||
if (!value) return null;
|
||||
const [body, signature] = value.split(".");
|
||||
if (!body || !signature) return null;
|
||||
const expected = createHmac("sha256", secret).update(body).digest();
|
||||
const actual = Buffer.from(signature, "base64url");
|
||||
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return null;
|
||||
try {
|
||||
return JSON.parse(Buffer.from(body, "base64url").toString()) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
CREATE TABLE `department_managers` (
|
||||
`department_id` integer NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
PRIMARY KEY(`department_id`, `user_id`),
|
||||
FOREIGN KEY (`department_id`) REFERENCES `departments`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `department_managers_user_idx` ON `department_managers` (`user_id`);--> statement-breakpoint
|
||||
CREATE TABLE `departments` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`code` text,
|
||||
`name` text NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`active` integer DEFAULT true NOT NULL,
|
||||
`created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `departments_code_unique` ON `departments` (`code`);--> statement-breakpoint
|
||||
CREATE TABLE `user_department_history` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`department_id` integer,
|
||||
`effective_from` text NOT NULL,
|
||||
`created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
|
||||
FOREIGN KEY (`department_id`) REFERENCES `departments`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `user_department_history_user_idx` ON `user_department_history` (`user_id`,`effective_from`);--> statement-breakpoint
|
||||
CREATE TABLE `users` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`employee_no` text NOT NULL,
|
||||
`email` text,
|
||||
`name` text,
|
||||
`department_id` integer,
|
||||
`active` integer DEFAULT true NOT NULL,
|
||||
`first_login_at` text,
|
||||
`last_login_at` text,
|
||||
`created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) NOT NULL,
|
||||
FOREIGN KEY (`department_id`) REFERENCES `departments`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `users_employee_no_unique` ON `users` (`employee_no`);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);--> statement-breakpoint
|
||||
CREATE TABLE `sessions` (
|
||||
`token_hash` text PRIMARY KEY NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) NOT NULL,
|
||||
`last_seen_at` text NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `sessions_user_idx` ON `sessions` (`user_id`);--> statement-breakpoint
|
||||
CREATE TABLE `user_roles` (
|
||||
`user_id` integer NOT NULL,
|
||||
`role` text NOT NULL,
|
||||
PRIMARY KEY(`user_id`, `role`),
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
@@ -0,0 +1,471 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "4257b747-0e31-451d-bf6d-d0cdef9253a9",
|
||||
"prevId": "572e1ecd-dece-498b-9902-d668dee6ef0b",
|
||||
"tables": {
|
||||
"_meta": {
|
||||
"name": "_meta",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"department_managers": {
|
||||
"name": "department_managers",
|
||||
"columns": {
|
||||
"department_id": {
|
||||
"name": "department_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"department_managers_user_idx": {
|
||||
"name": "department_managers_user_idx",
|
||||
"columns": [
|
||||
"user_id"
|
||||
],
|
||||
"isUnique": false
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"department_managers_department_id_departments_id_fk": {
|
||||
"name": "department_managers_department_id_departments_id_fk",
|
||||
"tableFrom": "department_managers",
|
||||
"tableTo": "departments",
|
||||
"columnsFrom": [
|
||||
"department_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"department_managers_user_id_users_id_fk": {
|
||||
"name": "department_managers_user_id_users_id_fk",
|
||||
"tableFrom": "department_managers",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {
|
||||
"department_managers_department_id_user_id_pk": {
|
||||
"columns": [
|
||||
"department_id",
|
||||
"user_id"
|
||||
],
|
||||
"name": "department_managers_department_id_user_id_pk"
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"departments": {
|
||||
"name": "departments",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"code": {
|
||||
"name": "code",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"active": {
|
||||
"name": "active",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"departments_code_unique": {
|
||||
"name": "departments_code_unique",
|
||||
"columns": [
|
||||
"code"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"user_department_history": {
|
||||
"name": "user_department_history",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"department_id": {
|
||||
"name": "department_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"effective_from": {
|
||||
"name": "effective_from",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"user_department_history_user_idx": {
|
||||
"name": "user_department_history_user_idx",
|
||||
"columns": [
|
||||
"user_id",
|
||||
"effective_from"
|
||||
],
|
||||
"isUnique": false
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"user_department_history_user_id_users_id_fk": {
|
||||
"name": "user_department_history_user_id_users_id_fk",
|
||||
"tableFrom": "user_department_history",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"user_department_history_department_id_departments_id_fk": {
|
||||
"name": "user_department_history_department_id_departments_id_fk",
|
||||
"tableFrom": "user_department_history",
|
||||
"tableTo": "departments",
|
||||
"columnsFrom": [
|
||||
"department_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"users": {
|
||||
"name": "users",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": true
|
||||
},
|
||||
"employee_no": {
|
||||
"name": "employee_no",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"department_id": {
|
||||
"name": "department_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"active": {
|
||||
"name": "active",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": true
|
||||
},
|
||||
"first_login_at": {
|
||||
"name": "first_login_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"last_login_at": {
|
||||
"name": "last_login_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"users_employee_no_unique": {
|
||||
"name": "users_employee_no_unique",
|
||||
"columns": [
|
||||
"employee_no"
|
||||
],
|
||||
"isUnique": true
|
||||
},
|
||||
"users_email_unique": {
|
||||
"name": "users_email_unique",
|
||||
"columns": [
|
||||
"email"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"users_department_id_departments_id_fk": {
|
||||
"name": "users_department_id_departments_id_fk",
|
||||
"tableFrom": "users",
|
||||
"tableTo": "departments",
|
||||
"columnsFrom": [
|
||||
"department_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"sessions": {
|
||||
"name": "sessions",
|
||||
"columns": {
|
||||
"token_hash": {
|
||||
"name": "token_hash",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
|
||||
},
|
||||
"last_seen_at": {
|
||||
"name": "last_seen_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"sessions_user_idx": {
|
||||
"name": "sessions_user_idx",
|
||||
"columns": [
|
||||
"user_id"
|
||||
],
|
||||
"isUnique": false
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"sessions_user_id_users_id_fk": {
|
||||
"name": "sessions_user_id_users_id_fk",
|
||||
"tableFrom": "sessions",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"user_roles": {
|
||||
"name": "user_roles",
|
||||
"columns": {
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"role": {
|
||||
"name": "role",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"user_roles_user_id_users_id_fk": {
|
||||
"name": "user_roles_user_id_users_id_fk",
|
||||
"tableFrom": "user_roles",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {
|
||||
"user_roles_user_id_role_pk": {
|
||||
"columns": [
|
||||
"user_id",
|
||||
"role"
|
||||
],
|
||||
"name": "user_roles_user_id_role_pk"
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,13 @@
|
||||
"when": 1791199731109,
|
||||
"tag": "0000_long_cannonball",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "6",
|
||||
"when": 1791285988344,
|
||||
"tag": "0001_conscious_sentinel",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
import { ROLES } from "@/lib/roles";
|
||||
import { users } from "./org-directory";
|
||||
|
||||
export { ROLES, type Role } from "@/lib/roles";
|
||||
|
||||
/** 使用者角色;一人可兼多個角色。 */
|
||||
export const userRoles = sqliteTable(
|
||||
"user_roles",
|
||||
{
|
||||
userId: integer("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
role: text("role", { enum: ROLES }).notNull(),
|
||||
},
|
||||
(t) => [primaryKey({ columns: [t.userId, t.role] })],
|
||||
);
|
||||
|
||||
/** 伺服器端 session。只存 token 的 SHA-256 雜湊,資料庫外洩也無法直接冒用。 */
|
||||
export const sessions = sqliteTable(
|
||||
"sessions",
|
||||
{
|
||||
tokenHash: text("token_hash").primaryKey(),
|
||||
userId: integer("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`),
|
||||
lastSeenAt: text("last_seen_at").notNull(),
|
||||
},
|
||||
(t) => [index("sessions_user_idx").on(t.userId)],
|
||||
);
|
||||
@@ -1,2 +1,4 @@
|
||||
// 所有 Drizzle schema 由此匯出;drizzle-kit 與資料庫連線都從這裡讀取。
|
||||
export * from "./meta";
|
||||
export * from "./org-directory";
|
||||
export * from "./identity-access";
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { departments, users } from "./org-directory";
|
||||
|
||||
describe("org-directory schema", () => {
|
||||
let t: TestDatabase;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
it("員工編號唯一", () => {
|
||||
t.db.insert(users).values({ employeeNo: "E1" }).run();
|
||||
expect(() => t.db.insert(users).values({ employeeNo: "E1" }).run()).toThrow(/UNIQUE/);
|
||||
});
|
||||
|
||||
it("email 有值時唯一,可有多筆未填", () => {
|
||||
t.db
|
||||
.insert(users)
|
||||
.values([{ employeeNo: "E1" }, { employeeNo: "E2" }])
|
||||
.run();
|
||||
t.db.insert(users).values({ employeeNo: "E3", email: "[email protected]" }).run();
|
||||
expect(() => t.db.insert(users).values({ employeeNo: "E4", email: "[email protected]" }).run()).toThrow(
|
||||
/UNIQUE/,
|
||||
);
|
||||
});
|
||||
|
||||
it("部門代碼有值時唯一,可有多筆未填", () => {
|
||||
t.db
|
||||
.insert(departments)
|
||||
.values([
|
||||
{ name: "設計部", type: "general" },
|
||||
{ name: "研發部", type: "rnd" },
|
||||
{ name: "廣告部", type: "general", code: "D01" },
|
||||
])
|
||||
.run();
|
||||
expect(() =>
|
||||
t.db.insert(departments).values({ name: "前製部", type: "general", code: "D01" }).run(),
|
||||
).toThrow(/UNIQUE/);
|
||||
});
|
||||
|
||||
it("所屬部門必須存在(外鍵)", () => {
|
||||
expect(() => t.db.insert(users).values({ employeeNo: "E1", departmentId: 999 }).run()).toThrow(
|
||||
/FOREIGN KEY/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
import { DEPARTMENT_TYPES } from "@/lib/department-types";
|
||||
|
||||
export { DEPARTMENT_TYPES, type DepartmentType } from "@/lib/department-types";
|
||||
|
||||
const createdAt = () =>
|
||||
text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))`);
|
||||
|
||||
/** 部門。不可刪除,只能停用,以保留歷史月結關聯。 */
|
||||
export const departments = sqliteTable("departments", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
// 對應 HR Sync 的部門代碼;MVP 選填。SQLite 的 UNIQUE 允許多筆 NULL。
|
||||
code: text("code").unique(),
|
||||
name: text("name").notNull(),
|
||||
type: text("type", { enum: DEPARTMENT_TYPES }).notNull(),
|
||||
active: integer("active", { mode: "boolean" }).notNull().default(true),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/**
|
||||
* 人員。以員工編號識別(公司登入的 `employee_number` claim)。
|
||||
* 來源為首次登入自動建立或名冊匯入;名冊匯入而尚未登入者沒有 email。
|
||||
* `departmentId` 為 NULL 即「待指派部門」。不可刪除,離職以停用表示。
|
||||
*/
|
||||
export const users = sqliteTable("users", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
employeeNo: text("employee_no").notNull().unique(),
|
||||
email: text("email").unique(),
|
||||
name: text("name"),
|
||||
departmentId: integer("department_id").references(() => departments.id),
|
||||
active: integer("active", { mode: "boolean" }).notNull().default(true),
|
||||
firstLoginAt: text("first_login_at"),
|
||||
lastLoginAt: text("last_login_at"),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/** 部門主管指派。主管的資料範圍以此表為準。 */
|
||||
export const departmentManagers = sqliteTable(
|
||||
"department_managers",
|
||||
{
|
||||
departmentId: integer("department_id")
|
||||
.notNull()
|
||||
.references(() => departments.id),
|
||||
userId: integer("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
},
|
||||
(t) => [
|
||||
primaryKey({ columns: [t.departmentId, t.userId] }),
|
||||
index("department_managers_user_idx").on(t.userId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* 人員所屬部門的生效紀錄,供「某日當時的部門成員」查詢(每月人數快照)。
|
||||
* `departmentId` 為 NULL 表示自該日起不屬於任何部門(停用或取消指派)。
|
||||
* `effectiveFrom` 為 Asia/Taipei 日期 `YYYY-MM-DD`,自該日 00:00 起生效。
|
||||
*/
|
||||
export const userDepartmentHistory = sqliteTable(
|
||||
"user_department_history",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: integer("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
departmentId: integer("department_id").references(() => departments.id),
|
||||
effectiveFrom: text("effective_from").notNull(),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("user_department_history_user_idx").on(t.userId, t.effectiveFrom)],
|
||||
);
|
||||
@@ -0,0 +1,53 @@
|
||||
import { count } from "drizzle-orm";
|
||||
import type { SQLiteTable } from "drizzle-orm/sqlite-core";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { departmentManagers, departments, userDepartmentHistory, userRoles, users } from "./schema";
|
||||
import { DEMO_USERS, seed } from "./seed";
|
||||
|
||||
describe("seed", () => {
|
||||
let t: TestDatabase;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
const rows = (table: SQLiteTable) => t.db.select({ n: count() }).from(table).get()!.n;
|
||||
const counts = () => ({
|
||||
departments: rows(departments),
|
||||
users: rows(users),
|
||||
roles: rows(userRoles),
|
||||
managers: rows(departmentManagers),
|
||||
history: rows(userDepartmentHistory),
|
||||
});
|
||||
|
||||
it("未開啟 demo 時不建立示範資料", () => {
|
||||
seed(t.db);
|
||||
expect(counts()).toEqual({ departments: 0, users: 0, roles: 0, managers: 0, history: 0 });
|
||||
});
|
||||
|
||||
it("demo 建立四種角色與待指派部門的示範使用者,重複執行不重複建立", () => {
|
||||
seed(t.db, new Date("2026-10-06T00:00:00Z"), { demo: true });
|
||||
const first = counts();
|
||||
seed(t.db, new Date("2026-10-07T00:00:00Z"), { demo: true });
|
||||
|
||||
expect(counts()).toEqual(first);
|
||||
expect(first.users).toBe(DEMO_USERS.length);
|
||||
expect(first.departments).toBe(2);
|
||||
const roles = new Set(
|
||||
t.db
|
||||
.select()
|
||||
.from(userRoles)
|
||||
.all()
|
||||
.map((r) => r.role),
|
||||
);
|
||||
expect(roles).toEqual(new Set(["employee", "manager", "admin", "sysadmin"]));
|
||||
expect(
|
||||
t.db
|
||||
.select()
|
||||
.from(users)
|
||||
.all()
|
||||
.some((u) => u.departmentId === null),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
+100
-4
@@ -1,12 +1,29 @@
|
||||
import { meta } from "./schema";
|
||||
import { withTransaction } from "./transaction";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { localDate } from "@/domain/calendar";
|
||||
import {
|
||||
departmentManagers,
|
||||
departments,
|
||||
meta,
|
||||
userDepartmentHistory,
|
||||
userRoles,
|
||||
users,
|
||||
type DepartmentType,
|
||||
type Role,
|
||||
} from "./schema";
|
||||
import { withTransaction, type Tx } from "./transaction";
|
||||
import type { Db } from "./client";
|
||||
|
||||
export interface SeedOptions {
|
||||
/** 建立開發與 e2e 用的示範部門與使用者。只在 AUTH_MODE=dev 時開啟。 */
|
||||
demo?: boolean;
|
||||
timeZone?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 種子資料。必須可重複執行:每筆都用 upsert 或 `onConflictDoNothing`,不得重複插入。
|
||||
* 各功能 change 在這裡加入自己的初始資料(例如制度參數預設值、範例帳號)。
|
||||
* 各功能 change 在這裡加入自己的初始資料(例如制度參數預設值)。
|
||||
*/
|
||||
export function seed(db: Db, now: Date = new Date()): void {
|
||||
export function seed(db: Db, now: Date = new Date(), options: SeedOptions = {}): void {
|
||||
withTransaction(db, (tx) => {
|
||||
tx.insert(meta)
|
||||
.values({ key: "seeded_at", value: now.toISOString(), updatedAt: now.toISOString() })
|
||||
@@ -15,5 +32,84 @@ export function seed(db: Db, now: Date = new Date()): void {
|
||||
set: { value: now.toISOString(), updatedAt: now.toISOString() },
|
||||
})
|
||||
.run();
|
||||
if (options.demo) {
|
||||
seedDemoData(tx, localDate(now, options.timeZone ?? "Asia/Taipei"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const DEMO_DEPARTMENTS: { code: string; name: string; type: DepartmentType }[] = [
|
||||
{ code: "DEMO-DSN", name: "設計部(示範)", type: "general" },
|
||||
{ code: "DEMO-RND", name: "研發部(示範)", type: "rnd" },
|
||||
];
|
||||
|
||||
/** 示範使用者:涵蓋四種角色、兼任主管,以及待指派部門。員工編號以 D 開頭,不會與真實工號衝突。 */
|
||||
export const DEMO_USERS: {
|
||||
employeeNo: string;
|
||||
name: string;
|
||||
department: string | null;
|
||||
roles: Role[];
|
||||
manages?: string;
|
||||
}[] = [
|
||||
{ employeeNo: "D0001", name: "王小明", department: "DEMO-DSN", roles: ["employee"] },
|
||||
{
|
||||
employeeNo: "D0002",
|
||||
name: "李經理",
|
||||
department: "DEMO-DSN",
|
||||
roles: ["employee", "manager"],
|
||||
manages: "DEMO-DSN",
|
||||
},
|
||||
{ employeeNo: "D0003", name: "陳研發", department: "DEMO-RND", roles: ["employee"] },
|
||||
{ employeeNo: "D0004", name: "林人資", department: "DEMO-DSN", roles: ["employee", "admin"] },
|
||||
{ employeeNo: "D0005", name: "張系管", department: "DEMO-RND", roles: ["employee", "sysadmin"] },
|
||||
{ employeeNo: "D0006", name: "趙新人", department: null, roles: ["employee"] },
|
||||
];
|
||||
|
||||
function seedDemoData(tx: Tx, today: string): void {
|
||||
for (const dept of DEMO_DEPARTMENTS) {
|
||||
tx.insert(departments).values(dept).onConflictDoNothing({ target: departments.code }).run();
|
||||
}
|
||||
const deptIds = new Map(
|
||||
tx
|
||||
.select({ id: departments.id, code: departments.code })
|
||||
.from(departments)
|
||||
.all()
|
||||
.map((d) => [d.code, d.id]),
|
||||
);
|
||||
|
||||
for (const demo of DEMO_USERS) {
|
||||
const departmentId = demo.department ? deptIds.get(demo.department)! : null;
|
||||
const existing = tx
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(eq(users.employeeNo, demo.employeeNo))
|
||||
.get();
|
||||
// 已存在就不動:開發者可能已在畫面上改過部門或角色。
|
||||
if (existing) continue;
|
||||
|
||||
const { id } = tx
|
||||
.insert(users)
|
||||
.values({
|
||||
employeeNo: demo.employeeNo,
|
||||
name: demo.name,
|
||||
email: `${demo.employeeNo.toLowerCase()}@demo.invalid`,
|
||||
departmentId,
|
||||
})
|
||||
.returning({ id: users.id })
|
||||
.get();
|
||||
if (departmentId !== null) {
|
||||
tx.insert(userDepartmentHistory)
|
||||
.values({ userId: id, departmentId, effectiveFrom: today })
|
||||
.run();
|
||||
}
|
||||
for (const role of demo.roles) {
|
||||
tx.insert(userRoles).values({ userId: id, role }).onConflictDoNothing().run();
|
||||
}
|
||||
if (demo.manages) {
|
||||
tx.insert(departmentManagers)
|
||||
.values({ departmentId: deptIds.get(demo.manages)!, userId: id })
|
||||
.onConflictDoNothing()
|
||||
.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+54
-8
@@ -2,34 +2,80 @@ import { describe, expect, it } from "vitest";
|
||||
import { EnvError, parseEnv } from "./env";
|
||||
|
||||
const secret = "x".repeat(32);
|
||||
const dev = { SESSION_SECRET: secret, AUTH_MODE: "dev" };
|
||||
const oidc = {
|
||||
SESSION_SECRET: secret,
|
||||
OIDC_ISSUER: "https://auth.moonshine-studio.net/application/o/vibe-aisubsidy/",
|
||||
OIDC_CLIENT_ID: "client",
|
||||
OIDC_CLIENT_SECRET: "secret",
|
||||
APP_URL: "https://aisubsidy-vibe.moonshine-studio.net",
|
||||
};
|
||||
|
||||
describe("parseEnv", () => {
|
||||
it("只給 SESSION_SECRET 時其餘套用預設值", () => {
|
||||
expect(parseEnv({ SESSION_SECRET: secret })).toEqual({
|
||||
it("dev 模式只給 SESSION_SECRET 時其餘套用預設值", () => {
|
||||
expect(parseEnv(dev)).toEqual({
|
||||
DATABASE_PATH: "./data/app.db",
|
||||
ATTACHMENTS_DIR: "./data/attachments",
|
||||
SESSION_SECRET: secret,
|
||||
TZ_APP: "Asia/Taipei",
|
||||
BACKUP_DIR: "./backups",
|
||||
BACKUP_KEEP: 14,
|
||||
AUTH_MODE: "dev",
|
||||
BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("缺少 SESSION_SECRET 時以明確訊息失敗", () => {
|
||||
expect(() => parseEnv({})).toThrow(EnvError);
|
||||
expect(() => parseEnv({})).toThrow(/SESSION_SECRET 未設定/);
|
||||
expect(() => parseEnv({ AUTH_MODE: "dev" })).toThrow(EnvError);
|
||||
expect(() => parseEnv({ AUTH_MODE: "dev" })).toThrow(/SESSION_SECRET 未設定/);
|
||||
});
|
||||
|
||||
it("SESSION_SECRET 為空字串視同未設定", () => {
|
||||
expect(() => parseEnv({ SESSION_SECRET: "" })).toThrow(/SESSION_SECRET 未設定/);
|
||||
expect(() => parseEnv({ ...dev, SESSION_SECRET: "" })).toThrow(/SESSION_SECRET 未設定/);
|
||||
});
|
||||
|
||||
it("SESSION_SECRET 太短時失敗", () => {
|
||||
expect(() => parseEnv({ SESSION_SECRET: "short" })).toThrow(/至少需要 32 個字元/);
|
||||
expect(() => parseEnv({ ...dev, SESSION_SECRET: "short" })).toThrow(/至少需要 32 個字元/);
|
||||
});
|
||||
|
||||
it("BACKUP_KEEP 必須是正整數", () => {
|
||||
expect(parseEnv({ SESSION_SECRET: secret, BACKUP_KEEP: "7" }).BACKUP_KEEP).toBe(7);
|
||||
expect(() => parseEnv({ SESSION_SECRET: secret, BACKUP_KEEP: "0" })).toThrow(EnvError);
|
||||
expect(parseEnv({ ...dev, BACKUP_KEEP: "7" }).BACKUP_KEEP).toBe(7);
|
||||
expect(() => parseEnv({ ...dev, BACKUP_KEEP: "0" })).toThrow(EnvError);
|
||||
});
|
||||
|
||||
it("BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS 以逗號分隔並去除空白", () => {
|
||||
expect(
|
||||
parseEnv({ ...dev, BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS: " E1, E2 ,," })
|
||||
.BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS,
|
||||
).toEqual(["E1", "E2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AUTH_MODE 交叉檢查", () => {
|
||||
it("oidc 且設定齊全時通過(AUTH_MODE 預設為 oidc)", () => {
|
||||
expect(parseEnv(oidc).AUTH_MODE).toBe("oidc");
|
||||
});
|
||||
|
||||
it.each(["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET", "APP_URL"])(
|
||||
"oidc 缺少 %s 時拒絕並指出缺哪一項",
|
||||
(key) => {
|
||||
expect(() => parseEnv({ ...oidc, [key]: undefined })).toThrow(
|
||||
new RegExp(`AUTH_MODE=oidc 需要 ${key}`),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("oidc 的 APP_URL 必須是 https", () => {
|
||||
expect(() => parseEnv({ ...oidc, APP_URL: "http://localhost:3000" })).toThrow(
|
||||
/APP_URL 必須是 https/,
|
||||
);
|
||||
});
|
||||
|
||||
it("dev 模式遇到平台注入的 OIDC_ISSUER 時拒絕啟動", () => {
|
||||
expect(() => parseEnv({ ...oidc, AUTH_MODE: "dev" })).toThrow(/不得以 AUTH_MODE=dev 啟動/);
|
||||
});
|
||||
|
||||
it("dev 且無 OIDC 設定時通過", () => {
|
||||
expect(parseEnv(dev).AUTH_MODE).toBe("dev");
|
||||
});
|
||||
});
|
||||
|
||||
+59
-10
@@ -1,16 +1,65 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// 伺服器端環境變數。Next.js 會自動載入 .env;CLI 腳本由 scripts/load-env.ts 以相同規則載入。
|
||||
const envSchema = z.object({
|
||||
DATABASE_PATH: z.string().min(1).default("./data/app.db"),
|
||||
ATTACHMENTS_DIR: z.string().min(1).default("./data/attachments"),
|
||||
SESSION_SECRET: z
|
||||
.string({ error: "SESSION_SECRET 未設定(請複製 .env.example 為 .env 並填入)" })
|
||||
.min(32, "SESSION_SECRET 至少需要 32 個字元"),
|
||||
TZ_APP: z.string().min(1).default("Asia/Taipei"),
|
||||
BACKUP_DIR: z.string().min(1).default("./backups"),
|
||||
BACKUP_KEEP: z.coerce.number().int().positive().default(14),
|
||||
});
|
||||
const envSchema = z
|
||||
.object({
|
||||
DATABASE_PATH: z.string().min(1).default("./data/app.db"),
|
||||
ATTACHMENTS_DIR: z.string().min(1).default("./data/attachments"),
|
||||
SESSION_SECRET: z
|
||||
.string({ error: "SESSION_SECRET 未設定(請複製 .env.example 為 .env 並填入)" })
|
||||
.min(32, "SESSION_SECRET 至少需要 32 個字元"),
|
||||
TZ_APP: z.string().min(1).default("Asia/Taipei"),
|
||||
BACKUP_DIR: z.string().min(1).default("./backups"),
|
||||
BACKUP_KEEP: z.coerce.number().int().positive().default(14),
|
||||
// oidc:公司 Authentik 登入(正式環境);dev:非正式環境的替代登入。
|
||||
// 不用 NODE_ENV 判斷,因為 e2e 跑的 next start 也是 production。
|
||||
AUTH_MODE: z.enum(["oidc", "dev"]).default("oidc"),
|
||||
// 本系統對外網址,用來組 OIDC redirect URI(平台對 redirect URI 做 strict 比對)。
|
||||
APP_URL: z.url().optional(),
|
||||
// 這些員工編號登入時自動取得系統管理員角色,以逗號分隔。
|
||||
BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS: z
|
||||
.string()
|
||||
.default("")
|
||||
.transform((value) =>
|
||||
value
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
// 由 vibe 平台在部署時注入(保留字),不寫進 repo 或 .env.example。
|
||||
OIDC_ISSUER: z.url().optional(),
|
||||
OIDC_CLIENT_ID: z.string().min(1).optional(),
|
||||
OIDC_CLIENT_SECRET: z.string().min(1).optional(),
|
||||
})
|
||||
.superRefine((env, ctx) => {
|
||||
if (env.AUTH_MODE === "dev") {
|
||||
// 平台注入的 OIDC_ISSUER 存在 = 在正式環境;此時絕不能開啟免驗證的替代登入。
|
||||
if (env.OIDC_ISSUER) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["AUTH_MODE"],
|
||||
message: "偵測到平台注入的 OIDC_ISSUER(正式環境),不得以 AUTH_MODE=dev 啟動",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const key of ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET", "APP_URL"] as const) {
|
||||
if (!env[key]) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: [key],
|
||||
message: `AUTH_MODE=oidc 需要 ${key}(本機開發請設 AUTH_MODE=dev)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (env.APP_URL && !env.APP_URL.startsWith("https://")) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["APP_URL"],
|
||||
message: "AUTH_MODE=oidc 時 APP_URL 必須是 https 網址",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type Env = z.infer<typeof envSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { requireDepartment } from "@/server/auth/current-user";
|
||||
import { createSession, validateSession } from "@/server/auth/session";
|
||||
import { departments, userRoles, users } from "@/server/db/schema";
|
||||
import { withTransaction } from "@/server/db/transaction";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import {
|
||||
assignDepartment,
|
||||
departmentMembersAt,
|
||||
listAccounts,
|
||||
setAccountActive,
|
||||
setRoles,
|
||||
} from "./accounts";
|
||||
|
||||
const TODAY = "2026-10-20";
|
||||
|
||||
describe("帳號與角色", () => {
|
||||
let t: TestDatabase;
|
||||
let design: number;
|
||||
let rnd: number;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
design = t.db
|
||||
.insert(departments)
|
||||
.values({ name: "設計部", type: "general" })
|
||||
.returning()
|
||||
.get().id;
|
||||
rnd = t.db.insert(departments).values({ name: "研發部", type: "rnd" }).returning().get().id;
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
const addUser = (employeeNo: string, values: Partial<typeof users.$inferInsert> = {}) =>
|
||||
t.db
|
||||
.insert(users)
|
||||
.values({ employeeNo, ...values })
|
||||
.returning()
|
||||
.get().id;
|
||||
const roleList = (userId: number) =>
|
||||
t.db
|
||||
.select()
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, userId))
|
||||
.all()
|
||||
.map((r) => r.role)
|
||||
.sort();
|
||||
|
||||
describe("清單篩選", () => {
|
||||
it("「待指派部門」只列在職且未指派部門的人", () => {
|
||||
addUser("E1");
|
||||
addUser("E2", { departmentId: design });
|
||||
addUser("E3", { active: false });
|
||||
expect(listAccounts(t.db, "pending").map((a) => a.employeeNo)).toEqual(["E1"]);
|
||||
expect(listAccounts(t.db, "inactive").map((a) => a.employeeNo)).toEqual(["E3"]);
|
||||
expect(listAccounts(t.db)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("指派部門", () => {
|
||||
it("指派部門後可通過 requireDepartment", () => {
|
||||
const id = addUser("E1");
|
||||
expect(assignDepartment(t.db, id, design, TODAY, TODAY).ok).toBe(true);
|
||||
const user = t.db.select().from(users).where(eq(users.id, id)).get()!;
|
||||
expect(requireDepartment(user).departmentId).toBe(design);
|
||||
});
|
||||
|
||||
it("生效日不可晚於今天、部門必須啟用", () => {
|
||||
const id = addUser("E1");
|
||||
expect(assignDepartment(t.db, id, design, "2026-10-21", TODAY)).toEqual({
|
||||
ok: false,
|
||||
error: "生效日不可晚於今天",
|
||||
});
|
||||
t.db.update(departments).set({ active: false }).where(eq(departments.id, rnd)).run();
|
||||
expect(assignDepartment(t.db, id, rnd, TODAY, TODAY)).toEqual({
|
||||
ok: false,
|
||||
error: "部門不存在或已停用",
|
||||
});
|
||||
});
|
||||
|
||||
it("調部門依生效日決定某日的部門成員", () => {
|
||||
const wang = addUser("E1", { name: "王小明" });
|
||||
assignDepartment(t.db, wang, design, "2026-09-01", TODAY);
|
||||
assignDepartment(t.db, wang, rnd, "2026-10-15", TODAY);
|
||||
|
||||
const members = (dept: number, date: string) =>
|
||||
departmentMembersAt(t.db, dept, date).map((m) => m.employeeNo);
|
||||
expect(members(design, "2026-10-01")).toEqual(["E1"]);
|
||||
expect(members(design, "2026-11-01")).toEqual([]);
|
||||
expect(members(rnd, "2026-11-01")).toEqual(["E1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("停用與啟用", () => {
|
||||
it("停用後 session 立即失效,且自當天起不計入部門成員", () => {
|
||||
const id = addUser("E1");
|
||||
assignDepartment(t.db, id, design, "2026-10-01", TODAY);
|
||||
const token = withTransaction(t.db, (tx) => createSession(tx, id, new Date()));
|
||||
|
||||
expect(setAccountActive(t.db, id, false, TODAY).ok).toBe(true);
|
||||
expect(validateSession(t.db, token, new Date())).toBeNull();
|
||||
expect(departmentMembersAt(t.db, design, "2026-10-19")).toHaveLength(1);
|
||||
expect(departmentMembersAt(t.db, design, TODAY)).toHaveLength(0);
|
||||
|
||||
setAccountActive(t.db, id, true, "2026-10-25");
|
||||
expect(departmentMembersAt(t.db, design, "2026-10-25")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("指派角色", () => {
|
||||
const sysadmin = { id: 999, roles: ["employee", "sysadmin"] as const };
|
||||
|
||||
it("系統管理員可指派角色,員工角色一律保留", () => {
|
||||
const id = addUser("E1");
|
||||
expect(setRoles(t.db, sysadmin, id, ["manager", "admin"]).ok).toBe(true);
|
||||
expect(roleList(id)).toEqual(["admin", "employee", "manager"]);
|
||||
});
|
||||
|
||||
it("非系統管理員嘗試修改他人角色時拒絕", () => {
|
||||
const id = addUser("E1");
|
||||
const admin = { id: 5, roles: ["employee", "admin"] as const };
|
||||
expect(setRoles(t.db, admin, id, ["sysadmin"])).toEqual({
|
||||
ok: false,
|
||||
error: "只有系統管理員可以指派角色",
|
||||
});
|
||||
expect(roleList(id)).toEqual([]);
|
||||
});
|
||||
|
||||
it("不能移除自己的系統管理員角色", () => {
|
||||
const self = addUser("E0");
|
||||
expect(setRoles(t.db, { id: self, roles: ["sysadmin"] }, self, ["employee"])).toEqual({
|
||||
ok: false,
|
||||
error: "不能移除自己的系統管理員角色",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { and, asc, eq, isNull, sql } from "drizzle-orm";
|
||||
import { ROLES, type Role } from "@/lib/roles";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { departments, userDepartmentHistory, userRoles, users } from "@/server/db/schema";
|
||||
import { withTransaction, type Tx } from "@/server/db/transaction";
|
||||
import { deleteUserSessions } from "@/server/auth/session";
|
||||
import { fail, ok, type Result } from "./result";
|
||||
|
||||
export type AccountFilter = "all" | "pending" | "inactive";
|
||||
|
||||
export interface AccountRow {
|
||||
id: number;
|
||||
employeeNo: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
departmentId: number | null;
|
||||
departmentName: string | null;
|
||||
active: boolean;
|
||||
lastLoginAt: string | null;
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
/** 帳號清單。`pending` = 在職但待指派部門;`inactive` = 已停用。 */
|
||||
export function listAccounts(db: Db, filter: AccountFilter = "all"): AccountRow[] {
|
||||
const where =
|
||||
filter === "pending"
|
||||
? and(eq(users.active, true), isNull(users.departmentId))
|
||||
: filter === "inactive"
|
||||
? eq(users.active, false)
|
||||
: undefined;
|
||||
const rows = db
|
||||
.select({
|
||||
id: users.id,
|
||||
employeeNo: users.employeeNo,
|
||||
name: users.name,
|
||||
email: users.email,
|
||||
departmentId: users.departmentId,
|
||||
departmentName: departments.name,
|
||||
active: users.active,
|
||||
lastLoginAt: users.lastLoginAt,
|
||||
})
|
||||
.from(users)
|
||||
.leftJoin(departments, eq(departments.id, users.departmentId))
|
||||
.where(where)
|
||||
.orderBy(asc(users.employeeNo))
|
||||
.all();
|
||||
const roles = db.select().from(userRoles).all();
|
||||
return rows.map((r) => ({
|
||||
...r,
|
||||
roles: ROLES.filter((role) => roles.some((x) => x.userId === r.id && x.role === role)),
|
||||
}));
|
||||
}
|
||||
|
||||
/** 寫入部門生效紀錄並更新目前部門。 */
|
||||
export function recordDepartmentChange(
|
||||
tx: Tx,
|
||||
userId: number,
|
||||
departmentId: number | null,
|
||||
effectiveFrom: string,
|
||||
): void {
|
||||
tx.insert(userDepartmentHistory).values({ userId, departmentId, effectiveFrom }).run();
|
||||
}
|
||||
|
||||
/**
|
||||
* 指派或變更所屬部門,並記錄生效日(不可晚於今天:`users.department_id` 一律代表目前的部門)。
|
||||
* 既有申請的歸屬部門存在申請本身,不受影響。
|
||||
*/
|
||||
export function assignDepartment(
|
||||
db: Db,
|
||||
userId: number,
|
||||
departmentId: number,
|
||||
effectiveFrom: string,
|
||||
today: string,
|
||||
): Result {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(effectiveFrom)) return fail("請輸入生效日期");
|
||||
if (effectiveFrom > today) return fail("生效日不可晚於今天");
|
||||
return withTransaction(db, (tx) => {
|
||||
const dept = tx.select().from(departments).where(eq(departments.id, departmentId)).get();
|
||||
if (!dept || !dept.active) return fail("部門不存在或已停用");
|
||||
const user = tx.select().from(users).where(eq(users.id, userId)).get();
|
||||
if (!user) return fail("人員不存在");
|
||||
if (user.departmentId === departmentId) return ok(undefined);
|
||||
tx.update(users).set({ departmentId }).where(eq(users.id, userId)).run();
|
||||
recordDepartmentChange(tx, userId, departmentId, effectiveFrom);
|
||||
return ok(undefined);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用或重新啟用帳號。停用時刪除其全部 session(下一個請求即失效),
|
||||
* 並記錄自當天起不屬於任何部門,使人數快照不再計入。
|
||||
*/
|
||||
export function setAccountActive(db: Db, userId: number, active: boolean, today: string): Result {
|
||||
return withTransaction(db, (tx) => {
|
||||
const user = tx.select().from(users).where(eq(users.id, userId)).get();
|
||||
if (!user) return fail("人員不存在");
|
||||
if (user.active === active) return ok(undefined);
|
||||
tx.update(users).set({ active }).where(eq(users.id, userId)).run();
|
||||
if (active) {
|
||||
if (user.departmentId !== null) recordDepartmentChange(tx, userId, user.departmentId, today);
|
||||
} else {
|
||||
deleteUserSessions(tx, userId);
|
||||
recordDepartmentChange(tx, userId, null, today);
|
||||
}
|
||||
return ok(undefined);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 設定使用者角色。只有系統管理員可以指派或移除角色;員工角色一律保留;
|
||||
* 系統管理員不能移除自己的系統管理員角色(避免沒有人能管理系統)。
|
||||
*/
|
||||
export function setRoles(
|
||||
db: Db,
|
||||
actor: { id: number; roles: readonly Role[] },
|
||||
userId: number,
|
||||
requested: readonly Role[],
|
||||
): Result {
|
||||
if (!actor.roles.includes("sysadmin")) return fail("只有系統管理員可以指派角色");
|
||||
const roles = new Set<Role>([...requested.filter((r) => ROLES.includes(r)), "employee"]);
|
||||
if (actor.id === userId && !roles.has("sysadmin")) {
|
||||
return fail("不能移除自己的系統管理員角色");
|
||||
}
|
||||
return withTransaction(db, (tx) => {
|
||||
const user = tx.select().from(users).where(eq(users.id, userId)).get();
|
||||
if (!user) return fail("人員不存在");
|
||||
tx.delete(userRoles).where(eq(userRoles.userId, userId)).run();
|
||||
tx.insert(userRoles)
|
||||
.values([...roles].map((role) => ({ userId, role })))
|
||||
.run();
|
||||
return ok(undefined);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 某部門在某日(Asia/Taipei 日期,自 00:00 起)的在職成員,供每月人數快照使用。
|
||||
* 依每位人員在該日之前最後一筆部門生效紀錄判斷;名冊匯入而從未登入的人也包含在內。
|
||||
*/
|
||||
export function departmentMembersAt(db: Db, departmentId: number, date: string) {
|
||||
const latest = sql`(
|
||||
select h2.id from ${userDepartmentHistory} h2
|
||||
where h2.user_id = ${users.id} and h2.effective_from <= ${date}
|
||||
order by h2.effective_from desc, h2.id desc limit 1
|
||||
)`;
|
||||
return db
|
||||
.select({ id: users.id, employeeNo: users.employeeNo, name: users.name })
|
||||
.from(users)
|
||||
.innerJoin(userDepartmentHistory, eq(userDepartmentHistory.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
eq(userDepartmentHistory.id, latest),
|
||||
eq(userDepartmentHistory.departmentId, departmentId),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(users.employeeNo))
|
||||
.all();
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { managedDepartmentIds } from "@/server/auth/scope";
|
||||
import { users } from "@/server/db/schema";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import {
|
||||
assignManager,
|
||||
createDepartment,
|
||||
listActiveDepartments,
|
||||
listDepartments,
|
||||
removeManager,
|
||||
setDepartmentActive,
|
||||
updateDepartment,
|
||||
} from "./departments";
|
||||
|
||||
describe("部門管理", () => {
|
||||
let t: TestDatabase;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
const create = (
|
||||
name: string,
|
||||
code: string | null = null,
|
||||
type: "general" | "rnd" = "general",
|
||||
) => {
|
||||
const r = createDepartment(t.db, { name, code, type });
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
return r.value;
|
||||
};
|
||||
|
||||
it("新增研發部門,類型為研發", () => {
|
||||
const id = create("研發部", "RD", "rnd");
|
||||
expect(listDepartments(t.db)).toMatchObject([{ id, name: "研發部", code: "RD", type: "rnd" }]);
|
||||
});
|
||||
|
||||
it("部門代碼重複時拒絕(新增與編輯)", () => {
|
||||
create("研發部", "RD");
|
||||
const other = create("設計部", "DS");
|
||||
expect(createDepartment(t.db, { name: "X", code: "RD", type: "general" })).toEqual({
|
||||
ok: false,
|
||||
error: "部門代碼已存在",
|
||||
});
|
||||
expect(updateDepartment(t.db, other, { name: "設計部", code: "RD", type: "general" })).toEqual({
|
||||
ok: false,
|
||||
error: "部門代碼已存在",
|
||||
});
|
||||
});
|
||||
|
||||
it("代碼可留空,多個部門都留空不衝突", () => {
|
||||
create("A", "");
|
||||
expect(createDepartment(t.db, { name: "B", code: " ", type: "general" }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("名稱必填", () => {
|
||||
expect(createDepartment(t.db, { name: " ", type: "general" })).toEqual({
|
||||
ok: false,
|
||||
error: "請輸入部門名稱",
|
||||
});
|
||||
});
|
||||
|
||||
it("停用部門不出現在人員的部門選項,但仍保留於部門清單", () => {
|
||||
const id = create("設計部");
|
||||
create("研發部", null, "rnd");
|
||||
setDepartmentActive(t.db, id, false);
|
||||
expect(listActiveDepartments(t.db).map((d) => d.name)).toEqual(["研發部"]);
|
||||
expect(listDepartments(t.db).find((d) => d.id === id)?.active).toBe(false);
|
||||
});
|
||||
|
||||
it("指派主管後取得該部門範圍;移除後立即失去", () => {
|
||||
const design = create("設計部");
|
||||
const manager = t.db
|
||||
.insert(users)
|
||||
.values({ employeeNo: "E20", name: "李經理" })
|
||||
.returning()
|
||||
.get();
|
||||
|
||||
expect(assignManager(t.db, design, " E20 ")).toEqual({ ok: true, value: undefined });
|
||||
const asManager = { id: manager.id, roles: ["employee", "manager"] as const };
|
||||
expect(managedDepartmentIds(t.db, asManager)).toEqual([design]);
|
||||
expect(listDepartments(t.db)[0].managers).toEqual([
|
||||
{ userId: manager.id, employeeNo: "E20", name: "李經理" },
|
||||
]);
|
||||
|
||||
removeManager(t.db, design, manager.id);
|
||||
expect(managedDepartmentIds(t.db, asManager)).toEqual([]);
|
||||
});
|
||||
|
||||
it("指派不存在或已停用的人員時拒絕", () => {
|
||||
const design = create("設計部");
|
||||
t.db.insert(users).values({ employeeNo: "E99", active: false }).run();
|
||||
expect(assignManager(t.db, design, "E404")).toEqual({
|
||||
ok: false,
|
||||
error: "找不到員工編號 E404",
|
||||
});
|
||||
expect(assignManager(t.db, design, "E99")).toEqual({
|
||||
ok: false,
|
||||
error: "該人員已停用,不能指派為主管",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { and, asc, eq, ne } from "drizzle-orm";
|
||||
import { departmentInput, type DepartmentInput } from "@/lib/validation/department";
|
||||
import type { DepartmentType } from "@/lib/department-types";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { departmentManagers, departments, userRoles, users } from "@/server/db/schema";
|
||||
import { withTransaction, type Tx } from "@/server/db/transaction";
|
||||
import { fail, ok, type Result } from "./result";
|
||||
|
||||
export interface DepartmentRow {
|
||||
id: number;
|
||||
code: string | null;
|
||||
name: string;
|
||||
type: DepartmentType;
|
||||
active: boolean;
|
||||
managers: { userId: number; employeeNo: string; name: string | null }[];
|
||||
}
|
||||
|
||||
export function listDepartments(db: Db): DepartmentRow[] {
|
||||
const rows = db.select().from(departments).orderBy(asc(departments.name)).all();
|
||||
const managers = db
|
||||
.select({
|
||||
departmentId: departmentManagers.departmentId,
|
||||
userId: users.id,
|
||||
employeeNo: users.employeeNo,
|
||||
name: users.name,
|
||||
})
|
||||
.from(departmentManagers)
|
||||
.innerJoin(users, eq(users.id, departmentManagers.userId))
|
||||
.orderBy(asc(users.employeeNo))
|
||||
.all();
|
||||
return rows.map((d) => ({
|
||||
id: d.id,
|
||||
code: d.code,
|
||||
name: d.name,
|
||||
type: d.type,
|
||||
active: d.active,
|
||||
managers: managers
|
||||
.filter((m) => m.departmentId === d.id)
|
||||
.map(({ userId, employeeNo, name }) => ({ userId, employeeNo, name })),
|
||||
}));
|
||||
}
|
||||
|
||||
/** 人員可選的部門:只列啟用中的部門。 */
|
||||
export function listActiveDepartments(db: Db | Tx) {
|
||||
return db
|
||||
.select({ id: departments.id, code: departments.code, name: departments.name })
|
||||
.from(departments)
|
||||
.where(eq(departments.active, true))
|
||||
.orderBy(asc(departments.name))
|
||||
.all();
|
||||
}
|
||||
|
||||
function codeTaken(tx: Tx, code: string | null, exceptId?: number): boolean {
|
||||
if (code === null) return false;
|
||||
const condition = exceptId
|
||||
? and(eq(departments.code, code), ne(departments.id, exceptId))
|
||||
: eq(departments.code, code);
|
||||
return tx.select({ id: departments.id }).from(departments).where(condition).get() !== undefined;
|
||||
}
|
||||
|
||||
export function createDepartment(db: Db, input: DepartmentInput): Result<number> {
|
||||
const parsed = departmentInput.safeParse(input);
|
||||
if (!parsed.success) return fail(parsed.error.issues[0].message);
|
||||
return withTransaction(db, (tx) => {
|
||||
if (codeTaken(tx, parsed.data.code)) return fail("部門代碼已存在");
|
||||
const { id } = tx.insert(departments).values(parsed.data).returning().get();
|
||||
return ok(id);
|
||||
});
|
||||
}
|
||||
|
||||
export function updateDepartment(db: Db, id: number, input: DepartmentInput): Result {
|
||||
const parsed = departmentInput.safeParse(input);
|
||||
if (!parsed.success) return fail(parsed.error.issues[0].message);
|
||||
return withTransaction(db, (tx) => {
|
||||
if (codeTaken(tx, parsed.data.code, id)) return fail("部門代碼已存在");
|
||||
const updated = tx
|
||||
.update(departments)
|
||||
.set(parsed.data)
|
||||
.where(eq(departments.id, id))
|
||||
.returning()
|
||||
.get();
|
||||
return updated ? ok(undefined) : fail("部門不存在");
|
||||
});
|
||||
}
|
||||
|
||||
/** 部門不可刪除,只能停用:停用後不出現在人員的部門選項,歷史資料仍可查。 */
|
||||
export function setDepartmentActive(db: Db, id: number, active: boolean): Result {
|
||||
const updated = db
|
||||
.update(departments)
|
||||
.set({ active })
|
||||
.where(eq(departments.id, id))
|
||||
.returning()
|
||||
.get();
|
||||
return updated ? ok(undefined) : fail("部門不存在");
|
||||
}
|
||||
|
||||
/** 以員工編號指派部門主管;被指派者同時取得主管角色,即取得該部門的主管資料範圍。 */
|
||||
export function assignManager(db: Db, departmentId: number, employeeNo: string): Result {
|
||||
const no = employeeNo.trim();
|
||||
return withTransaction(db, (tx) => {
|
||||
const dept = tx.select().from(departments).where(eq(departments.id, departmentId)).get();
|
||||
if (!dept) return fail("部門不存在");
|
||||
const user = tx.select().from(users).where(eq(users.employeeNo, no)).get();
|
||||
if (!user) return fail(`找不到員工編號 ${no}`);
|
||||
if (!user.active) return fail("該人員已停用,不能指派為主管");
|
||||
tx.insert(departmentManagers)
|
||||
.values({ departmentId, userId: user.id })
|
||||
.onConflictDoNothing()
|
||||
.run();
|
||||
tx.insert(userRoles).values({ userId: user.id, role: "manager" }).onConflictDoNothing().run();
|
||||
return ok(undefined);
|
||||
});
|
||||
}
|
||||
|
||||
/** 移除主管指派後立即失去該部門範圍(主管角色保留,由帳號與角色頁管理)。 */
|
||||
export function removeManager(db: Db, departmentId: number, userId: number): Result {
|
||||
db.delete(departmentManagers)
|
||||
.where(
|
||||
and(eq(departmentManagers.departmentId, departmentId), eq(departmentManagers.userId, userId)),
|
||||
)
|
||||
.run();
|
||||
return ok(undefined);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** service 的回傳:成功,或可直接顯示給使用者的錯誤訊息。 */
|
||||
export type Result<T = void> = { ok: true; value: T } | { ok: false; error: string };
|
||||
|
||||
export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
|
||||
export const fail = (error: string): Result<never> => ({ ok: false, error });
|
||||
@@ -0,0 +1,132 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { toCsv } from "@/lib/csv";
|
||||
import { departments, userRoles, users } from "@/server/db/schema";
|
||||
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
|
||||
import { departmentMembersAt } from "./accounts";
|
||||
import { ROSTER_TEMPLATE, commitRoster, validateRoster } from "./roster-import";
|
||||
|
||||
const TODAY = "2026-10-20";
|
||||
const HEADER = ["員工編號", "姓名", "部門", "角色"];
|
||||
const csv = (...rows: string[][]) => toCsv([HEADER, ...rows]);
|
||||
|
||||
describe("名冊 CSV 匯入", () => {
|
||||
let t: TestDatabase;
|
||||
let design: number;
|
||||
let rnd: number;
|
||||
beforeEach(() => {
|
||||
t = createTestDatabase();
|
||||
design = t.db
|
||||
.insert(departments)
|
||||
.values({ name: "設計部", type: "general", code: "DSN" })
|
||||
.returning()
|
||||
.get().id;
|
||||
rnd = t.db.insert(departments).values({ name: "研發部", type: "rnd" }).returning().get().id;
|
||||
t.db.insert(departments).values({ name: "舊部門", type: "general", active: false }).run();
|
||||
});
|
||||
afterEach(() => t.cleanup());
|
||||
|
||||
const user = (employeeNo: string) =>
|
||||
t.db.select().from(users).where(eq(users.employeeNo, employeeNo)).get();
|
||||
const roles = (employeeNo: string) =>
|
||||
t.db
|
||||
.select()
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, user(employeeNo)!.id))
|
||||
.all()
|
||||
.map((r) => r.role)
|
||||
.sort();
|
||||
|
||||
it("預覽顯示將新增與更新的筆數;部門可用代碼或名稱", () => {
|
||||
t.db.insert(users).values({ employeeNo: "E2" }).run();
|
||||
const preview = validateRoster(
|
||||
t.db,
|
||||
csv(["E1", "王小明", "DSN", ""], ["E2", "", "研發部", ""]),
|
||||
);
|
||||
expect(preview.errors).toEqual([]);
|
||||
expect(preview).toMatchObject({ create: 1, update: 1 });
|
||||
});
|
||||
|
||||
it("含錯誤列時列出每一列的原因,且完全不寫入", () => {
|
||||
const text = csv(
|
||||
["E1", "王小明", "設計部", ""],
|
||||
["E2", "李", "設計部", ""],
|
||||
["E3", "陳", "設計部", ""],
|
||||
["", "缺工號", "設計部", ""],
|
||||
["E5", "林", "設計部", ""],
|
||||
["E6", "張", "設計部", ""],
|
||||
["E7", "趙", "設計部", ""],
|
||||
["E8", "錢", "不存在部", "老闆"],
|
||||
);
|
||||
const result = commitRoster(t.db, text, TODAY);
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
errors: [
|
||||
{ line: 5, message: "缺少員工編號" },
|
||||
{ line: 9, message: "部門「不存在部」不存在;角色「老闆」不存在" },
|
||||
],
|
||||
});
|
||||
expect(t.db.select().from(users).all()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("檔案內員工編號重複、部門已停用都視為錯誤", () => {
|
||||
const preview = validateRoster(
|
||||
t.db,
|
||||
csv(["E1", "", "設計部", ""], ["E1", "", "研發部", ""], ["E2", "", "舊部門", ""]),
|
||||
);
|
||||
expect(preview.errors).toEqual([
|
||||
{ line: 3, message: "員工編號與第 2 列重複" },
|
||||
{ line: 4, message: "部門「舊部門」已停用" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("非 UTF-8 檔案(解碼出替代字元)提示改存 UTF-8", () => {
|
||||
const preview = validateRoster(t.db, "��,�\n");
|
||||
expect(preview.errors[0].message).toMatch(/UTF-8/);
|
||||
});
|
||||
|
||||
it("建立尚未登入的人員,從未登入也計入部門在職成員", () => {
|
||||
const result = commitRoster(t.db, csv(["E2001", "陳研發", "研發部", ""]), TODAY);
|
||||
expect(result).toEqual({ ok: true, create: 1, update: 0 });
|
||||
expect(user("E2001")).toMatchObject({
|
||||
name: "陳研發",
|
||||
departmentId: rnd,
|
||||
email: null,
|
||||
firstLoginAt: null,
|
||||
});
|
||||
expect(roles("E2001")).toEqual(["employee"]);
|
||||
expect(departmentMembersAt(t.db, rnd, TODAY).map((m) => m.employeeNo)).toEqual(["E2001"]);
|
||||
});
|
||||
|
||||
it("已存在者更新部門(記錄生效日)與角色;不覆寫登入取得的姓名", () => {
|
||||
commitRoster(t.db, csv(["E1", "名冊姓名", "設計部", ""]), "2026-10-01");
|
||||
t.db.update(users).set({ name: "公司帳號姓名" }).where(eq(users.employeeNo, "E1")).run();
|
||||
|
||||
const result = commitRoster(t.db, csv(["E1", "另一個姓名", "研發部", "員工、部門主管"]), TODAY);
|
||||
expect(result).toEqual({ ok: true, create: 0, update: 1 });
|
||||
expect(user("E1")).toMatchObject({ name: "公司帳號姓名", departmentId: rnd });
|
||||
expect(roles("E1")).toEqual(["employee", "manager"]);
|
||||
expect(departmentMembersAt(t.db, design, "2026-10-19").map((m) => m.employeeNo)).toEqual([
|
||||
"E1",
|
||||
]);
|
||||
expect(departmentMembersAt(t.db, rnd, TODAY).map((m) => m.employeeNo)).toEqual(["E1"]);
|
||||
});
|
||||
|
||||
it("角色欄留空時不變更既有角色;名冊不會移除系統管理員角色", () => {
|
||||
commitRoster(t.db, csv(["E1", "", "設計部", "系統管理員、管理者"]), TODAY);
|
||||
commitRoster(t.db, csv(["E1", "", "設計部", ""]), TODAY);
|
||||
expect(roles("E1")).toEqual(["admin", "employee", "sysadmin"]);
|
||||
|
||||
commitRoster(t.db, csv(["E1", "", "設計部", "員工"]), TODAY);
|
||||
expect(roles("E1")).toEqual(["employee", "sysadmin"]);
|
||||
});
|
||||
|
||||
it("範本本身可通過驗證(部門存在時)", () => {
|
||||
const preview = validateRoster(t.db, toCsv(ROSTER_TEMPLATE));
|
||||
expect(preview.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("缺少必要欄位時提示標題列錯誤", () => {
|
||||
expect(validateRoster(t.db, "姓名\n王小明\n").errors[0].message).toMatch(/員工編號/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { and, eq, ne } from "drizzle-orm";
|
||||
import { parseCsv } from "@/lib/csv";
|
||||
import { ROLES, ROLE_LABELS, type Role } from "@/lib/roles";
|
||||
import type { Db } from "@/server/db/client";
|
||||
import { departments, userRoles, users } from "@/server/db/schema";
|
||||
import { withTransaction, type Tx } from "@/server/db/transaction";
|
||||
import { recordDepartmentChange } from "./accounts";
|
||||
|
||||
export const ROSTER_HEADERS = ["員工編號", "姓名", "部門", "角色"] as const;
|
||||
|
||||
/** 範本內容:標題列與一列範例。部門可填部門代碼或名稱;角色可留空,多個以「、」分隔。 */
|
||||
export const ROSTER_TEMPLATE: string[][] = [
|
||||
[...ROSTER_HEADERS],
|
||||
["E0001", "王小明", "設計部", "員工、部門主管"],
|
||||
];
|
||||
|
||||
export interface RosterRowError {
|
||||
/** CSV 檔案中的列號(標題列為第 1 列)。 */
|
||||
line: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface RosterRow {
|
||||
line: number;
|
||||
employeeNo: string;
|
||||
name: string | null;
|
||||
departmentId: number;
|
||||
/** null = 角色欄留空,不變更既有角色。 */
|
||||
roles: Role[] | null;
|
||||
}
|
||||
|
||||
export interface RosterPreview {
|
||||
rows: RosterRow[];
|
||||
errors: RosterRowError[];
|
||||
create: number;
|
||||
update: number;
|
||||
}
|
||||
|
||||
const ROLE_BY_NAME = new Map<string, Role>([
|
||||
...ROLES.map((r) => [r, r] as const),
|
||||
...ROLES.map((r) => [ROLE_LABELS[r], r] as const),
|
||||
["主管", "manager"],
|
||||
["部長", "manager"],
|
||||
]);
|
||||
|
||||
/**
|
||||
* 驗證整份名冊(全部列都檢查完才回傳)。有任何錯誤時不得寫入。
|
||||
* Big5 等非 UTF-8 編碼解碼後會出現替代字元 U+FFFD,此時直接提示改存 UTF-8。
|
||||
*/
|
||||
export function validateRoster(db: Db | Tx, text: string): RosterPreview {
|
||||
const preview: RosterPreview = { rows: [], errors: [], create: 0, update: 0 };
|
||||
if (text.includes("�")) {
|
||||
preview.errors.push({
|
||||
line: 1,
|
||||
message: "檔案不是 UTF-8 編碼,請在 Excel 另存為「CSV UTF-8」",
|
||||
});
|
||||
return preview;
|
||||
}
|
||||
const [header, ...records] = parseCsv(text);
|
||||
if (!header) {
|
||||
preview.errors.push({ line: 1, message: "檔案沒有內容" });
|
||||
return preview;
|
||||
}
|
||||
const columns = header.map((h) => h.trim());
|
||||
const index = (name: string) => columns.indexOf(name);
|
||||
if (index("員工編號") < 0 || index("部門") < 0) {
|
||||
preview.errors.push({ line: 1, message: "標題列必須包含「員工編號」與「部門」欄位" });
|
||||
return preview;
|
||||
}
|
||||
if (records.length === 0) {
|
||||
preview.errors.push({ line: 2, message: "沒有資料列" });
|
||||
return preview;
|
||||
}
|
||||
|
||||
const allDepartments = db.select().from(departments).all();
|
||||
const existing = new Set(
|
||||
db
|
||||
.select({ employeeNo: users.employeeNo })
|
||||
.from(users)
|
||||
.all()
|
||||
.map((u) => u.employeeNo),
|
||||
);
|
||||
const seen = new Map<string, number>();
|
||||
|
||||
records.forEach((record, i) => {
|
||||
const line = i + 2;
|
||||
const cell = (name: string) => (index(name) >= 0 ? (record[index(name)] ?? "").trim() : "");
|
||||
const errors: string[] = [];
|
||||
|
||||
const employeeNo = cell("員工編號");
|
||||
if (!employeeNo) errors.push("缺少員工編號");
|
||||
else if (seen.has(employeeNo)) errors.push(`員工編號與第 ${seen.get(employeeNo)} 列重複`);
|
||||
else seen.set(employeeNo, line);
|
||||
|
||||
const deptText = cell("部門");
|
||||
const dept =
|
||||
allDepartments.find((d) => d.code !== null && d.code === deptText) ??
|
||||
allDepartments.find((d) => d.name === deptText);
|
||||
if (!deptText) errors.push("缺少部門");
|
||||
else if (!dept) errors.push(`部門「${deptText}」不存在`);
|
||||
else if (!dept.active) errors.push(`部門「${deptText}」已停用`);
|
||||
|
||||
const roleText = cell("角色");
|
||||
let roles: Role[] | null = null;
|
||||
if (roleText) {
|
||||
roles = [];
|
||||
for (const part of roleText
|
||||
.split(/[、,;;|]/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)) {
|
||||
const role = ROLE_BY_NAME.get(part);
|
||||
if (role) roles.push(role);
|
||||
else errors.push(`角色「${part}」不存在`);
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
preview.errors.push({ line, message: errors.join(";") });
|
||||
return;
|
||||
}
|
||||
preview.rows.push({
|
||||
line,
|
||||
employeeNo,
|
||||
name: cell("姓名") || null,
|
||||
departmentId: dept!.id,
|
||||
roles,
|
||||
});
|
||||
if (existing.has(employeeNo)) preview.update++;
|
||||
else preview.create++;
|
||||
});
|
||||
return preview;
|
||||
}
|
||||
|
||||
/**
|
||||
* 寫入名冊:單一交易內重新驗證(預覽之後資料可能已變動),有錯誤就完全不寫入。
|
||||
* 以員工編號 upsert:新的人員建立為尚未登入、具員工角色;已存在者更新部門(記錄生效日)與角色。
|
||||
* 姓名只在系統中尚無姓名時寫入——登入後以公司帳號的姓名為準。
|
||||
*/
|
||||
export type CommitRosterResult =
|
||||
{ ok: true; create: number; update: number } | { ok: false; errors: RosterRowError[] };
|
||||
|
||||
export function commitRoster(db: Db, text: string, today: string): CommitRosterResult {
|
||||
return withTransaction(db, (tx): CommitRosterResult => {
|
||||
const preview = validateRoster(tx, text);
|
||||
if (preview.errors.length > 0) return { ok: false, errors: preview.errors };
|
||||
for (const row of preview.rows) importRow(tx, row, today);
|
||||
return { ok: true, create: preview.create, update: preview.update };
|
||||
});
|
||||
}
|
||||
|
||||
function importRow(tx: Tx, row: RosterRow, today: string): void {
|
||||
let user = tx.select().from(users).where(eq(users.employeeNo, row.employeeNo)).get();
|
||||
if (!user) {
|
||||
user = tx
|
||||
.insert(users)
|
||||
.values({ employeeNo: row.employeeNo, name: row.name, departmentId: row.departmentId })
|
||||
.returning()
|
||||
.get();
|
||||
recordDepartmentChange(tx, user.id, row.departmentId, today);
|
||||
} else {
|
||||
if (user.name === null && row.name !== null) {
|
||||
tx.update(users).set({ name: row.name }).where(eq(users.id, user.id)).run();
|
||||
}
|
||||
if (user.departmentId !== row.departmentId) {
|
||||
tx.update(users).set({ departmentId: row.departmentId }).where(eq(users.id, user.id)).run();
|
||||
if (user.active) recordDepartmentChange(tx, user.id, row.departmentId, today);
|
||||
}
|
||||
}
|
||||
|
||||
if (row.roles !== null) {
|
||||
// 名冊不會移除系統管理員角色(只能在帳號與角色頁管理),避免匯入把管理者鎖在系統外。
|
||||
tx.delete(userRoles)
|
||||
.where(and(eq(userRoles.userId, user.id), ne(userRoles.role, "sysadmin")))
|
||||
.run();
|
||||
}
|
||||
const roles = new Set<Role>(["employee", ...(row.roles ?? [])]);
|
||||
for (const role of roles) {
|
||||
tx.insert(userRoles).values({ userId: user.id, role }).onConflictDoNothing().run();
|
||||
}
|
||||
}
|
||||
@@ -27,4 +27,12 @@ describe("runStartupChecks", () => {
|
||||
const { runStartupChecks } = await import("./startup");
|
||||
expect(() => runStartupChecks()).toThrow(/SESSION_SECRET 未設定/);
|
||||
});
|
||||
|
||||
it("dev 模式遇到平台注入的 OIDC_ISSUER 時拒絕啟動", async () => {
|
||||
vi.stubEnv("ATTACHMENTS_DIR", path.join(dir, "attachments"));
|
||||
vi.stubEnv("AUTH_MODE", "dev");
|
||||
vi.stubEnv("OIDC_ISSUER", "https://auth.moonshine-studio.net/application/o/vibe-x/");
|
||||
const { runStartupChecks } = await import("./startup");
|
||||
expect(() => runStartupChecks()).toThrow(/不得以 AUTH_MODE=dev 啟動/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto";
|
||||
import http from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
export type MockIdTokenClaims = Record<string, unknown>;
|
||||
|
||||
interface PendingCode {
|
||||
codeChallenge: string;
|
||||
nonce: string;
|
||||
claims: MockIdTokenClaims;
|
||||
}
|
||||
|
||||
/**
|
||||
* 整合測試用的最小 OIDC provider:discovery、JWKS、token endpoint(驗證 PKCE,簽發 RS256 ID token)。
|
||||
* 不實作授權頁面:測試直接以 `issueCode` 模擬「使用者在 Authentik 完成登入」。
|
||||
*/
|
||||
export async function startMockOidcProvider(clientId: string) {
|
||||
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
||||
const jwk = { ...publicKey.export({ format: "jwk" }), kid: "test", alg: "RS256", use: "sig" };
|
||||
const codes = new Map<string, PendingCode>();
|
||||
let issuer = "";
|
||||
|
||||
const signJwt = (payload: object) => {
|
||||
const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString("base64url");
|
||||
const input = `${enc({ alg: "RS256", typ: "JWT", kid: "test" })}.${enc(payload)}`;
|
||||
return `${input}.${sign("sha256", Buffer.from(input), privateKey).toString("base64url")}`;
|
||||
};
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", issuer);
|
||||
const json = (status: number, body: object) => {
|
||||
res.writeHead(status, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify(body));
|
||||
};
|
||||
if (url.pathname === "/.well-known/openid-configuration") {
|
||||
return json(200, {
|
||||
issuer,
|
||||
authorization_endpoint: `${issuer}authorize`,
|
||||
token_endpoint: `${issuer}token`,
|
||||
jwks_uri: `${issuer}jwks`,
|
||||
end_session_endpoint: `${issuer}end-session`,
|
||||
response_types_supported: ["code"],
|
||||
subject_types_supported: ["public"],
|
||||
id_token_signing_alg_values_supported: ["RS256"],
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/jwks") return json(200, { keys: [jwk] });
|
||||
if (url.pathname === "/token" && req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => (body += chunk));
|
||||
req.on("end", () => {
|
||||
const params = new URLSearchParams(body);
|
||||
const code = params.get("code") ?? "";
|
||||
const pending = codes.get(code);
|
||||
codes.delete(code);
|
||||
const challenge = createHash("sha256")
|
||||
.update(params.get("code_verifier") ?? "")
|
||||
.digest("base64url");
|
||||
if (!pending || challenge !== pending.codeChallenge) {
|
||||
return json(400, { error: "invalid_grant" });
|
||||
}
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
return json(200, {
|
||||
access_token: randomBytes(16).toString("hex"),
|
||||
token_type: "Bearer",
|
||||
expires_in: 300,
|
||||
id_token: signJwt({
|
||||
iss: issuer,
|
||||
aud: clientId,
|
||||
sub: `sub-${randomBytes(4).toString("hex")}`,
|
||||
iat: now,
|
||||
exp: now + 300,
|
||||
nonce: pending.nonce,
|
||||
...pending.claims,
|
||||
}),
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
json(404, { error: "not_found" });
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
issuer = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
|
||||
|
||||
return {
|
||||
issuer,
|
||||
/** 模擬使用者在 Authentik 完成登入:依授權網址的 nonce 與 PKCE challenge 發出 code。 */
|
||||
issueCode(authorizationUrl: URL, claims: MockIdTokenClaims): string {
|
||||
const code = randomBytes(8).toString("hex");
|
||||
codes.set(code, {
|
||||
codeChallenge: authorizationUrl.searchParams.get("code_challenge") ?? "",
|
||||
nonce: authorizationUrl.searchParams.get("nonce") ?? "",
|
||||
claims,
|
||||
});
|
||||
return code;
|
||||
},
|
||||
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import { DEMO, loginAs } from "./helpers";
|
||||
|
||||
test("未登入直接開啟管理頁時導向登入頁並記住原頁面", async ({ page }) => {
|
||||
await page.goto("/admin/settlements");
|
||||
await expect(page).toHaveURL(/\/login\?returnTo=%2Fadmin%2Fsettlements$/);
|
||||
});
|
||||
|
||||
test("登入後回到原本要去的頁面", async ({ page }) => {
|
||||
await loginAs(page, DEMO.admin, "/admin/settlements");
|
||||
await expect(page).toHaveURL(/\/admin\/settlements$/);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("全公司月結");
|
||||
});
|
||||
|
||||
test("員工直接輸入 /admin/settlements 看到無權限頁,不回傳管理資料", async ({ page }) => {
|
||||
await loginAs(page, DEMO.employee);
|
||||
const response = await page.goto("/admin/settlements");
|
||||
expect(response?.status()).toBe(403);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("無權限");
|
||||
await expect(page.getByText("全公司月結")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("員工的導覽只有首頁、新增申請、我的申請", async ({ page }) => {
|
||||
await loginAs(page, DEMO.employee);
|
||||
const nav = page.getByRole("navigation", { name: "主要導覽" });
|
||||
await expect(nav.getByRole("link")).toHaveText(["首頁", "新增申請", "我的申請"]);
|
||||
});
|
||||
|
||||
test("主管可進入部門審核,但不能進入全公司月結", async ({ page }) => {
|
||||
await loginAs(page, DEMO.manager);
|
||||
await expect(
|
||||
page.getByRole("navigation", { name: "主要導覽" }).getByRole("link", { name: "部門審核" }),
|
||||
).toBeVisible();
|
||||
expect((await page.goto("/department/review"))?.status()).toBe(200);
|
||||
expect((await page.goto("/admin/settlements"))?.status()).toBe(403);
|
||||
});
|
||||
|
||||
test("待指派部門者在首頁看到提示", async ({ page }) => {
|
||||
await loginAs(page, DEMO.pendingDepartment);
|
||||
await expect(page.getByText("尚未指派部門,請洽人資")).toBeVisible();
|
||||
});
|
||||
|
||||
test("登出後回到登入頁,再開首頁需重新登入", async ({ page }) => {
|
||||
await loginAs(page, DEMO.employee);
|
||||
await page.getByRole("button", { name: "登出" }).click();
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
await page.goto("/dashboard");
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import { DEMO, loginAs } from "./helpers";
|
||||
|
||||
// 每個測試用自己的工號與部門名稱,避免與其他平行執行的測試互相影響。
|
||||
|
||||
test("系統管理員新增部門,代碼重複時顯示錯誤", async ({ page }) => {
|
||||
await loginAs(page, DEMO.sysadmin, "/admin/departments");
|
||||
const form = page.locator("form").filter({ has: page.getByRole("button", { name: "新增" }) });
|
||||
await form.getByLabel("部門名稱").fill("E2E 廣告部");
|
||||
await form.getByLabel("部門代碼(選填)").fill("E2E-AD");
|
||||
await form.getByRole("button", { name: "新增" }).click();
|
||||
await expect(page.locator('input[name="name"][value="E2E 廣告部"]')).toHaveCount(1);
|
||||
|
||||
await form.getByLabel("部門名稱").fill("E2E 另一個部");
|
||||
await form.getByLabel("部門代碼(選填)").fill("E2E-AD");
|
||||
await form.getByRole("button", { name: "新增" }).click();
|
||||
await expect(page.getByText("部門代碼已存在")).toBeVisible();
|
||||
});
|
||||
|
||||
test("匯入名冊:有錯誤時不匯入;修正後預覽並確認匯入", async ({ page }) => {
|
||||
await loginAs(page, DEMO.sysadmin, "/admin/accounts/import");
|
||||
const header = "員工編號,姓名,部門,角色\r\n";
|
||||
|
||||
await page.getByLabel("名冊檔案(CSV,UTF-8)").setInputFiles({
|
||||
name: "bad.csv",
|
||||
mimeType: "text/csv",
|
||||
buffer: Buffer.from(header + "E9001,測試一,DEMO-DSN,\r\nE9002,測試二,不存在部,\r\n"),
|
||||
});
|
||||
await page.getByRole("button", { name: "上傳並檢查" }).click();
|
||||
await expect(page.getByText("第 3 列:部門「不存在部」不存在")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "確認匯入" })).toHaveCount(0);
|
||||
|
||||
await page.getByLabel("名冊檔案(CSV,UTF-8)").setInputFiles({
|
||||
name: "good.csv",
|
||||
mimeType: "text/csv",
|
||||
buffer: Buffer.from(
|
||||
String.fromCharCode(0xfeff) +
|
||||
header +
|
||||
"E9001,測試一,DEMO-DSN,\r\nE9002,測試二,研發部(示範),\r\n",
|
||||
),
|
||||
});
|
||||
await page.getByRole("button", { name: "上傳並檢查" }).click();
|
||||
await expect(page.getByText("將新增 2 筆、更新 0 筆人員資料。")).toBeVisible();
|
||||
await page.getByRole("button", { name: "確認匯入" }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/admin\/accounts\?notice=/);
|
||||
await expect(page.getByText("已匯入:新增 2 筆、更新 0 筆")).toBeVisible();
|
||||
await expect(page.getByTestId("account-E9001")).toContainText("設計部(示範)");
|
||||
});
|
||||
|
||||
test("待指派部門者被指派部門後,提示消失", async ({ browser }) => {
|
||||
const newcomer = await browser.newPage();
|
||||
await loginAs(newcomer, "E9100");
|
||||
await expect(newcomer.getByText("尚未指派部門,請洽人資")).toBeVisible();
|
||||
|
||||
const admin = await browser.newPage();
|
||||
await loginAs(admin, DEMO.sysadmin, "/admin/accounts?filter=pending");
|
||||
const row = admin.getByTestId("account-E9100");
|
||||
await row.getByLabel("所屬部門").selectOption({ label: "設計部(示範)" });
|
||||
await row.getByRole("button", { name: "指派部門" }).click();
|
||||
await expect(admin.getByTestId("account-E9100")).toHaveCount(0);
|
||||
|
||||
await newcomer.reload();
|
||||
await expect(newcomer.getByText("尚未指派部門,請洽人資")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("非系統管理員無法進入帳號管理與名冊匯入", async ({ page }) => {
|
||||
await loginAs(page, DEMO.admin);
|
||||
expect((await page.goto("/admin/accounts"))?.status()).toBe(403);
|
||||
// 範本是下載回應,用 request 檢查狀態碼(page.goto 遇到下載會失敗)。
|
||||
const template = await page.request.get("/admin/accounts/import/template");
|
||||
expect(template.status()).toBe(403);
|
||||
expect(template.headers()["content-disposition"]).toBeUndefined();
|
||||
});
|
||||
@@ -6,5 +6,6 @@ export const e2eEnv = {
|
||||
DATABASE_PATH: "./data/e2e/app.db",
|
||||
ATTACHMENTS_DIR: "./data/e2e/attachments",
|
||||
SESSION_SECRET: "e2e-session-secret-0123456789abcdef",
|
||||
AUTH_MODE: "dev",
|
||||
TZ_APP: "Asia/Taipei",
|
||||
};
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
|
||||
/** 以替代登入(AUTH_MODE=dev)登入示範使用者(見 src/server/db/seed.ts 的 DEMO_USERS)。 */
|
||||
export async function loginAs(page: Page, employeeNo: string, returnTo?: string) {
|
||||
await page.goto(returnTo ? `/login/dev?returnTo=${encodeURIComponent(returnTo)}` : "/login/dev");
|
||||
await page.getByLabel("員工編號").fill(employeeNo);
|
||||
await page.getByRole("button", { name: "登入" }).click();
|
||||
await expect(page).not.toHaveURL(/\/login/);
|
||||
}
|
||||
|
||||
export const DEMO = {
|
||||
employee: "D0001",
|
||||
manager: "D0002",
|
||||
admin: "D0004",
|
||||
sysadmin: "D0005",
|
||||
pendingDepartment: "D0006",
|
||||
} as const;
|
||||
@@ -1,7 +1,8 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("首頁可以開啟並顯示系統名稱", async ({ page }) => {
|
||||
test("未登入開啟首頁時導向登入頁", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await expect(page).toHaveURL(/\/login$/);
|
||||
await expect(page).toHaveTitle("AI 補助申請系統");
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("AI 補助申請系統");
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ export default defineConfig({
|
||||
// 測試不讀 .env;需要的環境變數在這裡給固定值。
|
||||
env: {
|
||||
SESSION_SECRET: "test-session-secret-0123456789abcdef",
|
||||
AUTH_MODE: "dev",
|
||||
TZ_APP: "Asia/Taipei",
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user