Compare commits
No commits in common. "main" and "v2026.05.18" have entirely different histories.
main
...
v2026.05.1
17
.env.example
17
.env.example
|
|
@ -1,14 +1,11 @@
|
|||
# OA 门户环境变量(本地开发)
|
||||
# OA 门户环境变量
|
||||
LDAP_URL=ldap://localhost:3890
|
||||
LDAP_BASE_DN=dc=tlyq,dc=ai
|
||||
LDAP_ADMIN_DN=uid=admin,ou=people,dc=tlyq,dc=ai
|
||||
JWT_SECRET=dev-jwt-secret-local
|
||||
JWT_SECRET=change-me-same-across-all-sites
|
||||
COOKIE_DOMAIN=
|
||||
NODE_ENV=development
|
||||
NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||
|
||||
# OIDC 配置
|
||||
AUTHELIA_URL=http://127.0.0.1:6180
|
||||
OIDC_CLIENT_ID=oa-oidc
|
||||
OIDC_CLIENT_SECRET=<见 Authelia 配置>
|
||||
OIDC_REDIRECT_URI=http://127.0.0.1:6179/api/auth/callback
|
||||
SMTP_HOST=smtphz.qiye.163.com
|
||||
SMTP_PORT=465
|
||||
SMTP_USER=gxp@qx002575.com
|
||||
SMTP_PASS=
|
||||
SMTP_FROM=gxp@qx002575.com
|
||||
|
|
|
|||
|
|
@ -2,6 +2,3 @@ node_modules/
|
|||
.next/
|
||||
.env
|
||||
.DS_Store
|
||||
.env.local
|
||||
.DS_Store
|
||||
tsconfig.tsbuildinfo
|
||||
|
|
|
|||
14
CHANGELOG.md
14
CHANGELOG.md
|
|
@ -1,19 +1,5 @@
|
|||
# 变更日志
|
||||
|
||||
## 2026-06-30
|
||||
|
||||
- [新增] SSO 统一认证:集成 Authelia OIDC,支持统一认证登录
|
||||
- [新增] OIDC 登录页面:添加「统一认证登录」按钮,支持 LDAP 回退
|
||||
- [新增] `src/lib/oidc.ts`:OIDC 客户端配置(PKCE + state + nonce)
|
||||
- [新增] `src/app/api/auth/login/oidc/route.ts`:OIDC 登录端点
|
||||
- [新增] `src/app/api/auth/callback/route.ts`:OIDC 回调处理
|
||||
- [新增] `src/app/api/auth/logout/route.ts`:跨域登出(支持 domain 参数)
|
||||
- [修复] NODE_TLS_REJECT_UNAUTHORIZED=0:Authelia 使用自签名证书
|
||||
- [修复] OIDC redirect_uri 回调重定向到 localhost:添加 getBaseUrl() 函数
|
||||
- [修复] token_endpoint_auth_method 配置缺失:添加 client_secret_basic
|
||||
- [优化] docker-compose.yml:统一环境变量管理,移除 env_file
|
||||
- [优化] .env.example:添加 OIDC 配置模板
|
||||
|
||||
## 2026-05-18
|
||||
|
||||
- [安全] 邮件发送从 163 企业邮箱 SMTP → Resend API(Sending Access 权限),凭证从邮箱完整密码降级为仅可发信的 API Key
|
||||
|
|
|
|||
25
CLAUDE.md
25
CLAUDE.md
|
|
@ -41,11 +41,7 @@ npm run build # 生产构建
|
|||
| `src/app/login/page.tsx` | 登录页(LLDAP 认证) |
|
||||
| `src/app/profile/page.tsx` | 个人信息页(账户信息 + 修改密码) |
|
||||
| `src/app/admin/create-user/page.tsx` | 用户管理页(创建/删除/角色管理,仅 admin 可见) |
|
||||
| `src/app/api/auth/login/route.ts` | 登录 API(LDAP 认证 + 审计日志 + 跨站点角色同步) |
|
||||
| `src/app/api/auth/callback/route.ts` | OIDC callback(handleOidcCallback + 跨站点角色同步) |
|
||||
| `src/lib/db.ts` | **新增** SQLite 数据库(审计日志专用) |
|
||||
| `src/lib/audit.ts` | **新增** 审计日志写入封装 |
|
||||
| `src/lib/sync-user.ts` | **新增** 跨站点用户角色同步函数(syncUserToAllSites) |
|
||||
| `src/app/api/auth/login/route.ts` | 登录 API(OA 仅 LLDAP 认证,无本地 DB) |
|
||||
| `src/app/api/auth/logout/route.ts` | 退出 API(清除 tlyq_session) |
|
||||
| `src/app/api/auth/change-password/route.ts` | 修改密码(docker exec 调 lldap_set_password) |
|
||||
| `src/app/api/admin/create-user/route.ts` | 创建用户(SQLite 写 LLDAP + 自动同步站点 + 角色设置) |
|
||||
|
|
@ -82,16 +78,6 @@ OA 本身**不存储用户数据**(无本地 users 表),纯 LLDAP 认证
|
|||
| `JWT_SECRET` | `dev-secret-key-local` | 强随机值(与 assets/issue 相同) |
|
||||
| `COOKIE_DOMAIN` | `""`(空) | `.tlyq.ai` |
|
||||
| `RESEND_API_KEY` | `re_xxxxxxxxxxxx` | Resend API Key(Sending Access 权限) |
|
||||
| `AUTHELIA_URL` | `https://sso.tlyq.ai` | 同 |
|
||||
| `OIDC_CLIENT_ID` | `oa-oidc` | 同 |
|
||||
| `OIDC_CLIENT_SECRET` | 本地生成的哈希值 | 服务器生成的哈希值 |
|
||||
| `OIDC_REDIRECT_URI` | `http://localhost:6179/api/auth/callback` | `https://oa.tlyq.ai/api/auth/callback` |
|
||||
| `NODE_TLS_REJECT_UNAUTHORIZED` | 不需要 | `0`(Authelia 使用自签名证书) |
|
||||
| `INTERNAL_API_KEY` | 各站点相同值 | 由 deploy-ai.sh 自动生成并注入(所有站点共用) |
|
||||
| `MONITOR_INTERNAL_URL` | `http://localhost:6181` | `http://monitor-ai:3000`(跨站点同步目标) |
|
||||
| `ASSETS_INTERNAL_URL` | `http://localhost:6177` | `http://assets-ai:3000`(跨站点同步目标) |
|
||||
| `ISSUE_INTERNAL_URL` | `http://localhost:6176` | `http://issue-ai:3000`(跨站点同步目标) |
|
||||
| `DATABASE_PATH` | `./data/oa.db` | `/app/data/oa.db`(审计日志 SQLite) |
|
||||
|
||||
### `.env` 示例
|
||||
|
||||
|
|
@ -103,15 +89,6 @@ JWT_SECRET=dev-secret-key-local
|
|||
COOKIE_DOMAIN=
|
||||
NODE_ENV=development
|
||||
RESEND_API_KEY=re_xxxxxxxxxxxx
|
||||
AUTHELIA_URL=https://sso.tlyq.ai
|
||||
OIDC_CLIENT_ID=oa-oidc
|
||||
OIDC_CLIENT_SECRET=<本地生成的哈希值>
|
||||
OIDC_REDIRECT_URI=http://localhost:6179/api/auth/callback
|
||||
DATABASE_PATH=./data/oa.db
|
||||
INTERNAL_API_KEY=dev-internal-key-change-in-production
|
||||
MONITOR_INTERNAL_URL=http://localhost:6181
|
||||
ASSETS_INTERNAL_URL=http://localhost:6177
|
||||
ISSUE_INTERNAL_URL=http://localhost:6176
|
||||
```
|
||||
|
||||
---
|
||||
|
|
|
|||
35
Dockerfile
35
Dockerfile
|
|
@ -1,35 +0,0 @@
|
|||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS runner
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
# 将 nextjs 加入 docker 组(Alpine: -g 而非 --gid),允许访问 docker.sock
|
||||
RUN addgroup -g 988 docker 2>/dev/null; addgroup nextjs docker
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
# docker-cli: 密码修改等写操作仍需 docker exec lldap(LLDAP 非 WAL 模式,不可并发写)
|
||||
# sqlite: 直连只读查询 LLDAP/asstes/issue 数据库
|
||||
# bcryptjs: OIDC callback 中 JWT 签发需要
|
||||
RUN apk add --no-cache docker-cli sqlite && npm install bcryptjs
|
||||
|
||||
USER nextjs
|
||||
|
||||
EXPOSE 3000
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
|
|
@ -46,5 +46,5 @@ npm run dev # http://localhost:6179
|
|||
|
||||
## 相关文档
|
||||
|
||||
- [OA 设计文档](../docs/design/OA-DESIGN.md) — 完整架构、认证流程、迁移步骤
|
||||
- [OA 设计文档](../docs/OA-DESIGN.md) — 完整架构、认证流程、迁移步骤
|
||||
- [OA UI 设计](../docs/OA-UI-DESIGN.md) — 页面设计、配色方案
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
# OA 生产环境配置(模板)
|
||||
# 真实密钥由首次部署时生成,后续部署不覆盖
|
||||
LDAP_URL=ldap://lldap:3890
|
||||
LDAP_BASE_DN=dc=tlyq,dc=ai
|
||||
LDAP_ADMIN_DN=uid=admin,ou=people,dc=tlyq,dc=ai
|
||||
JWT_SECRET=__JWT_SECRET__
|
||||
COOKIE_DOMAIN=.tlyq.ai
|
||||
NODE_ENV=production
|
||||
NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||
AUTHELIA_URL=https://sso.tlyq.ai
|
||||
OIDC_CLIENT_ID=oa-oidc
|
||||
OIDC_CLIENT_SECRET=__OIDC_CLIENT_SECRET__
|
||||
OIDC_REDIRECT_URI=https://oa.tlyq.ai/api/auth/callback
|
||||
|
|
@ -7,40 +7,21 @@ services:
|
|||
environment:
|
||||
- LDAP_URL=ldap://lldap:3890
|
||||
- LDAP_BASE_DN=dc=tlyq,dc=ai
|
||||
- LLDAP_ADMIN_PASSWORD=${LLDAP_ADMIN_PASSWORD}
|
||||
- JWT_SECRET=${JWT_SECRET:-oa-shared-jwt-secret-tlyq-2026}
|
||||
- JWT_SECRET=oa-shared-jwt-secret-tlyq-2026
|
||||
- COOKIE_DOMAIN=.tlyq.ai
|
||||
- NODE_ENV=production
|
||||
- NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||
- HOSTNAME=0.0.0.0
|
||||
- TZ=Asia/Shanghai
|
||||
- ASSETS_DB_PATH=/data/other-sites/assets/assets.db
|
||||
- ISSUE_DB_PATH=/data/other-sites/issue/issue.db
|
||||
- RESEND_API_KEY=${RESEND_API_KEY}
|
||||
- AUTHELIA_URL=${AUTHELIA_URL:-https://sso.tlyq.ai}
|
||||
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-oa-oidc}
|
||||
- OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET}
|
||||
- OIDC_REDIRECT_URI=${OIDC_REDIRECT_URI:-https://oa.tlyq.ai/api/auth/callback}
|
||||
- ASSETS_INTERNAL_URL=http://assets-ai:3000
|
||||
- ISSUE_INTERNAL_URL=http://issue-ai:3000
|
||||
- MONITOR_INTERNAL_URL=http://monitor-ai:3000
|
||||
- MONITOR_DB_PATH=/data/other-sites/monitor/monitor.db
|
||||
volumes:
|
||||
- ./.next:/app/.next
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
# 挂载外部数据目录(非单个文件),确保 SQLite WAL 文件共享
|
||||
- /root/docker/ldap-ai/data/lldap:/data/other-sites/lldap
|
||||
# 挂载整个数据目录(非单个文件),确保 SQLite WAL 文件共享
|
||||
- /var/lib/docker/volumes/assets-ai_assets-data/_data:/data/other-sites/assets
|
||||
- /var/lib/docker/volumes/issue-ai_issue-data/_data:/data/other-sites/issue
|
||||
- /root/docker/monitor-ai/data:/data/other-sites/monitor
|
||||
networks:
|
||||
- webnet
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
|
|
|
|||
|
|
@ -2,9 +2,6 @@ import type { NextConfig } from 'next'
|
|||
|
||||
const config: NextConfig = {
|
||||
output: 'standalone',
|
||||
outputFileTracingIncludes: {
|
||||
'/api/**': ['./node_modules/bcryptjs/**/*'],
|
||||
},
|
||||
}
|
||||
|
||||
export default config
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
13
package.json
13
package.json
|
|
@ -8,24 +8,15 @@
|
|||
"start": "next start"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"ldapts": "^6.0.0",
|
||||
"next": "^15.0.0",
|
||||
"openid-client": "^5.7.1",
|
||||
"resend": "^6.0.3",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"resend": "^6.0.3"
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.3.1",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"autoprefixer": "^10.5.2",
|
||||
"postcss": "^8.5.15",
|
||||
"tailwindcss": "^4.3.1",
|
||||
"typescript": "^5.0.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
const config = { plugins: { '@tailwindcss/postcss': {} } }
|
||||
export default config
|
||||
|
|
@ -33,10 +33,8 @@ export default function AdminUsersPage() {
|
|||
const [email, setEmail] = useState('')
|
||||
const [assetsRole, setAssetsRole] = useState('viewer')
|
||||
const [issueRole, setIssueRole] = useState('viewer')
|
||||
const [monitorRole, setMonitorRole] = useState('viewer')
|
||||
const [assetsRoles, setAssetsRoles] = useState<Role[]>([])
|
||||
const [issueRoles, setIssueRoles] = useState<Role[]>([])
|
||||
const [monitorRoles, setMonitorRoles] = useState<Role[]>([])
|
||||
const [users, setUsers] = useState<LdapUser[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [result, setResult] = useState<{ ok: boolean; msg: string } | null>(null)
|
||||
|
|
@ -59,7 +57,6 @@ export default function AdminUsersPage() {
|
|||
])
|
||||
if (rolesR.assets?.length) setAssetsRoles(rolesR.assets)
|
||||
if (rolesR.issue?.length) setIssueRoles(rolesR.issue)
|
||||
if (rolesR.monitor?.length) setMonitorRoles(rolesR.monitor)
|
||||
if (usersR.users?.length) setUsers(usersR.users)
|
||||
} catch {}
|
||||
}, [])
|
||||
|
|
@ -84,7 +81,7 @@ export default function AdminUsersPage() {
|
|||
e.preventDefault()
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await fetch('/api/admin/create-user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, displayName, assetsRole, issueRole, monitorRole, email: email || undefined }) })
|
||||
const res = await fetch('/api/admin/create-user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, displayName, assetsRole, issueRole, email: email || undefined }) })
|
||||
const d = await res.json()
|
||||
if (res.ok) {
|
||||
if (d.password) { setGeneratedPwd(d.password); setPwdUser(username); setPwdName(displayName || username); setShowPwd(true); setCopied(false) }
|
||||
|
|
@ -209,12 +206,6 @@ export default function AdminUsersPage() {
|
|||
{issueRoles.map(r => <option key={r.name} value={r.name}>{r.display_name}({r.name})</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<label style={s.label}>告警监控</label>
|
||||
<select value={monitorRole} onChange={e => setMonitorRole(e.target.value)} style={s.select}>
|
||||
{monitorRoles.map(r => <option key={r.name} value={r.name}>{r.display_name}({r.name})</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" disabled={loading} style={{ ...s.btn, background: loading ? '#93c5fd' : '#2563eb', cursor: loading ? 'not-allowed' : 'pointer' }}>
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import { useState, useEffect, useCallback } from 'react'
|
|||
|
||||
interface SiteUser { username: string; display_name: string; role: string }
|
||||
interface RoleData {
|
||||
assetsUsers: SiteUser[]; issueUsers: SiteUser[]; monitorUsers: SiteUser[]
|
||||
assetsRoles: string[]; issueRoles: string[]; monitorRoles: string[]
|
||||
assetsUsers: SiteUser[]; issueUsers: SiteUser[]
|
||||
assetsRoles: string[]; issueRoles: string[]
|
||||
emails: Record<string, string>
|
||||
}
|
||||
|
||||
|
|
@ -33,12 +33,11 @@ export default function RoleManager({ setResult, onUserUpdated }: Props) {
|
|||
const [editingDisplayName, setEditingDisplayName] = useState<string | null>(null)
|
||||
const [editDisplayNameValue, setEditDisplayNameValue] = useState('')
|
||||
const [savingDisplayName, setSavingDisplayName] = useState(false)
|
||||
const [syncing, setSyncing] = useState<string | null>(null) // username being synced, or 'all'
|
||||
|
||||
const fetchRoleData = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/admin/user-roles'); const d = await res.json()
|
||||
if (d.users) setRoleData({ assetsUsers: d.users.assets || [], issueUsers: d.users.issue || [], monitorUsers: d.users.monitor || [], assetsRoles: d.assetsRoles || [], issueRoles: d.issueRoles || [], monitorRoles: d.monitorRoles || [], emails: d.emails || {} })
|
||||
if (d.users) setRoleData({ assetsUsers: d.users.assets || [], issueUsers: d.users.issue || [], assetsRoles: d.assetsRoles || [], issueRoles: d.issueRoles || [], emails: d.emails || {} })
|
||||
} catch {}
|
||||
}, [])
|
||||
|
||||
|
|
@ -100,29 +99,11 @@ export default function RoleManager({ setResult, onUserUpdated }: Props) {
|
|||
setPending({}); if (fail === 0) fetchRoleData(); setSaving(false)
|
||||
}
|
||||
|
||||
async function syncUsers(usernames: string[], targetSite?: string) {
|
||||
setSyncing(usernames.length === 1 ? usernames[0] : 'all')
|
||||
try {
|
||||
const res = await fetch('/api/admin/sync-users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ usernames, targetSite }) })
|
||||
const d = await res.json()
|
||||
if (res.ok) {
|
||||
fetchRoleData()
|
||||
const failed = Object.entries(d.results || {}).flatMap(([site, users]: [string, any]) =>
|
||||
Object.entries(users).filter(([, ok]) => !ok).map(([u]) => `${u}→${site}`)
|
||||
)
|
||||
setResult(failed.length === 0, failed.length > 0 ? `${failed.join(', ')} 同步失败` : '同步完成')
|
||||
}
|
||||
else setResult(false, d.error || '同步失败')
|
||||
} catch { setResult(false, '网络错误') }
|
||||
finally { setSyncing(null) }
|
||||
}
|
||||
|
||||
if (!roleData) return <p style={{ fontSize: 13, color: 'var(--text-muted)', textAlign: 'center', padding: 40 }}>加载中...</p>
|
||||
|
||||
const userMap = new Map<string, { displayName: string; email: string; assetsRole: string; issueRole: string; monitorRole: string }>()
|
||||
roleData.assetsUsers.forEach(u => userMap.set(u.username, { displayName: u.display_name, email: roleData.emails[u.username] || '', assetsRole: u.role, issueRole: '—', monitorRole: '—' }))
|
||||
roleData.issueUsers.forEach(u => { const e = userMap.get(u.username); if (e) e.issueRole = u.role; else userMap.set(u.username, { displayName: u.display_name, email: roleData.emails[u.username] || '', assetsRole: '—', issueRole: u.role, monitorRole: '—' }) })
|
||||
roleData.monitorUsers.forEach(u => { const e = userMap.get(u.username); if (e) e.monitorRole = u.role; else userMap.set(u.username, { displayName: u.display_name, email: roleData.emails[u.username] || '', assetsRole: '—', issueRole: '—', monitorRole: u.role }) })
|
||||
const userMap = new Map<string, { displayName: string; email: string; assetsRole: string; issueRole: string }>()
|
||||
roleData.assetsUsers.forEach(u => userMap.set(u.username, { displayName: u.display_name, email: roleData.emails[u.username] || '', assetsRole: u.role, issueRole: '—' }))
|
||||
roleData.issueUsers.forEach(u => { const e = userMap.get(u.username); if (e) e.issueRole = u.role; else userMap.set(u.username, { displayName: u.display_name, email: roleData.emails[u.username] || '', assetsRole: '—', issueRole: u.role }) })
|
||||
const users = Array.from(userMap.entries())
|
||||
const changed = Object.keys(pending).length
|
||||
|
||||
|
|
@ -130,20 +111,15 @@ export default function RoleManager({ setResult, onUserUpdated }: Props) {
|
|||
<div>
|
||||
<div style={ss.bar}>
|
||||
<p style={ss.hint}>修改角色后点击「保存修改」统一提交{changed > 0 && <span style={{ color: '#d97706', fontWeight: 700, marginLeft: 10 }}>({changed} 项待保存)</span>}</p>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button onClick={() => syncUsers(users.map(([u]) => u))} disabled={syncing !== null} style={ss.saveBtn(false)}>
|
||||
{syncing === 'all' ? '同步中...' : '同步到所有站点'}
|
||||
</button>
|
||||
<button onClick={handleSave} disabled={changed === 0 || saving} style={ss.saveBtn(changed > 0)}>
|
||||
{saving ? '保存中...' : `保存修改${changed > 0 ? ` (${changed})` : ''}`}
|
||||
</button>
|
||||
</div>
|
||||
<button onClick={handleSave} disabled={changed === 0 || saving} style={ss.saveBtn(changed > 0)}>
|
||||
{saving ? '保存中...' : `保存修改${changed > 0 ? ` (${changed})` : ''}`}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ overflowX: 'auto' }}><table style={ss.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={ss.th}>用户名</th><th style={ss.th}>显示名</th><th style={ss.th}>邮箱</th><th style={ss.th}>资产管理</th><th style={ss.th}>工单跟踪</th><th style={ss.th}>告警监控</th>
|
||||
<th style={ss.th}>用户名</th><th style={ss.th}>显示名</th><th style={ss.th}>邮箱</th><th style={ss.th}>资产管理</th><th style={ss.th}>工单跟踪</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
|
@ -184,9 +160,8 @@ export default function RoleManager({ setResult, onUserUpdated }: Props) {
|
|||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td style={ss.td}><RoleCell site="assets" username={uname} originalRole={info.assetsRole} roles={roleData.assetsRoles} pending={pending} onSelect={handleSelect} getCurrentRole={getCurrentRole} syncing={syncing} onSync={syncUsers} /></td>
|
||||
<td style={ss.td}><RoleCell site="issue" username={uname} originalRole={info.issueRole} roles={roleData.issueRoles} pending={pending} onSelect={handleSelect} getCurrentRole={getCurrentRole} syncing={syncing} onSync={syncUsers} /></td>
|
||||
<td style={ss.td}><RoleCell site="monitor" username={uname} originalRole={info.monitorRole} roles={roleData.monitorRoles} pending={pending} onSelect={handleSelect} getCurrentRole={getCurrentRole} syncing={syncing} onSync={syncUsers} /></td>
|
||||
<td style={ss.td}><RoleCell site="assets" username={uname} originalRole={info.assetsRole} roles={roleData.assetsRoles} pending={pending} onSelect={handleSelect} getCurrentRole={getCurrentRole} /></td>
|
||||
<td style={ss.td}><RoleCell site="issue" username={uname} originalRole={info.issueRole} roles={roleData.issueRoles} pending={pending} onSelect={handleSelect} getCurrentRole={getCurrentRole} /></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
|
@ -195,27 +170,17 @@ export default function RoleManager({ setResult, onUserUpdated }: Props) {
|
|||
)
|
||||
}
|
||||
|
||||
function RoleCell({ site, username, originalRole, roles, pending, onSelect, getCurrentRole, syncing, onSync }: {
|
||||
function RoleCell({ site, username, originalRole, roles, pending, onSelect, getCurrentRole }: {
|
||||
site: string; username: string; originalRole: string; roles: string[]
|
||||
pending: Record<string, { site: string; newRole: string }>
|
||||
onSelect: (site: string, username: string, newRole: string, originalRole: string) => void
|
||||
getCurrentRole: (site: string, username: string, originalRole: string) => string
|
||||
syncing: string | null; onSync: (usernames: string[], site?: string) => void
|
||||
}) {
|
||||
const isReserved = username === 'admin' || username === 'localadmin'
|
||||
const changed = !!pending[`${site}:${username}`]
|
||||
const currentRole = getCurrentRole(site, username, originalRole)
|
||||
if (isReserved) return <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{currentRole}</span>
|
||||
if (originalRole === '—' && !changed) return (
|
||||
<span style={{ fontSize: 11 }}>
|
||||
<span style={{ color: 'var(--text-muted)' }}>未同步</span>
|
||||
{' '}
|
||||
<button onClick={() => onSync([username], site)} disabled={syncing === username}
|
||||
style={{ background: 'none', border: 'none', color: '#2563eb', fontSize: 11, cursor: syncing === username ? 'not-allowed' : 'pointer', padding: 0, textDecoration: 'underline', opacity: syncing === username ? 0.5 : 1 }}>
|
||||
{syncing === username ? '同步中...' : '同步'}
|
||||
</button>
|
||||
</span>
|
||||
)
|
||||
if (originalRole === '—' && !changed) return <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>未同步</span>
|
||||
return (
|
||||
<select value={currentRole} onChange={e => onSelect(site, username, e.target.value, originalRole)} style={ss.roleSelect(changed)}>
|
||||
{roles.map(r => <option key={r} value={r}>{r}</option>)}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { isLldapAdmin } from '@/lib/ldap'
|
||||
import { sendSetupLinkEmail } from '@/lib/email'
|
||||
import { signSetupToken } from '@/lib/setup-token'
|
||||
import { execLldap, lldapChangePassword, esc, getAdminPassword } from '@/lib/lldap-db'
|
||||
import bcrypt from 'bcryptjs'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
const INTERNAL_KEY = 'oa-internal-key-tlyq-2026'
|
||||
|
||||
|
|
@ -18,8 +19,10 @@ function generatePassword(): string {
|
|||
const all = upper + lower + digits + special
|
||||
const crypto = globalThis.crypto
|
||||
const pick = (s: string) => s[crypto.getRandomValues(new Uint32Array(1))[0] % s.length]
|
||||
// 确保每种类型至少一个,其余随机填充到 12 位
|
||||
let pwd = pick(upper) + pick(lower) + pick(digits) + pick(special)
|
||||
for (let i = 4; i < 12; i++) pwd += pick(all)
|
||||
// 打乱顺序
|
||||
return pwd.split('').sort(() => crypto.getRandomValues(new Uint32Array(1))[0] - 0x80000000).join('')
|
||||
}
|
||||
|
||||
|
|
@ -31,18 +34,28 @@ async function fetchRoles(siteUrl: string): Promise<string[]> {
|
|||
})
|
||||
const data = await res.json()
|
||||
return (data.roles || []).map((r: { name: string }) => r.name)
|
||||
} catch { return [] }
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function syncToSite(siteUrl: string, username: string, password: string): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${siteUrl}/api/auth/login`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
return res.ok
|
||||
} catch { return false }
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 直接更新站点 SQLite 数据库中的用户角色
|
||||
function setRoleSQL(dbPath: string, username: string, role: string): string {
|
||||
return `sqlite3 "${dbPath}" "UPDATE users SET role = '${role}', updated_at = datetime('now', '+8 hours') WHERE username = '${username}';"`
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
|
|
@ -55,68 +68,81 @@ export async function POST(request: Request) {
|
|||
return NextResponse.json({ error: '仅管理员可创建用户' }, { status: 403 })
|
||||
}
|
||||
|
||||
const { username, displayName, assetsRole, issueRole, monitorRole, email } = await request.json()
|
||||
const { username, displayName, assetsRole, issueRole, email } = await request.json()
|
||||
if (!username) return NextResponse.json({ error: '用户名不能为空' }, { status: 400 })
|
||||
if (!/^[a-z][a-z0-9_.@-]*$/i.test(username)) return NextResponse.json({ error: '用户名格式不合法' }, { status: 400 })
|
||||
|
||||
const password = generatePassword()
|
||||
const ASSETS_URL = process.env.ASSETS_INTERNAL_URL || 'http://localhost:6177'
|
||||
const ISSUE_URL = process.env.ISSUE_INTERNAL_URL || 'http://localhost:6176'
|
||||
const MONITOR_URL = process.env.MONITOR_INTERNAL_URL || 'http://localhost:6181'
|
||||
const [assetsRoles, issueRoles, monitorRoles] = await Promise.all([
|
||||
fetchRoles(ASSETS_URL), fetchRoles(ISSUE_URL), fetchRoles(MONITOR_URL),
|
||||
|
||||
// 从各站点实时获取可用角色列表
|
||||
const [assetsRoles, issueRoles] = await Promise.all([
|
||||
fetchRoles('http://localhost:6177'),
|
||||
fetchRoles('http://localhost:6176'),
|
||||
])
|
||||
|
||||
const ar = (assetsRole && assetsRoles.includes(assetsRole)) ? assetsRole : 'viewer'
|
||||
const ir = (issueRole && issueRoles.includes(issueRole)) ? issueRole : 'viewer'
|
||||
const mr = (monitorRole && monitorRoles.includes(monitorRole)) ? monitorRole : 'viewer'
|
||||
|
||||
const safeName = esc(displayName || username)
|
||||
const safeUser = esc(username)
|
||||
const safeName = (displayName || username).replace(/'/g, "'\\''")
|
||||
const safeUser = username.replace(/'/g, "'\\''")
|
||||
const lldapEmail = email || ''
|
||||
const d = new Date()
|
||||
const now = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`
|
||||
const userUuid = crypto.randomUUID()
|
||||
|
||||
// 1. docker exec lldap 插入用户(LLDAP DELETE 模式不可并发写)
|
||||
execLldap(`INSERT OR IGNORE INTO users (user_id, email, display_name, creation_date, uuid, lowercase_email, modified_date, password_modified_date) VALUES ('${safeUser}', '${esc(lldapEmail)}', '${safeName}', '${now}', '${userUuid}', LOWER('${esc(lldapEmail)}'), '${now}', '${now}')`)
|
||||
// 1. LLDAP SQLite 插入用户
|
||||
const insertSQL = `INSERT OR IGNORE INTO users (user_id, email, display_name, creation_date, uuid, lowercase_email, modified_date, password_modified_date) VALUES ('${username}', '${lldapEmail}', '${safeName}', '${now}', '${userUuid}', LOWER('${lldapEmail}'), '${now}', '${now}');`
|
||||
await execAsync(`docker exec lldap /bin/sh -c "cat > /tmp/iu.sql <<'EOSQL'\n${insertSQL}\nEOSQL\nsqlite3 /data/users.db < /tmp/iu.sql"`, { timeout: 5000 })
|
||||
|
||||
// 2. bcryptjs 直写 LLDAP 密码(替代 docker exec lldap_set_password)
|
||||
lldapChangePassword(username, password)
|
||||
// 2. 从 LLDAP 容器动态获取 admin 密码(不硬编码,admin 改密码后无需改 OA 配置)
|
||||
const { stdout: adminPassOut } = await execAsync('docker exec lldap printenv LLDAP_ADMIN_PASSWORD', { timeout: 3000 })
|
||||
const adminPass = (adminPassOut.trim() || 'admin123').replace(/'/g, "'\\''")
|
||||
|
||||
// 3. LLDAP 设置密码 —— 通过 base64 传输避免 shell 特殊字符问题
|
||||
const b64Pass = Buffer.from(password).toString('base64')
|
||||
await execAsync(`docker exec lldap /bin/sh -c "echo '${b64Pass}' | base64 -d > /tmp/userpwd.txt"`, { timeout: 3000 })
|
||||
const pwdCmd = `LLDAP_USER_PASSWORD=$(cat /tmp/userpwd.txt) ./lldap_set_password --base-url http://localhost:17170 --admin-username admin --admin-password '${adminPass}' --username '${safeUser}'`
|
||||
await execAsync(`docker exec lldap /bin/sh -c '${pwdCmd}'`, { timeout: 10000 })
|
||||
|
||||
// 3. 自动登录各站点触发用户同步
|
||||
const [assetsOk, issueOk, monitorOk] = await Promise.all([
|
||||
syncToSite(ASSETS_URL, username, password),
|
||||
syncToSite(ISSUE_URL, username, password),
|
||||
syncToSite(MONITOR_URL, username, password),
|
||||
const [assetsOk, issueOk] = await Promise.all([
|
||||
syncToSite('http://localhost:6177', username, password),
|
||||
syncToSite('http://localhost:6176', username, password),
|
||||
])
|
||||
|
||||
// 4. 直接更新各站点角色
|
||||
const assetsDb = process.env.ASSETS_DB_PATH || '/data/other-sites/assets/assets.db'
|
||||
const issueDb = process.env.ISSUE_DB_PATH || '/data/other-sites/issue/issue.db'
|
||||
const monitorDb = process.env.MONITOR_DB_PATH || '/data/other-sites/monitor/monitor.db'
|
||||
const roleResults = { assets: false, issue: false, monitor: false }
|
||||
if (assetsOk) try { execFileSync('sqlite3', [assetsDb], { input: `UPDATE users SET role = '${ar}', updated_at = datetime('now', '+8 hours') WHERE username = '${safeUser}';`, timeout: 3000 }); roleResults.assets = true } catch {}
|
||||
if (issueOk) try { execFileSync('sqlite3', [issueDb], { input: `UPDATE users SET role = '${ir}', updated_at = datetime('now', '+8 hours') WHERE username = '${safeUser}';`, timeout: 3000 }); roleResults.issue = true } catch {}
|
||||
if (monitorOk) try { execFileSync('sqlite3', [monitorDb], { input: `UPDATE users SET role = '${mr}', updated_at = datetime('now', '+8 hours') WHERE username = '${safeUser}';`, timeout: 3000 }); roleResults.monitor = true } catch {}
|
||||
// 4. 直接更新各站点 SQLite 的角色(覆盖 viewer 默认值)
|
||||
const assetsDb = process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db'
|
||||
const issueDb = process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db'
|
||||
const roleResults = { assets: false, issue: false }
|
||||
if (assetsOk) {
|
||||
try { await execAsync(setRoleSQL(assetsDb, username, ar), { timeout: 3000 }); roleResults.assets = true } catch {}
|
||||
}
|
||||
if (issueOk) {
|
||||
try { await execAsync(setRoleSQL(issueDb, username, ir), { timeout: 3000 }); roleResults.issue = true } catch {}
|
||||
}
|
||||
|
||||
// 5. 如果提供了邮箱,发送密码设置链接
|
||||
// 5. 如果提供了邮箱,发送密码设置链接(不再在邮件中发送明文密码)
|
||||
let emailSent = false
|
||||
if (email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
||||
try {
|
||||
const setupToken = signSetupToken(username)
|
||||
await sendSetupLinkEmail(email, username, `https://oa.tlyq.ai/setup-password?token=${setupToken}`, displayName || username)
|
||||
const setupUrl = `https://oa.tlyq.ai/setup-password?token=${setupToken}`
|
||||
await sendSetupLinkEmail(email, username, setupUrl, displayName || username)
|
||||
emailSent = true
|
||||
} catch (e) { console.error('发送邮件失败:', e) }
|
||||
} catch (e) {
|
||||
console.error('发送邮件失败:', e)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
password: emailSent ? undefined : password,
|
||||
synced: { assets: assetsOk, issue: issueOk, monitor: monitorOk },
|
||||
roles: { assets: ar, issue: ir, monitor: mr, applied: roleResults },
|
||||
synced: { assets: assetsOk, issue: issueOk },
|
||||
roles: { assets: ar, issue: ir, applied: roleResults },
|
||||
emailSent,
|
||||
message: emailSent ? `用户已创建,密码设置链接已发送至 ${email}` : '用户已创建并同步至所有站点',
|
||||
message: emailSent
|
||||
? `用户已创建,密码设置链接已发送至 ${email}`
|
||||
: '用户已创建并同步至所有站点',
|
||||
})
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '创建失败'
|
||||
|
|
|
|||
|
|
@ -5,24 +5,14 @@ import { isLldapAdmin } from '@/lib/ldap'
|
|||
|
||||
const INTERNAL_KEY = 'oa-internal-key-tlyq-2026'
|
||||
|
||||
// 角色中文显示名映射
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
admin: '管理员', editor: '编辑者', viewer: '观察者',
|
||||
}
|
||||
|
||||
interface RoleInfo { name: string; display_name: string }
|
||||
|
||||
async function fetchRoles(siteUrl: string): Promise<RoleInfo[]> {
|
||||
async function fetchRoles(url: string): Promise<{ name: string; display_name: string }[]> {
|
||||
try {
|
||||
const res = await fetch(`${siteUrl}/api/internal/roles`, {
|
||||
const res = await fetch(`${url}/api/internal/roles`, {
|
||||
headers: { 'x-internal-key': INTERNAL_KEY },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
const data = await res.json()
|
||||
return (data.roles || []).map((r: { name: string }) => ({
|
||||
name: r.name,
|
||||
display_name: ROLE_LABELS[r.name] || r.name,
|
||||
}))
|
||||
return data.roles || []
|
||||
} catch { return [] }
|
||||
}
|
||||
|
||||
|
|
@ -33,13 +23,10 @@ export async function GET() {
|
|||
const session = verifySharedJwt(token)
|
||||
if (!session || !(await isLldapAdmin(session.username))) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const A_URL = process.env.ASSETS_INTERNAL_URL || 'http://localhost:6177'
|
||||
const I_URL = process.env.ISSUE_INTERNAL_URL || 'http://localhost:6176'
|
||||
const M_URL = process.env.MONITOR_INTERNAL_URL || 'http://localhost:6181'
|
||||
|
||||
const [assets, issue, monitor] = await Promise.all([
|
||||
fetchRoles(A_URL), fetchRoles(I_URL), fetchRoles(M_URL),
|
||||
const [assetsRoles, issueRoles] = await Promise.all([
|
||||
fetchRoles('http://localhost:6177'),
|
||||
fetchRoles('http://localhost:6176'),
|
||||
])
|
||||
|
||||
return NextResponse.json({ assets, issue, monitor })
|
||||
return NextResponse.json({ assets: assetsRoles, issue: issueRoles })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { isLldapAdmin } from '@/lib/ldap'
|
||||
import { queryLldap, esc } from '@/lib/lldap-db'
|
||||
|
||||
const ASSETS_DB = process.env.ASSETS_DB_PATH || '/data/other-sites/assets/assets.db'
|
||||
const ISSUE_DB = process.env.ISSUE_DB_PATH || '/data/other-sites/issue/issue.db'
|
||||
const execAsync = promisify(exec)
|
||||
const ASSETS_DB = process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db'
|
||||
const ISSUE_DB = process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db'
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
|
|
@ -18,20 +19,23 @@ export async function POST() {
|
|||
return NextResponse.json({ error: '仅管理员可操作' }, { status: 403 })
|
||||
}
|
||||
|
||||
const out = queryLldap(`SELECT user_id, email FROM users WHERE email != ''`)
|
||||
const lines = out.split('\n').filter(Boolean)
|
||||
const { stdout } = await execAsync(
|
||||
`docker exec lldap sqlite3 /data/users.db "SELECT user_id, email FROM users WHERE email != '';"`,
|
||||
{ timeout: 5000 }
|
||||
)
|
||||
const lines = stdout.trim().split('\n').filter(Boolean)
|
||||
let synced = 0
|
||||
|
||||
for (const line of lines) {
|
||||
const [user, mail] = line.split('|')
|
||||
const su = esc(user)
|
||||
const sm = esc(mail || '')
|
||||
const su = user.replace(/'/g, "''")
|
||||
const sm = (mail || '').replace(/'/g, "''")
|
||||
for (const db of [ASSETS_DB, ISSUE_DB]) {
|
||||
try {
|
||||
execFileSync('sqlite3', [db], {
|
||||
input: `UPDATE users SET email = '${sm}', updated_at = datetime('now', '+8 hours') WHERE username = '${su}';`,
|
||||
timeout: 3000,
|
||||
})
|
||||
await execAsync(
|
||||
`sqlite3 "${db}" "UPDATE users SET email = '${sm}', updated_at = datetime('now', '+8 hours') WHERE username = '${su}';"`,
|
||||
{ timeout: 3000 }
|
||||
)
|
||||
} catch {}
|
||||
}
|
||||
synced++
|
||||
|
|
|
|||
|
|
@ -1,67 +0,0 @@
|
|||
// POST /api/admin/sync-users — 将用户同步到指定站点(docker exec 写 DB)
|
||||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { isLldapAdmin } from '@/lib/ldap'
|
||||
import { queryLldap, esc } from '@/lib/lldap-db'
|
||||
|
||||
const SITES: Record<string, [string, string]> = {
|
||||
assets: ['assets-ai', '/app/data/assets.db'],
|
||||
issue: ['issue-ai', '/app/data/issue.db'],
|
||||
monitor: ['monitor-ai', '/app/data/monitor.db'],
|
||||
}
|
||||
|
||||
function syncToSite(container: string, dbPath: string, username: string, displayName: string, email: string): boolean {
|
||||
try {
|
||||
const su = esc(username); const sd = esc(displayName); const se = esc(email)
|
||||
const d = new Date()
|
||||
const now = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`
|
||||
execFileSync('docker', ['exec', '-i', container, 'sqlite3', dbPath], {
|
||||
input: `INSERT OR IGNORE INTO users (username, display_name, email, role, is_active, created_at, updated_at) VALUES ('${su}', '${sd}', '${se}', 'viewer', 1, '${now}', '${now}');`,
|
||||
timeout: 5000,
|
||||
})
|
||||
return true
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const cookieStore = await cookies()
|
||||
const token = cookieStore.get('tlyq_session')?.value
|
||||
if (!token) return NextResponse.json({ error: '未登录' }, { status: 401 })
|
||||
const session = verifySharedJwt(token)
|
||||
if (!session || !(await isLldapAdmin(session.username))) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const { usernames, targetSite } = await request.json()
|
||||
if (!usernames || !Array.isArray(usernames) || usernames.length === 0) {
|
||||
return NextResponse.json({ error: '请指定要同步的用户' }, { status: 400 })
|
||||
}
|
||||
|
||||
// 从 LLDAP 获取用户信息
|
||||
const userInfo: Record<string, { displayName: string; email: string }> = {}
|
||||
try {
|
||||
const safeNames = usernames.map(u => `'${esc(u)}'`).join(',')
|
||||
const out = queryLldap(`SELECT user_id, display_name, email FROM users WHERE user_id IN (${safeNames})`)
|
||||
out.split('\n').filter(Boolean).forEach(line => {
|
||||
const [uid, dn, em] = line.split('|')
|
||||
userInfo[uid] = { displayName: dn || uid, email: em || '' }
|
||||
})
|
||||
} catch {}
|
||||
|
||||
const sites = targetSite && SITES[targetSite] ? { [targetSite]: SITES[targetSite] }
|
||||
: targetSite ? null : SITES
|
||||
if (!sites) return NextResponse.json({ error: '无效的站点' }, { status: 400 })
|
||||
|
||||
const results: Record<string, Record<string, boolean>> = {}
|
||||
for (const [site, [cName, cPath]] of Object.entries(sites)) {
|
||||
results[site] = {}
|
||||
for (const username of usernames) {
|
||||
const info = userInfo[username] || { displayName: username, email: '' }
|
||||
results[site][username] = syncToSite(cName, cPath, username, info.displayName, info.email)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, results })
|
||||
}
|
||||
|
|
@ -1,10 +1,11 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { isLldapAdmin } from '@/lib/ldap'
|
||||
import { queryLldap } from '@/lib/lldap-db'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
const INTERNAL_KEY = 'oa-internal-key-tlyq-2026'
|
||||
|
||||
async function fetchRoles(siteUrl: string): Promise<string[]> {
|
||||
|
|
@ -18,13 +19,13 @@ async function fetchRoles(siteUrl: string): Promise<string[]> {
|
|||
} catch { return [] }
|
||||
}
|
||||
|
||||
function queryDb(dbPath: string, sql: string): string {
|
||||
try { return execFileSync('sqlite3', [dbPath, sql], { timeout: 3000, encoding: 'utf8' }).trim() } catch { return '' }
|
||||
function queryDb(dbPath: string, sql: string): Promise<string> {
|
||||
return execAsync(`sqlite3 "${dbPath}" "${sql.replace(/"/g, '\\"')}"`, { timeout: 3000 }).then(r => r.stdout).catch(() => '')
|
||||
}
|
||||
|
||||
async function getSiteUsers(dbPath: string, roles: string[]): Promise<{ username: string; display_name: string; role: string }[]> {
|
||||
const out = queryDb(dbPath, 'SELECT username, display_name, role FROM users WHERE is_active=1 ORDER BY username;')
|
||||
return out.split('\n').filter(Boolean).map(line => {
|
||||
const out = await queryDb(dbPath, 'SELECT username, display_name, role FROM users WHERE is_active=1 ORDER BY username;')
|
||||
return out.trim().split('\n').filter(Boolean).map(line => {
|
||||
const [username, display_name, role] = line.split('|')
|
||||
return { username, display_name: display_name || username, role: roles.includes(role) ? role : 'viewer' }
|
||||
})
|
||||
|
|
@ -38,60 +39,41 @@ async function checkAdmin() {
|
|||
return session ? isLldapAdmin(session.username) : false
|
||||
}
|
||||
|
||||
const A_URL = process.env.ASSETS_INTERNAL_URL || 'http://localhost:6177'
|
||||
const I_URL = process.env.ISSUE_INTERNAL_URL || 'http://localhost:6176'
|
||||
const M_URL = process.env.MONITOR_INTERNAL_URL || 'http://localhost:6181'
|
||||
const A_DB = process.env.ASSETS_DB_PATH || '/data/other-sites/assets/assets.db'
|
||||
const I_DB = process.env.ISSUE_DB_PATH || '/data/other-sites/issue/issue.db'
|
||||
const M_DB = process.env.MONITOR_DB_PATH || '/data/other-sites/monitor/monitor.db'
|
||||
|
||||
function siteDb(site: string): string {
|
||||
if (site === 'assets') return A_DB
|
||||
if (site === 'issue') return I_DB
|
||||
return M_DB
|
||||
}
|
||||
function siteUrl(site: string): string {
|
||||
if (site === 'assets') return A_URL
|
||||
if (site === 'issue') return I_URL
|
||||
return M_URL
|
||||
}
|
||||
|
||||
// GET — 列出各站点用户及其角色
|
||||
export async function GET() {
|
||||
if (!(await checkAdmin())) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
try {
|
||||
const [assetsRoles, issueRoles, monitorRoles] = await Promise.all([
|
||||
fetchRoles(A_URL), fetchRoles(I_URL), fetchRoles(M_URL),
|
||||
const [assetsRoles, issueRoles] = await Promise.all([
|
||||
fetchRoles('http://localhost:6177'),
|
||||
fetchRoles('http://localhost:6176'),
|
||||
])
|
||||
|
||||
// monitor 走 API(DB 被 monitor 进程锁,不可直连),assets/issue 直连 SQLite
|
||||
const [assetsUsers, issueUsers] = await Promise.all([
|
||||
getSiteUsers(A_DB, assetsRoles),
|
||||
getSiteUsers(I_DB, issueRoles),
|
||||
getSiteUsers(process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db', assetsRoles),
|
||||
getSiteUsers(process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db', issueRoles),
|
||||
])
|
||||
let monitorUsers: { username: string; display_name: string; role: string }[] = []
|
||||
try {
|
||||
const mRes = await fetch(`${M_URL}/api/internal/users`, { headers: { 'x-internal-key': INTERNAL_KEY }, signal: AbortSignal.timeout(5000) })
|
||||
const mData = await mRes.json()
|
||||
monitorUsers = (mData.users || []).map((u: any) => ({ username: u.username, display_name: u.display_name || u.username, role: monitorRoles.includes(u.role) ? u.role : 'viewer' }))
|
||||
} catch { /* monitor 不可达时使用空列表 */ }
|
||||
|
||||
// 从 LLDAP 获取所有用户邮箱
|
||||
let emails: Record<string, string> = {}
|
||||
try {
|
||||
const out = queryLldap(`SELECT user_id, email FROM users`)
|
||||
out.split('\n').filter(Boolean).forEach(line => {
|
||||
const { stdout } = await execAsync(
|
||||
`docker exec lldap /bin/sh -c "echo 'SELECT user_id, email FROM users;' | sqlite3 /data/users.db"`,
|
||||
{ timeout: 3000 }
|
||||
)
|
||||
stdout.trim().split('\n').filter(Boolean).forEach(line => {
|
||||
const [uid, e] = line.split('|')
|
||||
emails[uid] = e || ''
|
||||
})
|
||||
} catch {}
|
||||
|
||||
return NextResponse.json({
|
||||
assetsRoles, issueRoles, monitorRoles,
|
||||
users: { assets: assetsUsers, issue: issueUsers, monitor: monitorUsers },
|
||||
assetsRoles,
|
||||
issueRoles,
|
||||
users: { assets: assetsUsers, issue: issueUsers },
|
||||
emails,
|
||||
})
|
||||
} catch {
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: '查询失败' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
@ -105,22 +87,18 @@ export async function PUT(request: Request) {
|
|||
if (!username || !site || !role) return NextResponse.json({ error: '参数不完整' }, { status: 400 })
|
||||
if (username === 'admin' || username === 'localadmin') return NextResponse.json({ error: '不能修改系统保留用户角色' }, { status: 400 })
|
||||
|
||||
const roles = await fetchRoles(siteUrl(site))
|
||||
const dbPath = site === 'assets'
|
||||
? (process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db')
|
||||
: (process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db')
|
||||
|
||||
// 验证角色合法性
|
||||
const roles = await fetchRoles(`http://localhost:${site === 'assets' ? 6177 : 6176}`)
|
||||
if (!roles.includes(role)) return NextResponse.json({ error: '无效的角色' }, { status: 400 })
|
||||
|
||||
// 统一通过 docker exec -i 写各站点 DB(直连 SQLite 在不同容器间始终 readonly)
|
||||
const containers: Record<string, [string, string]> = {
|
||||
assets: ['assets-ai', '/app/data/assets.db'],
|
||||
issue: ['issue-ai', '/app/data/issue.db'],
|
||||
monitor: ['monitor-ai', '/app/data/monitor.db'],
|
||||
}
|
||||
const [cName, cPath] = containers[site] || [null, null]
|
||||
if (!cName) return NextResponse.json({ error: '未知站点' }, { status: 400 })
|
||||
const sql = `UPDATE users SET role='${role}', updated_at=datetime('now', '+8 hours') WHERE username='${username}';`
|
||||
execFileSync('docker', ['exec', '-i', cName, 'sqlite3', cPath], { input: sql, timeout: 5000 })
|
||||
await execAsync(`sqlite3 "${dbPath}" "UPDATE users SET role='${role}', updated_at=datetime('now', '+8 hours') WHERE username='${username}';"`, { timeout: 3000 })
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch {
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: '更新失败' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { isLldapAdmin } from '@/lib/ldap'
|
||||
import { queryLldap, execLldap, esc } from '@/lib/lldap-db'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
function checkAdmin() {
|
||||
return async () => {
|
||||
|
|
@ -15,28 +17,22 @@ function checkAdmin() {
|
|||
}
|
||||
}
|
||||
|
||||
function siteSQL(dbPath: string, sql: string): void {
|
||||
try { execFileSync('sqlite3', [dbPath], { input: sql, timeout: 3000 }) } catch {}
|
||||
}
|
||||
|
||||
function nowStr(): string {
|
||||
const d = new Date()
|
||||
return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`
|
||||
}
|
||||
|
||||
// GET — 列出 LLDAP 中所有用户
|
||||
export async function GET() {
|
||||
const isAdmin = await checkAdmin()()
|
||||
if (!isAdmin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
try {
|
||||
const out = queryLldap(`SELECT user_id, email, display_name, creation_date FROM users ORDER BY creation_date DESC`)
|
||||
const users = out.split('\n').filter(Boolean).map(line => {
|
||||
const { stdout } = await execAsync(
|
||||
`docker exec lldap /bin/sh -c "echo 'SELECT user_id, email, display_name, creation_date FROM users ORDER BY creation_date DESC;' | sqlite3 /data/users.db"`,
|
||||
{ timeout: 5000 }
|
||||
)
|
||||
const users = stdout.trim().split('\n').filter(Boolean).map(line => {
|
||||
const [user_id, email, display_name, creation_date] = line.split('|')
|
||||
return { username: user_id, email, displayName: display_name || user_id, createdAt: creation_date }
|
||||
})
|
||||
return NextResponse.json({ users })
|
||||
} catch {
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: '查询失败' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
@ -53,24 +49,34 @@ export async function DELETE(request: Request) {
|
|||
return NextResponse.json({ error: '不能删除系统保留用户' }, { status: 400 })
|
||||
}
|
||||
|
||||
const safeUser = esc(username)
|
||||
execLldap(`DELETE FROM users WHERE user_id='${safeUser}'`)
|
||||
const safeUser = username.replace(/'/g, "''")
|
||||
|
||||
// 删除 LLDAP 用户
|
||||
const lldapSQL = `DELETE FROM users WHERE user_id='${safeUser}';`
|
||||
await execAsync(
|
||||
`docker exec lldap /bin/sh -c "cat > /tmp/del.sql <<'EOSQL'\n${lldapSQL}\nEOSQL\nsqlite3 /data/users.db < /tmp/del.sql"`,
|
||||
{ timeout: 5000 }
|
||||
)
|
||||
|
||||
// 删除各站点本地用户
|
||||
const results: Record<string, boolean> = {}
|
||||
for (const [site, dbPath] of Object.entries({
|
||||
assets: process.env.ASSETS_DB_PATH || '/data/other-sites/assets/assets.db',
|
||||
issue: process.env.ISSUE_DB_PATH || '/data/other-sites/issue/issue.db',
|
||||
assets: process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db',
|
||||
issue: process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db',
|
||||
})) {
|
||||
try { siteSQL(dbPath, `DELETE FROM users WHERE username='${safeUser}'`); results[site] = true } catch { results[site] = false }
|
||||
try {
|
||||
await execAsync(`sqlite3 "${dbPath}" "DELETE FROM users WHERE username='${safeUser}';"`, { timeout: 3000 })
|
||||
results[site] = true
|
||||
} catch { results[site] = false }
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, deleted: results })
|
||||
} catch {
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: '删除失败' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH — 修改用户信息
|
||||
// PATCH — 修改用户信息(admin 权限)
|
||||
export async function PATCH(request: Request) {
|
||||
const isAdmin = await checkAdmin()()
|
||||
if (!isAdmin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
|
@ -85,30 +91,42 @@ export async function PATCH(request: Request) {
|
|||
return NextResponse.json({ error: '邮箱格式不合法' }, { status: 400 })
|
||||
}
|
||||
|
||||
const safeUser = esc(username)
|
||||
let lldapSets: string[] = [], siteSets: string[] = []
|
||||
const safeUser = username.replace(/'/g, "''")
|
||||
const d = new Date()
|
||||
const now = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`
|
||||
|
||||
// 更新 LLDAP
|
||||
let lldapSets: string[] = []
|
||||
let siteSets: string[] = []
|
||||
if (email !== undefined) {
|
||||
const safeEmail = esc(email || '')
|
||||
const safeEmail = (email || '').replace(/'/g, "''")
|
||||
lldapSets.push(`email = '${safeEmail}'`, `lowercase_email = LOWER('${safeEmail}')`)
|
||||
siteSets.push(`email = '${safeEmail}'`)
|
||||
}
|
||||
if (displayName !== undefined) {
|
||||
const safeName = esc(displayName)
|
||||
const safeName = displayName.replace(/'/g, "''")
|
||||
lldapSets.push(`display_name = '${safeName}'`)
|
||||
siteSets.push(`display_name = '${safeName}'`)
|
||||
}
|
||||
lldapSets.push(`modified_date = '${nowStr()}'`)
|
||||
lldapSets.push(`modified_date = '${now}'`)
|
||||
siteSets.push(`updated_at = datetime('now', '+8 hours')`)
|
||||
|
||||
execLldap(`UPDATE users SET ${lldapSets.join(', ')} WHERE user_id = '${safeUser}'`)
|
||||
const lldapSQL = `UPDATE users SET ${lldapSets.join(', ')} WHERE user_id = '${safeUser}';`
|
||||
await execAsync(
|
||||
`docker exec lldap /bin/sh -c "cat > /tmp/up.sql <<'EOSQL'\n${lldapSQL}\nEOSQL\nsqlite3 /data/users.db < /tmp/up.sql"`,
|
||||
{ timeout: 5000 }
|
||||
)
|
||||
|
||||
const siteSql = `UPDATE users SET ${siteSets.join(', ')} WHERE username = '${safeUser}'`
|
||||
for (const dbPath of [process.env.ASSETS_DB_PATH || '/data/other-sites/assets/assets.db', process.env.ISSUE_DB_PATH || '/data/other-sites/issue/issue.db']) {
|
||||
siteSQL(dbPath, siteSql)
|
||||
// 同步更新 assets / issue
|
||||
const assetsDb = process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db'
|
||||
const issueDb = process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db'
|
||||
const siteSQL = `UPDATE users SET ${siteSets.join(', ')} WHERE username = '${safeUser}';`
|
||||
for (const dbPath of [assetsDb, issueDb]) {
|
||||
try { await execAsync(`sqlite3 "${dbPath}" "${siteSQL}"`, { timeout: 3000 }) } catch {}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, username, email, displayName })
|
||||
} catch {
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: '修改失败' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,35 +0,0 @@
|
|||
// GET /api/auth/callback — OIDC callback(V2:OA 签发 tlyq_session)
|
||||
import { NextRequest } from 'next/server'
|
||||
import { handleOidcCallback } from '@shared/lib/auth/handle-callback'
|
||||
import { ldapUserExists } from '@/lib/ldap'
|
||||
import { syncUserToAllSites } from '@/lib/sync-user'
|
||||
|
||||
const autheliaUrl = process.env.AUTHELIA_URL || 'https://sso.tlyq.ai'
|
||||
const oidcClientId = process.env.OIDC_CLIENT_ID || 'oa-oidc'
|
||||
const oidcClientSecret = process.env.OIDC_CLIENT_SECRET || ''
|
||||
const oidcRedirectUri = process.env.OIDC_REDIRECT_URI || 'https://oa.tlyq.ai/api/auth/callback'
|
||||
const jwtSecret = process.env.JWT_SECRET || 'oa-shared-jwt-secret-tlyq-2026'
|
||||
const cookieDomain = process.env.COOKIE_DOMAIN || '.tlyq.ai'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const response = await handleOidcCallback(request, {
|
||||
oidc: { autheliaUrl, clientId: oidcClientId, clientSecret: oidcClientSecret, redirectUri: oidcRedirectUri },
|
||||
jwtSecret,
|
||||
cookieDomain,
|
||||
|
||||
// 强制验证 LLDAP 存在性(违反 §2.3 的旧行为已修正)
|
||||
getUser: async (username) => {
|
||||
const exists = await ldapUserExists(username)
|
||||
if (exists) {
|
||||
// 跨站点角色同步(fire-and-forget,不阻塞 callback 响应)
|
||||
syncUserToAllSites(username, username, 'admin').catch(() => {})
|
||||
return { id: -1, role: 'admin' }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
// OA 不通过 OIDC 创建/更新用户
|
||||
})
|
||||
|
||||
return response
|
||||
}
|
||||
|
|
@ -1,7 +1,10 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { lldapChangePassword, getAdminPassword } from '@/lib/lldap-db'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
|
|
@ -19,6 +22,7 @@ export async function POST(request: Request) {
|
|||
if (newPassword.length < 8) {
|
||||
return NextResponse.json({ error: '新密码至少 8 位' }, { status: 400 })
|
||||
}
|
||||
// 密码复杂度:大写/小写/数字/特殊字符 4选3
|
||||
const hasUpper = /[A-Z]/.test(newPassword)
|
||||
const hasLower = /[a-z]/.test(newPassword)
|
||||
const hasDigit = /[0-9]/.test(newPassword)
|
||||
|
|
@ -28,12 +32,25 @@ export async function POST(request: Request) {
|
|||
return NextResponse.json({ error: '密码需包含大写字母、小写字母、数字、特殊字符中至少 3 种' }, { status: 400 })
|
||||
}
|
||||
|
||||
// 通过 bcryptjs + 直连 LLDAP SQLite 修改密码(不再 docker exec)
|
||||
lldapChangePassword(session.username, newPassword)
|
||||
// 从 LLDAP 容器动态获取 admin 密码(不硬编码,admin 改密码后无需改 OA 配置)
|
||||
const { stdout: adminPassOut } = await execAsync('docker exec lldap printenv LLDAP_ADMIN_PASSWORD', { timeout: 3000 })
|
||||
const adminPass = (adminPassOut.trim() || 'admin123').replace(/'/g, "'\\''")
|
||||
|
||||
const safeUser = session.username.replace(/'/g, "'\\''")
|
||||
const safePass = newPassword.replace(/'/g, "'\\''")
|
||||
const cmd = `docker exec lldap ./lldap_set_password --base-url http://localhost:17170 --admin-username admin --admin-password '${adminPass}' --username '${safeUser}' --password '${safePass}'`
|
||||
|
||||
const { stdout, stderr } = await execAsync(cmd, { timeout: 10000 })
|
||||
if (stderr && !stderr.includes('Successfully')) {
|
||||
return NextResponse.json({ error: stderr.trim() || '修改失败' }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : '修改失败'
|
||||
if (msg.includes('command not found') || msg.includes('No such container')) {
|
||||
return NextResponse.json({ error: '密码服务不可用' }, { status: 503 })
|
||||
}
|
||||
return NextResponse.json({ error: msg }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
// GET /api/auth/login/oidc — OIDC SSO 重定向(V2:使用 shared handleOidcLogin 工厂)
|
||||
import { handleOidcLogin } from '@shared/lib/auth/handle-login'
|
||||
|
||||
const autheliaUrl = process.env.AUTHELIA_URL || 'https://sso.tlyq.ai'
|
||||
const oidcClientId = process.env.OIDC_CLIENT_ID || 'oa-oidc'
|
||||
const oidcClientSecret = process.env.OIDC_CLIENT_SECRET || ''
|
||||
const oidcRedirectUri = process.env.OIDC_REDIRECT_URI || 'https://oa.tlyq.ai/api/auth/callback'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
const switchUser = url.searchParams.get('switch') === '1'
|
||||
return handleOidcLogin({ autheliaUrl, clientId: oidcClientId, clientSecret: oidcClientSecret, redirectUri: oidcRedirectUri, switchUser })
|
||||
}
|
||||
|
|
@ -1,9 +1,7 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { signSharedJwt, sharedCookieConfig } from '@/lib/jwt'
|
||||
import { ldapAuth, isLldapAdmin } from '@/lib/ldap'
|
||||
import { writeAuditLog } from '@/lib/audit'
|
||||
import { syncUserToAllSites } from '@/lib/sync-user'
|
||||
import { ldapAuth } from '@/lib/ldap'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
|
|
@ -25,20 +23,6 @@ export async function POST(request: Request) {
|
|||
const cookieStore = await cookies()
|
||||
cookieStore.set(cfg.name, token, cfg)
|
||||
|
||||
// 审计日志
|
||||
try {
|
||||
writeAuditLog({
|
||||
username: result.username!,
|
||||
action: 'login',
|
||||
details: { method: 'ldap', displayName: result.displayName },
|
||||
ipAddress: request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown',
|
||||
})
|
||||
} catch { /* 审计日志失败不影响登录 */ }
|
||||
|
||||
// 跨站点角色同步(不阻塞响应)
|
||||
const role = (await isLldapAdmin(result.username!)) ? 'admin' : 'viewer'
|
||||
syncUserToAllSites(result.username!, result.displayName!, role).catch(() => {})
|
||||
|
||||
return NextResponse.json({
|
||||
user: { username: result.username, displayName: result.displayName },
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,25 +1,8 @@
|
|||
// GET + POST /api/auth/logout — 退出登录(清除 cookie + 302 跳转 /login)
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
|
||||
const cookieDomain = process.env.COOKIE_DOMAIN || '.tlyq.ai'
|
||||
|
||||
/** 从 OIDC_REDIRECT_URI 提取 site URL(不可信请求头,见 LESSONS-LEARNED #51) */
|
||||
function getSiteUrl(): string {
|
||||
const redirectUri = process.env.OIDC_REDIRECT_URI || ''
|
||||
try { const u = new URL(redirectUri); return `${u.protocol}//${u.host}` } catch { /* fallthrough */ }
|
||||
return process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:6179'
|
||||
export async function POST() {
|
||||
const cookieStore = await cookies()
|
||||
cookieStore.set('tlyq_session', '', { maxAge: 0, path: '/' })
|
||||
return NextResponse.redirect(new URL('/login', process.env.NEXT_PUBLIC_URL || 'http://localhost:6179'))
|
||||
}
|
||||
|
||||
/** 清除 tlyq_session + session cookie → 302 跳转 /login */
|
||||
function logoutResponse(): NextResponse {
|
||||
const response = NextResponse.redirect(new URL('/login', getSiteUrl()))
|
||||
response.cookies.set('tlyq_session', '', {
|
||||
httpOnly: true, secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax', domain: cookieDomain, path: '/', maxAge: 0,
|
||||
})
|
||||
response.cookies.set('session', '', { path: '/', maxAge: 0 })
|
||||
return response
|
||||
}
|
||||
|
||||
export async function GET() { return logoutResponse() }
|
||||
export async function POST() { return logoutResponse() }
|
||||
|
|
|
|||
|
|
@ -1,15 +1,20 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySharedJwt } from '@/lib/jwt'
|
||||
import { isLldapAdmin } from '@/lib/ldap'
|
||||
import { queryLldap, execLldap, esc } from '@/lib/lldap-db'
|
||||
import { execFileSync } from 'child_process'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
async function getLldapInfo(username: string): Promise<{ email: string; displayName: string }> {
|
||||
try {
|
||||
const safe = esc(username)
|
||||
const out = queryLldap(`SELECT email, display_name FROM users WHERE user_id = '${safe}'`)
|
||||
const parts = out.split('|')
|
||||
const safeUser = username.replace(/'/g, "''")
|
||||
const { stdout } = await execAsync(
|
||||
`docker exec lldap /bin/sh -c "echo 'SELECT email, display_name FROM users WHERE user_id='\\''${safeUser}'\\'';' | sqlite3 /data/users.db"`,
|
||||
{ timeout: 3000 }
|
||||
)
|
||||
const parts = stdout.trim().split('|')
|
||||
return { email: parts[0] || '', displayName: parts[1] || username }
|
||||
} catch { return { email: '', displayName: username } }
|
||||
}
|
||||
|
|
@ -50,23 +55,23 @@ export async function PUT(request: Request) {
|
|||
return NextResponse.json({ error: '邮箱格式不合法' }, { status: 400 })
|
||||
}
|
||||
|
||||
const safeUser = esc(payload.username)
|
||||
const safeEmail = esc(email || '')
|
||||
const safeUser = payload.username.replace(/'/g, "''")
|
||||
const safeEmail = (email || '').replace(/'/g, "''")
|
||||
const d = new Date()
|
||||
const now = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`
|
||||
|
||||
// docker exec lldap 更新邮箱(LLDAP DELETE 模式不可并发写)
|
||||
execLldap(`UPDATE users SET email = '${safeEmail}', lowercase_email = LOWER('${safeEmail}'), modified_date = '${now}' WHERE user_id = '${safeUser}'`)
|
||||
const updateSQL = `UPDATE users SET email = '${safeEmail}', lowercase_email = LOWER('${safeEmail}'), modified_date = '${now}' WHERE user_id = '${safeUser}';`
|
||||
await execAsync(
|
||||
`docker exec lldap /bin/sh -c "cat > /tmp/ue.sql <<'EOSQL'\n${updateSQL}\nEOSQL\nsqlite3 /data/users.db < /tmp/ue.sql"`,
|
||||
{ timeout: 5000 }
|
||||
)
|
||||
|
||||
// 同步更新 assets / issue 本地用户表
|
||||
const assetsDb = process.env.ASSETS_DB_PATH || '/data/other-sites/assets/assets.db'
|
||||
const issueDb = process.env.ISSUE_DB_PATH || '/data/other-sites/issue/issue.db'
|
||||
const assetsDb = process.env.ASSETS_DB_PATH || '/Users/niuniu/programs/docker/assets-ai/data/assets.db'
|
||||
const issueDb = process.env.ISSUE_DB_PATH || '/Users/niuniu/programs/docker/issue-ai/data/issue.db'
|
||||
for (const dbPath of [assetsDb, issueDb]) {
|
||||
try {
|
||||
execFileSync('sqlite3', [dbPath], {
|
||||
input: `UPDATE users SET email = '${safeEmail}', updated_at = datetime('now', '+8 hours') WHERE username = '${safeUser}';`,
|
||||
timeout: 3000,
|
||||
})
|
||||
await execAsync(`sqlite3 "${dbPath}" "UPDATE users SET email = '${safeEmail}', updated_at = datetime('now', '+8 hours') WHERE username = '${safeUser}';"`, { timeout: 3000 })
|
||||
} catch {}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { verifySetupToken } from '@/lib/setup-token'
|
||||
import { lldapChangePassword } from '@/lib/lldap-db'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
|
|
@ -26,12 +29,26 @@ export async function POST(request: Request) {
|
|||
return NextResponse.json({ error: '密码需包含大写字母、小写字母、数字、特殊字符中至少 3 种' }, { status: 400 })
|
||||
}
|
||||
|
||||
// 通过 bcryptjs + 直连 LLDAP SQLite 修改密码(不再 docker exec)
|
||||
lldapChangePassword(payload.username, password)
|
||||
const { stdout: adminPassOut } = await execAsync(
|
||||
'docker exec lldap printenv LLDAP_ADMIN_PASSWORD', { timeout: 3000 }
|
||||
)
|
||||
const adminPass = (adminPassOut.trim() || 'admin123').replace(/'/g, "'\\''")
|
||||
|
||||
const safeUser = payload.username.replace(/'/g, "'\\''")
|
||||
const safePass = password.replace(/'/g, "'\\''")
|
||||
const cmd = `docker exec lldap ./lldap_set_password --base-url http://localhost:17170 --admin-username admin --admin-password '${adminPass}' --username '${safeUser}' --password '${safePass}'`
|
||||
|
||||
const { stderr } = await execAsync(cmd, { timeout: 10000 })
|
||||
if (stderr && !stderr.includes('Successfully')) {
|
||||
return NextResponse.json({ error: stderr.trim() || '设置失败' }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : '设置失败'
|
||||
if (msg.includes('command not found') || msg.includes('No such container')) {
|
||||
return NextResponse.json({ error: '密码服务不可用' }, { status: 503 })
|
||||
}
|
||||
return NextResponse.json({ error: msg }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({ status: 'OK' })
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
@import "tailwindcss";
|
||||
@config "../../tailwind.config.js";
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--bg: #f8fafc; --bg-card: #fff; --bg-hover: #f1f5f9; --border: #e2e8f0;
|
||||
--text: #0f172a; --text-secondary: #475569; --text-muted: #94a3b8;
|
||||
}
|
||||
.dark {
|
||||
--bg: #020617; --bg-card: #0f172a; --bg-hover: #1e293b; --border: #1e293b;
|
||||
--text: #f1f5f9; --text-secondary: #94a3b8; --text-muted: #64748b;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,3 @@
|
|||
import './globals.css'
|
||||
|
||||
export const metadata = { title: 'OA 统一门户' }
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
|
|
@ -15,8 +13,24 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|||
} catch(e) {}
|
||||
})();
|
||||
`}} />
|
||||
<style>{`
|
||||
:root {
|
||||
--bg: #f8fafc; --bg-card: #fff; --bg-hover: #f1f5f9; --border: #e2e8f0;
|
||||
--text: #0f172a; --text-secondary: #475569; --text-muted: #94a3b8;
|
||||
}
|
||||
.dark {
|
||||
--bg: #020617; --bg-card: #0f172a; --bg-hover: #1e293b; --border: #1e293b;
|
||||
--text: #f1f5f9; --text-secondary: #94a3b8; --text-muted: #64748b;
|
||||
}
|
||||
`}</style>
|
||||
</head>
|
||||
<body>
|
||||
<body style={{
|
||||
margin: 0,
|
||||
background: 'var(--bg)',
|
||||
color: 'var(--text)',
|
||||
fontFamily: 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
|
||||
transition: 'background 0.3s, color 0.3s',
|
||||
}}>
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -1,101 +1,82 @@
|
|||
'use client'
|
||||
|
||||
import { useState, Suspense } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { useState } from 'react'
|
||||
|
||||
function LoginPageContent() {
|
||||
export default function LoginPage() {
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [showLdapForm, setShowLdapForm] = useState(false)
|
||||
const searchParams = useSearchParams()
|
||||
const isLocalMode = searchParams.get('method') === 'local'
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault(); setError(''); setLoading(true)
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { setError(data.error || '登录失败'); return }
|
||||
window.location.href = '/'
|
||||
} catch { setError('网络错误') } finally { setLoading(false) }
|
||||
}
|
||||
|
||||
function handleSsoLogin() {
|
||||
fetch('/api/auth/login/oidc').then(res => {
|
||||
if (res.status === 200) {
|
||||
return res.json().then(data => {
|
||||
if (data.conflict) { window.location.href = '/' }
|
||||
else { setError(data.error || '登录失败') }
|
||||
})
|
||||
if (!res.ok) {
|
||||
const d = await res.json()
|
||||
setError(d.error || '登录失败')
|
||||
return
|
||||
}
|
||||
window.location.href = res.url || '/api/auth/login/oidc'
|
||||
}).catch(() => { window.location.href = '/api/auth/login/oidc' })
|
||||
window.location.href = '/'
|
||||
} catch {
|
||||
setError('网络错误')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const showLocalForm = isLocalMode || showLdapForm
|
||||
const inputStyle: React.CSSProperties = {
|
||||
width: '100%', height: 42, padding: '0 12px',
|
||||
background: 'var(--bg-card)', border: '1px solid var(--border)', borderRadius: 8,
|
||||
fontSize: 14, outline: 'none', boxSizing: 'border-box', color: 'var(--text)',
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950 px-4">
|
||||
<div className="w-full max-w-sm bg-white dark:bg-slate-900 rounded-lg border border-blue-200/50 dark:border-blue-500/20 shadow-lg p-8">
|
||||
<h1 className="text-2xl font-bold text-center mb-6 text-slate-900 dark:text-white">统一门户</h1>
|
||||
{error && <div className="mb-4 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 text-sm">{error}</div>}
|
||||
|
||||
{!showLocalForm ? (
|
||||
<>
|
||||
<button onClick={handleSsoLogin} className="w-full py-2 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium transition-colors duration-200 mb-3">
|
||||
统一认证登录
|
||||
</button>
|
||||
<p className="text-center text-xs text-slate-400 mb-3">通过 SSO 统一身份认证</p>
|
||||
<p className="text-center mb-2">
|
||||
<button onClick={() => { window.location.href = '/api/auth/login/oidc?switch=1' }} className="text-xs text-slate-400 hover:text-slate-600 underline">
|
||||
使用其他账号登录
|
||||
</button>
|
||||
</p>
|
||||
<p className="text-center">
|
||||
<button onClick={() => setShowLdapForm(true)} className="text-xs text-slate-400 hover:text-slate-600 underline">
|
||||
使用 LDAP 直接登录
|
||||
</button>
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">用户名</label>
|
||||
<input type="text" value={username} onChange={e => setUsername(e.target.value)} placeholder="请输入用户名"
|
||||
className="w-full px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">密码</label>
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="请输入密码"
|
||||
className="w-full px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" required />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 px-4 rounded-lg bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium transition-colors duration-200">{loading ? '登录中...' : '登录'}</button>
|
||||
</form>
|
||||
{!isLocalMode && (
|
||||
<p className="text-center mt-3">
|
||||
<button onClick={() => setShowLdapForm(false)} className="text-xs text-slate-400 hover:text-slate-600 underline">
|
||||
返回统一认证登录
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg)' }}>
|
||||
<div style={{
|
||||
width: 400, background: 'var(--bg-card)', border: '1px solid var(--border)', borderRadius: 12,
|
||||
padding: '40px 36px', boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04)',
|
||||
}}>
|
||||
<div style={{ textAlign: 'center', marginBottom: 32 }}>
|
||||
<div style={{ width: 44, height: 44, margin: '0 auto 14px', background: '#2563eb', borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, color: '#fff' }}>◎</div>
|
||||
<h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--text)', margin: 0 }}>统一门户</h1>
|
||||
<p style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>TLYQ.IDENTITY</p>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-secondary)', marginBottom: 6 }}>账号</div>
|
||||
<input type="text" placeholder="LDAP 用户名" value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
onFocus={e => { e.target.style.borderColor = 'transparent'; e.target.style.boxShadow = '0 0 0 2px #2563eb' }}
|
||||
onBlur={e => { e.target.style.borderColor = 'var(--border)'; e.target.style.boxShadow = 'none' }}
|
||||
style={inputStyle} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-secondary)', marginBottom: 6 }}>密码</div>
|
||||
<input type="password" placeholder="输入密码" value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
onFocus={e => { e.target.style.borderColor = 'transparent'; e.target.style.boxShadow = '0 0 0 2px #2563eb' }}
|
||||
onBlur={e => { e.target.style.borderColor = 'var(--border)'; e.target.style.boxShadow = 'none' }}
|
||||
style={inputStyle} />
|
||||
</div>
|
||||
{error && <p style={{ color: '#dc2626', fontSize: 13, marginBottom: 12, padding: '8px 12px', background: '#fef2f2', borderRadius: 8 }}>{error}</p>}
|
||||
<button type="submit" disabled={loading} style={{
|
||||
width: '100%', height: 44, background: loading ? '#60a5fa' : '#2563eb',
|
||||
color: '#fff', border: 'none', borderRadius: 8, fontSize: 15, fontWeight: 500, cursor: loading ? 'not-allowed' : 'pointer',
|
||||
}}>
|
||||
{loading ? '验证中...' : '登 录'}
|
||||
</button>
|
||||
<p style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: 'var(--text-muted)' }}>
|
||||
通过 <span style={{ color: '#2563eb', fontWeight: 500 }}>LLDAP</span> 统一身份认证
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="min-h-screen flex items-center justify-center">加载中...</div>}>
|
||||
<LoginPageContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,22 +11,20 @@ function siteUrl(url: string, domain: string): string {
|
|||
}
|
||||
|
||||
const CORE_SITES = [
|
||||
{ name: '资产管理', url: 'http://127.0.0.1:6177', desc: 'GPU 服务器、存储服务器等硬件设备信息管理与实时监控', tag: 'CMDB', dot: '#2563eb', domain: 'assets.tlyq.ai' },
|
||||
{ name: '工单跟踪', url: 'http://127.0.0.1:6176', desc: '故障工单全流程管理,SLA 自动计算,月度/周度报告导出', tag: 'ITS', dot: '#7c3aed', domain: 'issue.tlyq.ai' },
|
||||
{ name: '告警监控', url: 'http://127.0.0.1:6181', desc: '统一告警监控中心,容器/端点健康检查,企业微信告警推送', tag: 'MONITOR', dot: '#4f46e5', domain: 'monitor.tlyq.ai' },
|
||||
{ name: '资产管理', url: 'http://localhost:6177', desc: 'GPU 服务器、存储服务器等硬件设备信息管理与实时监控', tag: 'CMDB', dot: '#2563eb', domain: 'assets.tlyq.ai' },
|
||||
{ name: '工单跟踪', url: 'http://localhost:6176', desc: '故障工单全流程管理,SLA 自动计算,月度/周度报告导出', tag: 'ITS', dot: '#7c3aed', domain: 'issue.tlyq.ai' },
|
||||
]
|
||||
|
||||
const OTHER_SITES = [
|
||||
{ name: '官网', url: 'http://127.0.0.1:6173', desc: 'tlyq.ai 企业官方网站', tag: 'WWW', dot: '#059669', domain: 'www.tlyq.ai' },
|
||||
{ name: '云平台', url: 'http://127.0.0.1:6174', desc: '云服务登录入口与资源概览', tag: 'CLOUD', dot: '#d97706', domain: 'cloud.tlyq.ai' },
|
||||
{ name: 'Token 工厂', url: 'http://127.0.0.1:6175', desc: 'Token 管理与发放平台', tag: 'TOKEN', dot: '#e11d48', domain: 'token.tlyq.ai' },
|
||||
{ name: '官网', url: 'http://localhost:6173', desc: 'tlyq.ai 企业官方网站', tag: 'WWW', dot: '#059669', domain: 'www.tlyq.ai' },
|
||||
{ name: '云平台', url: 'http://localhost:6174', desc: '云服务登录入口与资源概览', tag: 'CLOUD', dot: '#d97706', domain: 'cloud.tlyq.ai' },
|
||||
{ name: 'Token 工厂', url: 'http://localhost:6175', desc: 'Token 管理与发放平台', tag: 'TOKEN', dot: '#e11d48', domain: 'token.tlyq.ai' },
|
||||
{ name: '代码仓库', url: 'https://git.tlyq.ai', desc: 'Gitea 代码托管与版本管理', tag: 'GIT', dot: '#db2777', domain: 'git.tlyq.ai' },
|
||||
]
|
||||
|
||||
const COLORS: Record<string, { light: string; tag: string }> = {
|
||||
'#2563eb': { light: 'rgba(37,99,235,0.08)', tag: '#2563eb' },
|
||||
'#7c3aed': { light: 'rgba(124,58,237,0.08)', tag: '#7c3aed' },
|
||||
'#4f46e5': { light: 'rgba(79,70,229,0.08)', tag: '#4f46e5' },
|
||||
'#059669': { light: 'rgba(5,150,105,0.08)', tag: '#059669' },
|
||||
'#d97706': { light: 'rgba(217,119,6,0.08)', tag: '#d97706' },
|
||||
'#e11d48': { light: 'rgba(225,29,72,0.08)', tag: '#e11d48' },
|
||||
|
|
|
|||
|
|
@ -1,77 +1,37 @@
|
|||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
|
||||
type Theme = 'light' | 'dark' | 'auto'
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
export default function ThemeToggle() {
|
||||
const [theme, setTheme] = useState<Theme>('auto')
|
||||
const [open, setOpen] = useState(false)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const [dark, setDark] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem('theme') as Theme | null
|
||||
setTheme(stored || 'auto')
|
||||
applyTheme(stored || 'auto')
|
||||
setDark(document.documentElement.classList.contains('dark'))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) }
|
||||
document.addEventListener('mousedown', handler)
|
||||
return () => document.removeEventListener('mousedown', handler)
|
||||
}, [])
|
||||
|
||||
function applyTheme(t: Theme) {
|
||||
const root = document.documentElement
|
||||
root.classList.remove('light', 'dark')
|
||||
if (t === 'auto') {
|
||||
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
root.classList.add(prefersDark ? 'dark' : 'light')
|
||||
} else {
|
||||
root.classList.add(t)
|
||||
}
|
||||
function toggle() {
|
||||
const next = !dark
|
||||
setDark(next)
|
||||
document.documentElement.classList.toggle('dark', next)
|
||||
localStorage.setItem('theme', next ? 'dark' : 'light')
|
||||
}
|
||||
|
||||
function select(t: Theme) {
|
||||
setTheme(t)
|
||||
localStorage.setItem('theme', t)
|
||||
applyTheme(t)
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const icons: Record<Theme, string> = { light: '☀', dark: '☾', auto: '◐' }
|
||||
const labels: Record<Theme, string> = { light: '浅色', dark: '深色', auto: '自动' }
|
||||
|
||||
return (
|
||||
<div ref={ref} style={{ position: 'relative' }}>
|
||||
<button onClick={() => setOpen(!open)} title="切换主题" style={{
|
||||
width: 36, height: 36, borderRadius: 8, border: 'none',
|
||||
background: open ? 'var(--bg-hover)' : 'transparent', color: 'var(--text-secondary)', cursor: 'pointer',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: 18, transition: 'background 0.15s',
|
||||
}}>
|
||||
{icons[theme]}
|
||||
<>
|
||||
<button
|
||||
onClick={toggle}
|
||||
className="theme-toggle-btn"
|
||||
title={dark ? '切换到亮色模式' : '切换到暗色模式'}
|
||||
style={{
|
||||
width: 36, height: 36, borderRadius: 8, border: 'none',
|
||||
background: 'transparent', color: 'var(--text-secondary)', cursor: 'pointer',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: 18, transition: 'background 0.15s',
|
||||
}}
|
||||
>
|
||||
{dark ? '☀' : '☾'}
|
||||
</button>
|
||||
{open && (
|
||||
<div style={{
|
||||
position: 'absolute', top: '100%', right: 0, marginTop: 4,
|
||||
background: 'var(--bg-card)', border: '1px solid var(--border)',
|
||||
borderRadius: 8, padding: '4px 0', minWidth: 100, zIndex: 100,
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||||
}}>
|
||||
{(['light', 'dark', 'auto'] as Theme[]).map(t => (
|
||||
<button key={t} onClick={() => select(t)} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8, width: '100%',
|
||||
padding: '6px 12px', border: 'none', background: t === theme ? 'var(--bg-hover)' : 'transparent',
|
||||
color: 'var(--text)', cursor: 'pointer', fontSize: 13, textAlign: 'left',
|
||||
}}>
|
||||
<span>{icons[t]}</span>
|
||||
<span>{labels[t]}</span>
|
||||
{t === theme && <span style={{ marginLeft: 'auto', color: '#2563eb' }}>✓</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<style>{`.theme-toggle-btn:hover { background: var(--bg-hover) !important; }`}</style>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
// oa-ai/src/lib/audit.ts — 审计日志写入
|
||||
import db from '@/lib/db'
|
||||
|
||||
export function writeAuditLog(params: {
|
||||
username: string
|
||||
action: string
|
||||
details?: Record<string, unknown>
|
||||
ipAddress: string
|
||||
}) {
|
||||
db.prepare(
|
||||
`INSERT INTO audit_logs (username, action, details, ip_address)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
).run(
|
||||
params.username, params.action,
|
||||
JSON.stringify(params.details || {}), params.ipAddress
|
||||
)
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
// oa-ai/src/lib/db.ts — 仅为审计日志创建的 SQLite 数据库
|
||||
import Database from 'better-sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
|
||||
const dbPath = process.env.DATABASE_PATH || './data/oa.db'
|
||||
const dbDir = path.dirname(dbPath)
|
||||
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true })
|
||||
|
||||
const db = new Database(dbPath)
|
||||
db.pragma('journal_mode = WAL')
|
||||
|
||||
// 初始化 audit_logs 表
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT,
|
||||
action TEXT,
|
||||
details TEXT,
|
||||
ip_address TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now', '+8 hours'))
|
||||
)`)
|
||||
|
||||
export default db
|
||||
|
|
@ -1,8 +1,6 @@
|
|||
// oa-ai/src/lib/jwt.ts — V2:使用 signJwtV2(含 iss: 'oa.tlyq.ai'),旧函数保留兼容
|
||||
import { signJwt, verifyJwt } from '@shared/lib/auth/jwt'
|
||||
import { signJwtV2 } from '@shared/lib/auth/jwt-v2'
|
||||
import crypto from 'crypto'
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'default-secret-change-me'
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'change-me-same-across-all-sites'
|
||||
const COOKIE_DOMAIN = process.env.COOKIE_DOMAIN || ''
|
||||
|
||||
export interface SharedSession {
|
||||
|
|
@ -12,34 +10,51 @@ export interface SharedSession {
|
|||
exp: number
|
||||
}
|
||||
|
||||
// 保持原有签名:signSharedJwt(payload, expiresIn) → 内部改用 signJwtV2
|
||||
function base64url(str: string): string {
|
||||
return Buffer.from(str).toString('base64url')
|
||||
}
|
||||
|
||||
export function signSharedJwt(
|
||||
payload: { username: string; displayName: string },
|
||||
expiresIn: number = 7 * 24 * 60 * 60
|
||||
): string {
|
||||
return signJwtV2({ secret: JWT_SECRET, payload, iss: 'oa.tlyq.ai', expiresInSeconds: expiresIn })
|
||||
const header = { alg: 'HS256', typ: 'JWT' }
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const body = { ...payload, iat: now, exp: now + expiresIn }
|
||||
const segments = [base64url(JSON.stringify(header)), base64url(JSON.stringify(body))]
|
||||
const signingInput = segments.join('.')
|
||||
segments.push(
|
||||
crypto.createHmac('sha256', JWT_SECRET).update(signingInput).digest('base64url')
|
||||
)
|
||||
return segments.join('.')
|
||||
}
|
||||
|
||||
// 保持原有签名:verifySharedJwt(token) — 兼容旧 token(无 iss)和新 token(有 iss)
|
||||
export function verifySharedJwt(token: string): SharedSession | null {
|
||||
const payload = verifyJwt(token, JWT_SECRET)
|
||||
if (!payload) return null
|
||||
return {
|
||||
username: payload.username as string,
|
||||
displayName: (payload.displayName || payload.username) as string,
|
||||
iat: payload.iat as number,
|
||||
exp: payload.exp as number,
|
||||
}
|
||||
try {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) return null
|
||||
const signingInput = parts.slice(0, 2).join('.')
|
||||
const expectedSig = crypto.createHmac('sha256', JWT_SECRET)
|
||||
.update(signingInput).digest('base64url')
|
||||
if (parts[2] !== expectedSig) return null
|
||||
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString())
|
||||
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) return null
|
||||
return {
|
||||
username: payload.username,
|
||||
displayName: payload.displayName,
|
||||
iat: payload.iat,
|
||||
exp: payload.exp,
|
||||
}
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
// 保持原有签名:sharedCookieConfig(maxAge)
|
||||
export function sharedCookieConfig(maxAge: number = 7 * 24 * 60 * 60) {
|
||||
return {
|
||||
name: 'tlyq_session',
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax' as const,
|
||||
domain: COOKIE_DOMAIN || undefined,
|
||||
domain: COOKIE_DOMAIN,
|
||||
path: '/',
|
||||
maxAge,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,45 +1,25 @@
|
|||
import { Client, InvalidCredentialsError } from 'ldapts'
|
||||
import { execFileSync } from 'child_process'
|
||||
|
||||
const LDAP_URL = process.env.LDAP_URL || 'ldap://localhost:3890'
|
||||
const LDAP_BASE_DN = process.env.LDAP_BASE_DN || 'dc=tlyq,dc=ai'
|
||||
|
||||
// 从环境变量获取 LLDAP admin 密码(优先使用环境变量,fallback 到 docker exec)
|
||||
// 运行时从 LLDAP 容器动态获取 admin 密码
|
||||
function getLdapAdminPassword(): string {
|
||||
if (process.env.LLDAP_ADMIN_PASSWORD) {
|
||||
return process.env.LLDAP_ADMIN_PASSWORD
|
||||
}
|
||||
try {
|
||||
const { execFileSync } = require('child_process') as typeof import('child_process')
|
||||
return execFileSync('docker', ['exec', 'lldap', 'printenv', 'LLDAP_ADMIN_PASSWORD'],
|
||||
{ timeout: 3000 }).toString().trim()
|
||||
} catch {
|
||||
throw new Error('无法获取 LLDAP admin 密码:请设置 LLDAP_ADMIN_PASSWORD 环境变量或确保 Docker socket 可用')
|
||||
}
|
||||
}
|
||||
|
||||
// 验证用户是否存在于 LLDAP 中(用于 OIDC callback 验证)
|
||||
export async function ldapUserExists(username: string): Promise<boolean> {
|
||||
const adminDn = `uid=admin,ou=people,${LDAP_BASE_DN}`
|
||||
const client = new Client({ url: LDAP_URL, timeout: 5000 })
|
||||
try {
|
||||
const adminPass = getLdapAdminPassword()
|
||||
await client.bind(adminDn, adminPass)
|
||||
const { searchEntries } = await client.search(LDAP_BASE_DN, {
|
||||
scope: 'sub', filter: `(uid=${username})`, timeLimit: 3,
|
||||
})
|
||||
return searchEntries.length > 0
|
||||
} catch { return false }
|
||||
finally { try { await client.unbind() } catch { /* */ } }
|
||||
} catch { return 'admin123' }
|
||||
}
|
||||
|
||||
// 检查用户是否属于 lldap_admin 组(用于管理员权限判断)
|
||||
export async function isLldapAdmin(username: string): Promise<boolean> {
|
||||
if (username === 'admin') return true // 默认 admin 永远是管理员
|
||||
const adminDn = `uid=admin,ou=people,${LDAP_BASE_DN}`
|
||||
const adminPass = getLdapAdminPassword()
|
||||
const client = new Client({ url: LDAP_URL, timeout: 5000 })
|
||||
|
||||
try {
|
||||
const adminPass = getLdapAdminPassword()
|
||||
await client.bind(adminDn, adminPass)
|
||||
const userDn = `uid=${username},ou=people,${LDAP_BASE_DN}`
|
||||
const { searchEntries } = await client.search(`ou=groups,${LDAP_BASE_DN}`, {
|
||||
|
|
@ -51,7 +31,7 @@ export async function isLldapAdmin(username: string): Promise<boolean> {
|
|||
} catch {
|
||||
return false // LLDAP 不可达 → 保守拒绝,非 admin 不放行
|
||||
} finally {
|
||||
try { await client.unbind() } catch { /* */ }
|
||||
await client.unbind()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,37 +0,0 @@
|
|||
// lib/lldap-db.ts — LLDAP 操作(读直连 SQLite / 写走 docker exec stdin)
|
||||
// LLDAP 使用 DELETE journal mode,不可并发写 → 写操作必须通过 docker exec 在 LLDAP 容器内执行
|
||||
// SQL 通过 stdin 传入 sqlite3,不经过 shell 解析 → 无命令注入风险
|
||||
import { execFileSync } from 'child_process'
|
||||
import bcrypt from 'bcryptjs'
|
||||
|
||||
const LLDAP_DB = process.env.LLDAP_DB_PATH || '/data/other-sites/lldap/users.db'
|
||||
|
||||
/** 直连 LLDAP SQLite 只读查询 */
|
||||
export function queryLldap(sql: string): string {
|
||||
return execFileSync('sqlite3', [LLDAP_DB, sql], { timeout: 5000, encoding: 'utf8' }).trim()
|
||||
}
|
||||
|
||||
/** docker exec -i lldap sqlite3,通过 stdin 传入 SQL(无 shell 解析,无命令注入风险) */
|
||||
export function execLldap(sql: string, timeout = 5000): string {
|
||||
return execFileSync('docker', ['exec', '-i', 'lldap', 'sqlite3', '/data/users.db'], {
|
||||
input: sql, timeout, encoding: 'utf8',
|
||||
}).trim()
|
||||
}
|
||||
|
||||
/** 安全的 SQL 字符串转义(SQLite 标准:'' → 单引号) */
|
||||
export function esc(val: string): string {
|
||||
return val.replace(/'/g, "''")
|
||||
}
|
||||
|
||||
/** 修改 LLDAP 用户密码 */
|
||||
export function lldapChangePassword(username: string, newPassword: string): void {
|
||||
const hash = bcrypt.hashSync(newPassword, 12)
|
||||
const safeUser = esc(username)
|
||||
const now = new Date().toISOString().replace('T', ' ').slice(0, 19)
|
||||
execLldap(`UPDATE users SET password_hash = '${hash}', password_modified_date = '${now}', modified_date = '${now}' WHERE user_id = '${safeUser}';`)
|
||||
}
|
||||
|
||||
/** 获取 admin 密码 */
|
||||
export function getAdminPassword(): string {
|
||||
return process.env.LLDAP_ADMIN_PASSWORD || 'admin123'
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
import { Issuer } from 'openid-client'
|
||||
import crypto from 'crypto'
|
||||
|
||||
const AUTHELIA_URL = process.env.AUTHELIA_URL || 'https://sso.tlyq.ai'
|
||||
const OIDC_CLIENT_ID = process.env.OIDC_CLIENT_ID || 'oa-oidc'
|
||||
const OIDC_CLIENT_SECRET = process.env.OIDC_CLIENT_SECRET || ''
|
||||
const OIDC_REDIRECT_URI = process.env.OIDC_REDIRECT_URI || 'https://oa.tlyq.ai/api/auth/callback'
|
||||
|
||||
let oidcClient: any = null
|
||||
let lastDiscovery = 0
|
||||
const DISCOVERY_TTL = 3600000 // 1 小时
|
||||
|
||||
export async function getOidcClient() {
|
||||
const now = Date.now()
|
||||
if (oidcClient && (now - lastDiscovery) < DISCOVERY_TTL) {
|
||||
return oidcClient
|
||||
}
|
||||
|
||||
try {
|
||||
const issuer = await Issuer.discover(AUTHELIA_URL)
|
||||
oidcClient = new issuer.Client({
|
||||
client_id: OIDC_CLIENT_ID,
|
||||
client_secret: OIDC_CLIENT_SECRET,
|
||||
redirect_uris: [OIDC_REDIRECT_URI],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: 'client_secret_basic',
|
||||
})
|
||||
lastDiscovery = now
|
||||
return oidcClient
|
||||
} catch (error) {
|
||||
console.error('OIDC discovery 失败:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function generatePKCE() {
|
||||
const codeVerifier = crypto.randomBytes(32).toString('base64url')
|
||||
const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url')
|
||||
return { codeVerifier, codeChallenge }
|
||||
}
|
||||
|
||||
export function generateState() {
|
||||
return crypto.randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
||||
export function generateNonce() {
|
||||
return crypto.randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
// oa-ai/src/lib/sync-user.ts — 跨站点用户角色同步
|
||||
const SYNC_TARGETS = [
|
||||
{ key: 'MONITOR_INTERNAL_URL', name: 'monitor-ai' },
|
||||
{ key: 'ASSETS_INTERNAL_URL', name: 'assets-ai' },
|
||||
{ key: 'ISSUE_INTERNAL_URL', name: 'issue-ai' },
|
||||
]
|
||||
|
||||
export async function syncUserToAllSites(
|
||||
username: string,
|
||||
displayName: string,
|
||||
role: string
|
||||
): Promise<void> {
|
||||
const internalKey = process.env.INTERNAL_API_KEY
|
||||
if (!internalKey) {
|
||||
console.warn('同步跳过:INTERNAL_API_KEY 未配置')
|
||||
return
|
||||
}
|
||||
|
||||
await Promise.allSettled(SYNC_TARGETS.map(({ key, name }) => {
|
||||
const baseUrl = process.env[key]
|
||||
if (!baseUrl) {
|
||||
console.warn(`同步跳过 ${name}:${key} 未配置`)
|
||||
return Promise.resolve()
|
||||
}
|
||||
return fetch(`${baseUrl}/api/internal/users`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-internal-key': internalKey || '',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ username, displayName, role }),
|
||||
}).catch(e => console.error(`同步失败 ${name}:`, e))
|
||||
}))
|
||||
}
|
||||
|
|
@ -1,14 +1,62 @@
|
|||
// src/middleware.ts — V2 单 cookie 模型,Edge 验签 + iss 校验
|
||||
import { createMiddlewareV2 } from '@shared/lib/auth/middleware-v2'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
|
||||
const jwtSecret = process.env.JWT_SECRET || 'oa-shared-jwt-secret-tlyq-2026'
|
||||
const cookieDomain = process.env.COOKIE_DOMAIN || '.tlyq.ai'
|
||||
function decodeJwtPayload(token: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) return null
|
||||
let payload = parts[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
while (payload.length % 4) payload += '='
|
||||
return JSON.parse(atob(payload))
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
export const middleware = createMiddlewareV2({
|
||||
jwtSecret,
|
||||
cookieDomain,
|
||||
allowedIssuers: ['*'], // 迁移模式
|
||||
publicPaths: ['/login', '/api/auth', '/api/health', '/api/admin', '/setup-password', '/_next', '/favicon.ico'],
|
||||
})
|
||||
function isValidPayload(payload: Record<string, unknown> | null): boolean {
|
||||
if (!payload) return false
|
||||
return !(payload.exp && (payload.exp as number) < Math.floor(Date.now() / 1000))
|
||||
}
|
||||
|
||||
function noCache(response: NextResponse) {
|
||||
response.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate')
|
||||
return response
|
||||
}
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl
|
||||
|
||||
// 登录/设置密码/API 路径放行(API 路由自行验证)
|
||||
if (pathname === '/login' || pathname === '/setup-password' || pathname.startsWith('/api/auth/') || pathname.startsWith('/api/admin/')) {
|
||||
return NextResponse.next()
|
||||
}
|
||||
// /admin 管理页面需要认证
|
||||
if (pathname.startsWith('/admin')) {
|
||||
const token = request.cookies.get('tlyq_session')?.value
|
||||
const payload = token ? decodeJwtPayload(token) : null
|
||||
if (!isValidPayload(payload)) {
|
||||
return NextResponse.redirect(new URL('/login', request.url))
|
||||
}
|
||||
return noCache(NextResponse.next())
|
||||
}
|
||||
|
||||
// 静态资源放行(已有路径哈希,允许缓存)
|
||||
if (pathname.startsWith('/_next/') || pathname === '/favicon.ico') {
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
const token = request.cookies.get('tlyq_session')?.value
|
||||
const payload = token ? decodeJwtPayload(token) : null
|
||||
|
||||
if (isValidPayload(payload)) {
|
||||
const response = NextResponse.next()
|
||||
response.cookies.set('session', JSON.stringify({ username: payload!.username }), {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
})
|
||||
return noCache(response)
|
||||
}
|
||||
|
||||
return noCache(NextResponse.redirect(new URL('/login', request.url)))
|
||||
}
|
||||
|
||||
export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico|public).*)'] }
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
darkMode: 'class',
|
||||
content: ['./src/**/*.{js,ts,jsx,tsx,mdx}'],
|
||||
theme: { extend: {} },
|
||||
plugins: [],
|
||||
}
|
||||
|
|
@ -22,13 +22,9 @@
|
|||
"name": "next"
|
||||
}
|
||||
],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
],
|
||||
"@shared/*": [
|
||||
"./shared/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in New Issue