Merge pull request #833 from Windfarer/oidc
feat: Authentication with OIDC
This commit is contained in:
@@ -309,3 +309,26 @@ DOCREADER_TRANSPORT=grpc
|
||||
|
||||
# Weaviate 数据库名称(可选)
|
||||
#WEAVIATE_COLLECTION=your_weaviate_db_name
|
||||
|
||||
# ----- OIDC Auth -----
|
||||
# 如果需要启用OIDC登录,设为true并填写后续字段
|
||||
# OIDC_AUTH_ENABLE=false
|
||||
|
||||
# (Optional) 用于OIDC自动发现端点配置
|
||||
# OIDC_AUTH_ISSUER_URL=http://127.0.0.1:5556/dex
|
||||
# OIDC_AUTH_DISCOVERY_URL=http://127.0.0.1:5556/dex/.well-known/openid-configuration
|
||||
|
||||
# OIDC_AUTH_PROVIDER_DISPLAY_NAME=OIDC
|
||||
# OIDC_AUTH_CLIENT_ID=client_id_for_oidc_client
|
||||
# OIDC_AUTH_CLIENT_SECRET=secret_for_oidc_client
|
||||
|
||||
# (Optional) OIDC 端点配置, 如果上面的OIDC_AUTH_DISCOVERY_URL填过了,下面的这些可以留空
|
||||
# OIDC_AUTH_AUTHORIZATION_ENDPOINT=http://127.0.0.1:5556/dex/auth
|
||||
# OIDC_AUTH_TOKEN_ENDPOINT=http://127.0.0.1:5556/dex/token
|
||||
# OIDC_AUTH_USER_INFO_ENDPOINT=http://127.0.0.1:5556/dex/userinfo
|
||||
|
||||
# OIDC_AUTH_SCOPES="openid profile email"
|
||||
|
||||
# 用于OIDC用于信息中提取用户数据
|
||||
# OIDC_USER_INFO_MAPPING_USER_NAME=name
|
||||
# OIDC_USER_INFO_MAPPING_EMAIL=email
|
||||
@@ -186,6 +186,19 @@ services:
|
||||
- jaeger
|
||||
- full
|
||||
|
||||
dex:
|
||||
image: dexidp/dex:latest
|
||||
container_name: WeKnora-dex-dev
|
||||
ports:
|
||||
- "5556:5556"
|
||||
volumes:
|
||||
- ./misc/dex-config.yaml:/etc/dex/config.yaml
|
||||
command: ["dex", "serve", "/etc/dex/config.yaml"]
|
||||
profiles:
|
||||
- dex
|
||||
- full
|
||||
|
||||
|
||||
networks:
|
||||
WeKnora-network-dev:
|
||||
driver: bridge
|
||||
|
||||
@@ -340,6 +340,18 @@ services:
|
||||
profiles:
|
||||
- weaviate
|
||||
|
||||
dex:
|
||||
image: dexidp/dex:latest
|
||||
container_name: dex
|
||||
ports:
|
||||
- "5556:5556"
|
||||
volumes:
|
||||
- ./misc/dex-config.yaml:/etc/dex/config.yaml
|
||||
command: ["dex", "serve", "/etc/dex/config.yaml"]
|
||||
profiles:
|
||||
- dex
|
||||
- full
|
||||
|
||||
networks:
|
||||
WeKnora-network:
|
||||
driver: bridge
|
||||
|
||||
@@ -0,0 +1,642 @@
|
||||
# WeKnora OIDC 认证调用流程
|
||||
|
||||
本文档说明 WeKnora 当前 OIDC 登录能力的实际调用过程,覆盖:
|
||||
|
||||
- 前端如何判断是否展示 OIDC 登录入口
|
||||
- 用户点击 OIDC 登录后的前后端调用链路
|
||||
- 后端如何与 OIDC Provider 交互
|
||||
- 登录成功后前端如何接收结果并落盘本地登录态
|
||||
- 关键配置项与本地联调方式
|
||||
|
||||
本文内容基于当前项目实现,相关代码主要位于:
|
||||
|
||||
- 后端路由:`internal/router/router.go`
|
||||
- 认证处理:`internal/handler/auth.go`
|
||||
- 认证服务:`internal/application/service/user.go`
|
||||
- 配置定义:`internal/config/config.go`
|
||||
- 前端登录页:`frontend/src/views/auth/Login.vue`
|
||||
- 前端全局回调处理:`frontend/src/App.vue`
|
||||
- 前端认证 API:`frontend/src/api/auth/index.ts`
|
||||
- 本地 Dex 示例:`misc/dex-config.yaml`
|
||||
|
||||
---
|
||||
|
||||
## 1. 整体设计说明
|
||||
|
||||
本项目的 OIDC 登录采用的是 **后端发起授权参数生成、后端接收回调并完成 code 换 token、前端通过 URL hash 接收最终登录结果** 的模式。
|
||||
|
||||
和常见的纯前端 OIDC SDK 不同,WeKnora 的特点是:
|
||||
|
||||
1. **前端只负责发起跳转**,不直接和 OIDC Provider 交换 token。
|
||||
2. **后端负责用授权码 `code` 向 OIDC Provider 换取 token**。
|
||||
3. 后端拿到 OIDC 用户信息后,会:
|
||||
- 查找本地用户;
|
||||
- 若用户不存在,则自动创建本地账号和默认租户;
|
||||
- 最终签发 WeKnora 自己的本地 JWT(`token` / `refresh_token`)。
|
||||
4. 后端不会直接把登录结果放在 query string 中,而是:
|
||||
- 将结果 JSON 序列化后再做 base64url 编码;
|
||||
- 以 `#oidc_result=...` 的形式重定向回前端;
|
||||
- 前端在 `App.vue` 中统一解析 hash,完成登录态持久化。
|
||||
|
||||
因此,**OIDC Provider 的 token 只用于后端换取用户身份,本项目真正的业务访问凭证仍然是 WeKnora 自己签发的 JWT**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 相关接口
|
||||
|
||||
当前 OIDC 相关接口均注册在 `internal/router/router.go` 中:
|
||||
|
||||
- `GET /api/v1/auth/oidc/config`
|
||||
- 获取 OIDC 是否启用,以及 Provider 展示名称
|
||||
- `GET /api/v1/auth/oidc/url`
|
||||
- 生成第三方登录跳转地址
|
||||
- `GET /api/v1/auth/oidc/callback`
|
||||
- OIDC Provider 回调地址
|
||||
|
||||
其中,前端常规登录仍然使用:
|
||||
|
||||
- `POST /api/v1/auth/login`
|
||||
- `POST /api/v1/auth/refresh`
|
||||
- `POST /api/v1/auth/logout`
|
||||
- `GET /api/v1/auth/me`
|
||||
|
||||
---
|
||||
|
||||
## 3. 调用流程图
|
||||
|
||||
### 3.1 总体时序图
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant U as 用户浏览器
|
||||
participant FE as 前端(Login/App)
|
||||
participant BE as WeKnora 后端
|
||||
participant OP as OIDC Provider
|
||||
|
||||
FE->>BE: GET /api/v1/auth/oidc/config
|
||||
BE-->>FE: { enabled, provider_display_name }
|
||||
|
||||
U->>FE: 点击“OIDC 登录”
|
||||
FE->>BE: GET /api/v1/auth/oidc/url?redirect_uri=...
|
||||
BE-->>FE: { success, authorization_url, state }
|
||||
FE->>OP: 浏览器跳转到 authorization_url
|
||||
|
||||
OP-->>BE: GET /api/v1/auth/oidc/callback?code=...&state=...
|
||||
BE->>OP: POST token endpoint (code 换 token)
|
||||
OP-->>BE: access_token / id_token
|
||||
BE->>OP: GET userinfo endpoint(可选)
|
||||
OP-->>BE: 用户信息 claims
|
||||
|
||||
BE->>BE: 查找/自动创建本地用户
|
||||
BE->>BE: 签发本地 token、refresh_token
|
||||
BE-->>FE: 302 到 /#oidc_result=...
|
||||
|
||||
FE->>FE: App.vue 解析 hash
|
||||
FE->>FE: 写入 authStore/token/tenant
|
||||
FE-->>U: 跳转 /platform/knowledge-bases
|
||||
```
|
||||
|
||||
### 3.2 后端回调处理分支图
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[OIDC Provider 回调到 /api/v1/auth/oidc/callback] --> B{query 中是否有 error}
|
||||
B -- 是 --> C[拼接 #oidc_error 和 error_description]
|
||||
C --> D[302 重定向到前端登录页]
|
||||
|
||||
B -- 否 --> E[解析 state]
|
||||
E --> F{state 是否合法且包含 redirect_uri}
|
||||
F -- 否 --> G[302 到前端并带 #oidc_error=invalid_state]
|
||||
|
||||
F -- 是 --> H{是否有 code}
|
||||
H -- 否 --> I[302 到前端并带 #oidc_error=missing_code]
|
||||
|
||||
H -- 是 --> J[调用 LoginWithOIDC,传入 code 和 redirect_uri]
|
||||
J --> K[向 OIDC token endpoint 换 token]
|
||||
K --> L[解析 id_token / 调用 userinfo]
|
||||
L --> M{本地用户是否存在}
|
||||
M -- 否 --> N[自动注册新用户并创建默认租户]
|
||||
M -- 是 --> O[使用现有用户]
|
||||
N --> P[签发 WeKnora JWT]
|
||||
O --> P
|
||||
P --> Q[编码为 oidc_result]
|
||||
Q --> R[302 重定向到前端首页 hash]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 前端调用流程
|
||||
|
||||
## 4.1 登录页初始化:决定是否展示 OIDC 登录按钮
|
||||
|
||||
登录页组件位于 `frontend/src/views/auth/Login.vue`。
|
||||
|
||||
页面加载时会执行:
|
||||
|
||||
```ts
|
||||
loadOIDCConfig()
|
||||
```
|
||||
|
||||
该函数调用:
|
||||
|
||||
```ts
|
||||
getOIDCConfig() -> GET /api/v1/auth/oidc/config
|
||||
```
|
||||
|
||||
后端 `GetOIDCConfig` 会读取 `configInfo.OIDCAuth`:
|
||||
|
||||
- `enabled`: 是否启用 OIDC
|
||||
- `provider_display_name`: 登录按钮上展示的供应商名称
|
||||
|
||||
前端据此决定:
|
||||
|
||||
- 是否显示 OIDC 登录按钮;
|
||||
- 按钮文案是否显示为“使用 XXX 登录”。
|
||||
|
||||
---
|
||||
|
||||
## 4.2 用户点击 OIDC 登录按钮
|
||||
|
||||
用户点击按钮后,`Login.vue` 中会执行 `handleOIDCLogin()`。
|
||||
|
||||
核心逻辑:
|
||||
|
||||
1. 前端先构造后端回调地址:
|
||||
|
||||
```ts
|
||||
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
||||
```
|
||||
|
||||
其中:
|
||||
|
||||
- `redirect_uri`:提供给 OIDC Provider 的回调地址,必须是后端地址。
|
||||
|
||||
登录成功后,后端固定回跳前端首页 `/`,并通过 hash 传递 OIDC 结果。
|
||||
|
||||
2. 前端调用:
|
||||
|
||||
```ts
|
||||
GET /api/v1/auth/oidc/url?redirect_uri=...
|
||||
```
|
||||
|
||||
3. 后端返回 `authorization_url` 后,前端直接执行:
|
||||
|
||||
```ts
|
||||
window.location.href = authorizationURL
|
||||
```
|
||||
|
||||
浏览器随后离开 WeKnora 页面,跳转到 OIDC Provider 的授权页。
|
||||
|
||||
---
|
||||
|
||||
## 5. 后端生成授权地址
|
||||
|
||||
对应处理器:`AuthHandler.GetOIDCAuthorizationURL`
|
||||
|
||||
对应服务:`userService.GetOIDCAuthorizationURL`
|
||||
|
||||
### 5.1 参数校验
|
||||
|
||||
后端要求以下参数必须存在:
|
||||
|
||||
- `redirect_uri`
|
||||
|
||||
否则直接返回校验错误。
|
||||
|
||||
### 5.2 读取 OIDC 配置
|
||||
|
||||
`getOIDCConfig()` 会执行以下逻辑:
|
||||
|
||||
1. 检查 `OIDCAuth.Enable` 是否为 `true`;
|
||||
2. 设置默认值:
|
||||
- `ProviderDisplayName` 默认是 `OIDC`
|
||||
- `Scopes` 默认是 `openid profile email`
|
||||
- `UserInfoMapping.Username` 默认是 `name`
|
||||
- `UserInfoMapping.Email` 默认是 `email`
|
||||
3. 若未显式配置授权/令牌端点,则通过 `discovery_url` 拉取 OIDC Discovery 文档;
|
||||
4. 自动补齐:
|
||||
- `authorization_endpoint`
|
||||
- `token_endpoint`
|
||||
- `userinfo_endpoint`
|
||||
|
||||
### 5.3 生成 state
|
||||
|
||||
后端不会把 state 只当成随机串,而是编码了一个 JSON 结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"nonce": "随机字符串",
|
||||
"redirect_uri": "后端回调地址"
|
||||
}
|
||||
```
|
||||
|
||||
然后再做 base64url 编码,作为 `state` 传给 Provider。
|
||||
|
||||
这样在 OIDC Provider 回调时,后端就可以从 `state` 里还原:
|
||||
|
||||
- 本次使用的后端 `redirect_uri`
|
||||
|
||||
### 5.4 拼接授权地址
|
||||
|
||||
后端最终拼接的参数包含:
|
||||
|
||||
- `response_type=code`
|
||||
- `client_id`
|
||||
- `redirect_uri`
|
||||
- `scope`
|
||||
- `state`
|
||||
|
||||
然后返回给前端:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"provider_display_name": "Dex",
|
||||
"authorization_url": "...",
|
||||
"state": "..."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. OIDC Provider 回调到后端
|
||||
|
||||
OIDC Provider 完成认证后,会回调:
|
||||
|
||||
```text
|
||||
GET /api/v1/auth/oidc/callback
|
||||
```
|
||||
|
||||
处理器为 `AuthHandler.OIDCRedirectCallback`。
|
||||
|
||||
### 6.1 Provider 返回错误时
|
||||
|
||||
如果 query 中带有:
|
||||
|
||||
- `error`
|
||||
- `error_description`
|
||||
|
||||
后端不会返回 JSON,而是直接 302 到前端首页 `/`,并带上 hash:
|
||||
|
||||
```text
|
||||
#oidc_error=...&oidc_error_description=...
|
||||
```
|
||||
|
||||
### 6.2 解析 state
|
||||
|
||||
后端会把 `state` 做 base64url 解码并解析为结构体。
|
||||
|
||||
如果出现以下情况,将判定失败:
|
||||
|
||||
- `state` 无法解码
|
||||
- JSON 结构非法
|
||||
- `state.redirect_uri` 为空
|
||||
|
||||
失败时会重定向到前端首页:
|
||||
|
||||
```text
|
||||
#oidc_error=invalid_state
|
||||
```
|
||||
|
||||
### 6.3 校验 code
|
||||
|
||||
如果没有收到 `code`,则重定向:
|
||||
|
||||
```text
|
||||
#oidc_error=missing_code
|
||||
```
|
||||
|
||||
### 6.4 正式执行 OIDC 登录
|
||||
|
||||
若 `state` 与 `code` 都合法,则调用:
|
||||
|
||||
```go
|
||||
LoginWithOIDC(ctx, code, decodedState.RedirectURI)
|
||||
```
|
||||
|
||||
注意这里传入的是 **state 中保存的 redirect_uri**,而不是重新拼接的地址,这样保证了 code 交换时使用的 `redirect_uri` 和授权时完全一致。
|
||||
|
||||
---
|
||||
|
||||
## 7. 后端用 code 换 token 并解析用户身份
|
||||
|
||||
核心逻辑位于 `internal/application/service/user.go`。
|
||||
|
||||
## 7.1 换取 OIDC token
|
||||
|
||||
`exchangeOIDCCode()` 会向 OIDC Provider 的 `token_endpoint` 发起:
|
||||
|
||||
```text
|
||||
POST application/x-www-form-urlencoded
|
||||
```
|
||||
|
||||
表单参数包括:
|
||||
|
||||
- `grant_type=authorization_code`
|
||||
- `code`
|
||||
- `redirect_uri`
|
||||
- `client_id`
|
||||
- `client_secret`
|
||||
|
||||
期望返回字段:
|
||||
|
||||
- `access_token`
|
||||
- `id_token`
|
||||
- `token_type`
|
||||
|
||||
如果 `access_token` 和 `id_token` 都缺失,则认为失败。
|
||||
|
||||
## 7.2 解析用户信息
|
||||
|
||||
`resolveOIDCUserInfo()` 的处理顺序是:
|
||||
|
||||
1. 如果有 `id_token`,先本地解码 JWT payload,提取 claims;
|
||||
2. 如果配置了 `userinfo_endpoint` 且有 `access_token`,再调用 userinfo 接口;
|
||||
3. 将两部分 claims 合并,userinfo 的字段可覆盖前面已取到的字段;
|
||||
4. 根据配置的 `user_info_mapping` 提取:
|
||||
- 用户名字段
|
||||
- 邮箱字段
|
||||
|
||||
默认映射:
|
||||
|
||||
- `username -> name`
|
||||
- `email -> email`
|
||||
|
||||
另外还有回退逻辑:
|
||||
|
||||
1. 若 username 为空,尝试 `preferred_username`
|
||||
2. 再尝试 `name`
|
||||
3. 再尝试从邮箱前缀生成用户名
|
||||
|
||||
如果最终没有拿到邮箱,则直接报错,因为本地用户是按 email 关联的。
|
||||
|
||||
---
|
||||
|
||||
## 8. 本地用户关联与自动开通
|
||||
|
||||
### 8.1 通过邮箱查找用户
|
||||
|
||||
后端使用 OIDC 返回的邮箱执行:
|
||||
|
||||
```go
|
||||
userRepo.GetUserByEmail(ctx, userInfo.Email)
|
||||
```
|
||||
|
||||
### 8.2 用户不存在时自动注册
|
||||
|
||||
若本地不存在该邮箱用户,则调用 `provisionOIDCUser()` 自动创建账号。
|
||||
|
||||
自动创建逻辑包括:
|
||||
|
||||
1. 根据 OIDC 用户名/邮箱生成本地用户名;
|
||||
2. 若用户名冲突,则自动追加 `-1`、`-2` 等后缀;
|
||||
3. 生成随机密码;
|
||||
4. 调用现有 `Register()` 流程创建用户;
|
||||
5. `Register()` 内部还会自动创建默认租户。
|
||||
|
||||
因此,**首次使用 OIDC 登录的用户,不需要提前在 WeKnora 中手工建号**。
|
||||
|
||||
### 8.3 用户禁用处理
|
||||
|
||||
如果找到的本地用户 `IsActive=false`,则登录失败,回调给前端的错误信息为:
|
||||
|
||||
```text
|
||||
Account is disabled
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 生成 WeKnora 本地登录态
|
||||
|
||||
OIDC 登录成功后,后端不会直接把 OIDC token 交给前端使用,而是继续执行:
|
||||
|
||||
```go
|
||||
GenerateTokens(ctx, user)
|
||||
```
|
||||
|
||||
生成两类 JWT:
|
||||
|
||||
- `token`:访问令牌,默认 24 小时
|
||||
- `refresh_token`:刷新令牌,默认 7 天
|
||||
|
||||
并写入本地 `auth_tokens` 存储(通过 `tokenRepo.CreateToken`)。
|
||||
|
||||
最终后端还会查询当前用户所属租户,并返回:
|
||||
|
||||
- `user`
|
||||
- `tenant`
|
||||
- `token`
|
||||
- `refresh_token`
|
||||
- `is_new_user`
|
||||
|
||||
这一步意味着:
|
||||
|
||||
> OIDC 只负责“确认你是谁”,WeKnora 自己负责“签发系统内可用的业务令牌”。
|
||||
|
||||
---
|
||||
|
||||
## 10. 后端如何把结果传回前端
|
||||
|
||||
`OIDCRedirectCallback` 在拿到 `OIDCCallbackResponse` 后,会执行:
|
||||
|
||||
1. 将响应对象 JSON 序列化;
|
||||
2. 用 base64url 编码;
|
||||
3. 302 重定向到:
|
||||
|
||||
```text
|
||||
/#oidc_result=ENCODED_PAYLOAD
|
||||
```
|
||||
|
||||
失败时则返回:
|
||||
|
||||
```text
|
||||
/#oidc_error=...&oidc_error_description=...
|
||||
```
|
||||
|
||||
这里使用 hash 的好处是:
|
||||
|
||||
- 不会把结果作为 query 参数再次发送给服务端;
|
||||
- 前端可以在浏览器本地直接读取并清理;
|
||||
- 避免刷新时重复向后端暴露这些参数。
|
||||
|
||||
---
|
||||
|
||||
## 11. 前端如何消费 OIDC 回调结果
|
||||
|
||||
前端不是在 `Login.vue` 中处理回调,而是在 `frontend/src/App.vue` 中统一处理。
|
||||
|
||||
这样即使后端把用户重定向到 `/`,应用根组件也能接住这次 OIDC 登录结果。
|
||||
|
||||
## 11.1 App.vue 解析 hash
|
||||
|
||||
应用挂载时执行:
|
||||
|
||||
```ts
|
||||
handleGlobalOIDCCallback()
|
||||
```
|
||||
|
||||
它会读取:
|
||||
|
||||
```ts
|
||||
window.location.hash
|
||||
```
|
||||
|
||||
并解析以下字段:
|
||||
|
||||
- `oidc_error`
|
||||
- `oidc_error_description`
|
||||
- `oidc_result`
|
||||
|
||||
## 11.2 错误分支
|
||||
|
||||
如果存在 `oidc_error`:
|
||||
|
||||
1. 调用 `clearOIDCCallbackState('/login')` 清理 URL;
|
||||
2. 跳转到 `/login`;
|
||||
3. 弹出错误消息。
|
||||
|
||||
## 11.3 成功分支
|
||||
|
||||
如果存在 `oidc_result`:
|
||||
|
||||
1. base64url 解码并反序列化;
|
||||
2. 如果 `response.success=true`:
|
||||
- 写入 `authStore.setUser(...)`
|
||||
- 写入 `authStore.setToken(...)`
|
||||
- 写入 `authStore.setRefreshToken(...)`
|
||||
- 写入 `authStore.setTenant(...)`
|
||||
3. 最终跳转到:
|
||||
|
||||
```text
|
||||
/platform/knowledge-bases
|
||||
```
|
||||
|
||||
这与普通账号密码登录成功后的持久化逻辑保持一致。
|
||||
|
||||
---
|
||||
|
||||
## 12. 关键配置项
|
||||
|
||||
OIDC 配置定义位于 `internal/config/config.go`,环境变量示例见 `.env.example`。
|
||||
|
||||
### 12.1 主要配置项
|
||||
|
||||
| 配置项 | 说明 |
|
||||
|---|---|
|
||||
| `OIDC_AUTH_ENABLE` | 是否启用 OIDC 登录 |
|
||||
| `OIDC_AUTH_ISSUER_URL` | Issuer 地址,可用于自动拼 discovery URL |
|
||||
| `OIDC_AUTH_DISCOVERY_URL` | OIDC Discovery 地址 |
|
||||
| `OIDC_AUTH_PROVIDER_DISPLAY_NAME` | 前端按钮显示名称 |
|
||||
| `OIDC_AUTH_CLIENT_ID` | OIDC Client ID |
|
||||
| `OIDC_AUTH_CLIENT_SECRET` | OIDC Client Secret |
|
||||
| `OIDC_AUTH_AUTHORIZATION_ENDPOINT` | 授权端点,可选 |
|
||||
| `OIDC_AUTH_TOKEN_ENDPOINT` | Token 端点,可选 |
|
||||
| `OIDC_AUTH_USER_INFO_ENDPOINT` | UserInfo 端点,可选 |
|
||||
| `OIDC_AUTH_SCOPES` | Scope 列表,默认 `openid profile email` |
|
||||
| `OIDC_USER_INFO_MAPPING_USER_NAME` | claims 中映射到用户名的字段名 |
|
||||
| `OIDC_USER_INFO_MAPPING_EMAIL` | claims 中映射到邮箱的字段名 |
|
||||
|
||||
### 12.2 启用时的最小要求
|
||||
|
||||
当 `OIDC_AUTH_ENABLE=true` 时,后端校验要求:
|
||||
|
||||
1. 必须有 `client_id`
|
||||
2. 必须有 `client_secret`
|
||||
3. 必须满足以下二选一:
|
||||
- 配置 `discovery_url`
|
||||
- 或同时配置 `authorization_endpoint + token_endpoint`
|
||||
|
||||
---
|
||||
|
||||
## 13. 本地联调示例(Dex)
|
||||
[Dex](https://dexidp.io/) 是一个简单易用的OIDC Provider,您可以通过它对接多种第三方认证系统(如OAuth2.0,Google,GitHub,LDAP等)。除了Dex之外,您也可以选择[KeyCloak](https://www.keycloak.org/)等其他符合OpenID Connect协议的Provider进行接入。
|
||||
|
||||
项目中已提供 Dex 示例配置:`misc/dex-config.yaml`。
|
||||
|
||||
其中静态客户端配置示例:
|
||||
|
||||
```yaml
|
||||
staticClients:
|
||||
- id: weknora
|
||||
redirectURIs:
|
||||
- 'http://127.0.0.1:5173/api/v1/auth/oidc/callback'
|
||||
- 'http://127.0.0.1/api/v1/auth/oidc/callback'
|
||||
name: 'WeKnora'
|
||||
# secret: <YOUR_SECRET_HERE>
|
||||
```
|
||||
|
||||
这说明本地调试时,需要确保 **Provider 注册的 redirect URI 与前端实际传给后端的 `redirect_uri` 完全一致**。
|
||||
|
||||
前端当前实现中使用的是:
|
||||
|
||||
```ts
|
||||
${window.location.origin}/api/v1/auth/oidc/callback
|
||||
```
|
||||
|
||||
所以:
|
||||
|
||||
- 若前端从 `http://127.0.0.1:5173` 访问,则 redirect URI 为
|
||||
`http://127.0.0.1:5173/api/v1/auth/oidc/callback`
|
||||
- 若通过 Nginx 统一入口访问,则可能是
|
||||
`http://127.0.0.1/api/v1/auth/oidc/callback`
|
||||
|
||||
Provider 必须提前把这些地址加入白名单。
|
||||
|
||||
---
|
||||
|
||||
## 14. 调用链路总结
|
||||
|
||||
可以把当前 OIDC 登录理解为以下 4 个阶段:
|
||||
|
||||
### 阶段一:前端发现能力
|
||||
|
||||
前端调用 `/auth/oidc/config`,决定是否展示第三方登录入口。
|
||||
|
||||
### 阶段二:浏览器跳转授权
|
||||
|
||||
前端调用 `/auth/oidc/url` 获取授权地址,然后跳转到 OIDC Provider。
|
||||
|
||||
### 阶段三:后端完成身份兑换
|
||||
|
||||
Provider 回调后端 `/auth/oidc/callback`,后端用 `code` 换 token、拉取用户信息、关联或创建本地用户,并签发 WeKnora JWT。
|
||||
|
||||
### 阶段四:前端接收最终结果
|
||||
|
||||
后端 302 回前端,并通过 `#oidc_result` 传递登录结果;前端在 `App.vue` 中统一解析,写入本地登录态并进入业务页面。
|
||||
|
||||
---
|
||||
|
||||
## 15. 注意事项
|
||||
|
||||
1. **`redirect_uri` 必须严格匹配** Provider 客户端配置。
|
||||
2. **前端首页不是 OIDC Provider 回调地址**。
|
||||
- Provider 回调的是后端 `/api/v1/auth/oidc/callback`
|
||||
- 后端再固定重定向到前端首页 `/`
|
||||
3. **邮箱是本地账号关联主键**。
|
||||
- 若 Provider 没返回 email,将无法完成登录。
|
||||
4. **首次 OIDC 登录会自动创建用户和默认租户**。
|
||||
5. **真正用于访问 WeKnora API 的仍是本地 JWT**,不是 OIDC access token。
|
||||
6. 当前实现对 `state` 做了编码封装,但 **没有服务端持久化 state/nonce 校验**;它主要用于传递上下文和基本防错,而不是完整的防重放机制。
|
||||
|
||||
---
|
||||
|
||||
## 16. 相关源码定位
|
||||
|
||||
- 前端是否展示 OIDC 登录按钮:
|
||||
- `frontend/src/views/auth/Login.vue`
|
||||
- 前端获取授权地址:
|
||||
- `frontend/src/api/auth/index.ts`
|
||||
- `frontend/src/views/auth/Login.vue`
|
||||
- 前端解析回调 hash:
|
||||
- `frontend/src/App.vue`
|
||||
- OIDC 接口路由注册:
|
||||
- `internal/router/router.go`
|
||||
- OIDC HTTP 处理:
|
||||
- `internal/handler/auth.go`
|
||||
- OIDC 业务逻辑:
|
||||
- `internal/application/service/user.go`
|
||||
- OIDC 配置结构与环境变量覆盖:
|
||||
- `internal/config/config.go`
|
||||
- Dex 本地示例:
|
||||
- `misc/dex-config.yaml`
|
||||
+97
-1
@@ -1,7 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, nextTick, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import ManualKnowledgeEditor from '@/components/manual-knowledge-editor.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
// TDesign locale configs
|
||||
import enUSConfig from 'tdesign-vue-next/esm/locale/en_US'
|
||||
@@ -10,6 +13,8 @@ import koKRConfig from 'tdesign-vue-next/esm/locale/ko_KR'
|
||||
import ruRUConfig from 'tdesign-vue-next/esm/locale/ru_RU'
|
||||
|
||||
const { locale } = useI18n()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const tdLocaleMap: Record<string, object> = {
|
||||
'en-US': enUSConfig,
|
||||
@@ -19,6 +24,97 @@ const tdLocaleMap: Record<string, object> = {
|
||||
}
|
||||
|
||||
const tdGlobalConfig = computed(() => tdLocaleMap[locale.value] || enUSConfig)
|
||||
|
||||
const decodeOIDCResult = (encoded: string) => {
|
||||
const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4)
|
||||
const binary = window.atob(padded)
|
||||
const bytes = Uint8Array.from(binary, char => char.charCodeAt(0))
|
||||
return JSON.parse(new TextDecoder().decode(bytes))
|
||||
}
|
||||
|
||||
const clearOIDCCallbackState = (path = '/') => {
|
||||
window.history.replaceState({}, document.title, path)
|
||||
}
|
||||
|
||||
const persistOIDCLoginResponse = async (response: any) => {
|
||||
if (response.user && response.tenant && response.token) {
|
||||
authStore.setUser({
|
||||
id: response.user.id || '',
|
||||
username: response.user.username || '',
|
||||
email: response.user.email || '',
|
||||
avatar: response.user.avatar,
|
||||
tenant_id: String(response.tenant.id) || '',
|
||||
can_access_all_tenants: response.user.can_access_all_tenants || false,
|
||||
created_at: response.user.created_at || new Date().toISOString(),
|
||||
updated_at: response.user.updated_at || new Date().toISOString()
|
||||
})
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: response.tenant.created_at || new Date().toISOString(),
|
||||
updated_at: response.tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
|
||||
const handleGlobalOIDCCallback = async () => {
|
||||
const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : ''
|
||||
if (!hash) return
|
||||
|
||||
const params = new URLSearchParams(hash)
|
||||
const oidcError = params.get('oidc_error')
|
||||
const oidcErrorDescription = params.get('oidc_error_description')
|
||||
const oidcResult = params.get('oidc_result')
|
||||
|
||||
if (!oidcError && !oidcResult) return
|
||||
|
||||
if (oidcError) {
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error(oidcErrorDescription || 'OIDC login failed')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
if (!oidcResult) {
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error('OIDC login failed')
|
||||
return
|
||||
}
|
||||
|
||||
const response = decodeOIDCResult(oidcResult)
|
||||
if (response.success) {
|
||||
clearOIDCCallbackState('/')
|
||||
MessagePlugin.success('Login successful')
|
||||
await persistOIDCLoginResponse(response)
|
||||
return
|
||||
}
|
||||
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error(response.message || 'OIDC login failed')
|
||||
} catch (error: any) {
|
||||
console.error('Global OIDC callback handling failed:', error)
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error(error.message || 'OIDC login failed')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
handleGlobalOIDCCallback()
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<t-config-provider :globalConfig="tdGlobalConfig">
|
||||
|
||||
@@ -39,6 +39,20 @@ export interface LoginResponse {
|
||||
refresh_token?: string
|
||||
}
|
||||
|
||||
export interface OIDCAuthURLResponse {
|
||||
success: boolean
|
||||
authorization_url?: string
|
||||
state?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface OIDCConfigResponse {
|
||||
success: boolean
|
||||
enabled: boolean
|
||||
provider_display_name?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
// 用户注册接口
|
||||
export interface RegisterRequest {
|
||||
username: string
|
||||
@@ -130,6 +144,37 @@ export async function login(data: LoginRequest): Promise<LoginResponse> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 OIDC 登录跳转地址
|
||||
*/
|
||||
export async function getOIDCAuthorizationURL(redirectURI: string): Promise<OIDCAuthURLResponse> {
|
||||
try {
|
||||
const response = await get(`/api/v1/auth/oidc/url?redirect_uri=${encodeURIComponent(redirectURI)}`)
|
||||
return response as unknown as OIDCAuthURLResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 OIDC 登录配置
|
||||
*/
|
||||
export async function getOIDCConfig(): Promise<OIDCConfigResponse> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/oidc/config')
|
||||
return response as unknown as OIDCConfigResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
enabled: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
*/
|
||||
|
||||
@@ -1027,6 +1027,12 @@ export default {
|
||||
auth: {
|
||||
login: 'Login',
|
||||
logout: 'Logout',
|
||||
oidcLogin: 'Sign in with OIDC',
|
||||
oidcLoginWithProvider: 'Sign in with {provider}',
|
||||
redirectingToOIDC: 'Redirecting to identity provider...',
|
||||
orContinueWith: 'Or continue with',
|
||||
oidcLoginFailed: 'OIDC login failed',
|
||||
oidcStateMismatch: 'OIDC state verification failed, please try again',
|
||||
username: 'Username',
|
||||
email: 'Email',
|
||||
password: 'Password',
|
||||
|
||||
@@ -989,6 +989,12 @@ export default {
|
||||
auth: {
|
||||
login: 'Вход',
|
||||
logout: 'Выход',
|
||||
oidcLogin: 'Войти через OIDC',
|
||||
oidcLoginWithProvider: 'Войти через {provider}',
|
||||
redirectingToOIDC: 'Перенаправление к поставщику удостоверений...',
|
||||
orContinueWith: 'Или продолжить с помощью',
|
||||
oidcLoginFailed: 'Ошибка входа через OIDC',
|
||||
oidcStateMismatch: 'Не удалось проверить состояние OIDC, попробуйте снова',
|
||||
username: 'Имя пользователя',
|
||||
email: 'Почта Email',
|
||||
password: 'Пароль',
|
||||
|
||||
@@ -887,6 +887,12 @@ export default {
|
||||
loginSuccess: "登录成功!",
|
||||
loginFailed: "登录失败",
|
||||
loggingIn: "登录中...",
|
||||
oidcLogin: "使用 OIDC 登录",
|
||||
oidcLoginWithProvider: "使用 {provider} 登录",
|
||||
redirectingToOIDC: "正在跳转到身份提供商...",
|
||||
orContinueWith: "或使用以下方式继续",
|
||||
oidcLoginFailed: "OIDC 登录失败",
|
||||
oidcStateMismatch: "OIDC 状态校验失败,请重试",
|
||||
register: "注册",
|
||||
registering: "注册中...",
|
||||
createAccount: "创建账户",
|
||||
|
||||
@@ -228,14 +228,31 @@
|
||||
>
|
||||
{{ loading ? $t('auth.loggingIn') : $t('auth.login') }}
|
||||
</t-button>
|
||||
</t-form>
|
||||
|
||||
<div class="form-footer">
|
||||
<span>{{ $t('auth.noAccount') }}</span>
|
||||
<a href="#" @click.prevent="toggleMode" class="link-button">
|
||||
{{ $t('auth.registerNow') }}
|
||||
</a>
|
||||
</div>
|
||||
<div class="form-footer login-form-footer">
|
||||
<span>{{ $t('auth.noAccount') }}</span>
|
||||
<a href="#" @click.prevent="toggleMode" class="link-button">
|
||||
{{ $t('auth.registerNow') }}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div v-if="oidcEnabled" class="oidc-divider">
|
||||
<span>{{ $t('auth.orContinueWith') }}</span>
|
||||
</div>
|
||||
|
||||
<t-button
|
||||
v-if="oidcEnabled"
|
||||
theme="default"
|
||||
size="large"
|
||||
block
|
||||
:loading="oidcLoading"
|
||||
:disabled="loading"
|
||||
class="oidc-button"
|
||||
@click="handleOIDCLogin"
|
||||
>
|
||||
{{ oidcLoading ? $t('auth.redirectingToOIDC') : oidcLoginText }}
|
||||
</t-button>
|
||||
</t-form>
|
||||
|
||||
<!-- Features list -->
|
||||
<div class="login-features">
|
||||
@@ -360,7 +377,7 @@ import { Autoplay, EffectFade, Pagination } from 'swiper/modules'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/effect-fade'
|
||||
import 'swiper/css/pagination'
|
||||
import { login, register } from '@/api/auth'
|
||||
import { login, register, getOIDCAuthorizationURL, getOIDCConfig } from '@/api/auth'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -401,8 +418,11 @@ const registerFormRef = ref()
|
||||
|
||||
// State management
|
||||
const loading = ref(false)
|
||||
const oidcLoading = ref(false)
|
||||
const isRegisterMode = ref(false)
|
||||
const showLanguageMenu = ref(false)
|
||||
const oidcEnabled = ref(false)
|
||||
const oidcProviderName = ref('')
|
||||
|
||||
// Language options
|
||||
const languageOptions = [
|
||||
@@ -413,6 +433,12 @@ const languageOptions = [
|
||||
]
|
||||
|
||||
const currentLanguage = computed(() => locale.value)
|
||||
const oidcLoginText = computed(() => {
|
||||
if (oidcProviderName.value) {
|
||||
return t('auth.oidcLoginWithProvider', { provider: oidcProviderName.value })
|
||||
}
|
||||
return t('auth.oidcLogin')
|
||||
})
|
||||
const currentLangOption = computed(() => languageOptions.find(l => l.value === currentLanguage.value))
|
||||
|
||||
// Login form data
|
||||
@@ -516,6 +542,69 @@ onBeforeUnmount(() => {
|
||||
document.removeEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
const persistLoginResponse = async (response: any) => {
|
||||
if (response.user && response.tenant && response.token) {
|
||||
authStore.setUser({
|
||||
id: response.user.id || '',
|
||||
username: response.user.username || '',
|
||||
email: response.user.email || '',
|
||||
avatar: response.user.avatar,
|
||||
tenant_id: String(response.tenant.id) || '',
|
||||
can_access_all_tenants: response.user.can_access_all_tenants || false,
|
||||
created_at: response.user.created_at || new Date().toISOString(),
|
||||
updated_at: response.user.updated_at || new Date().toISOString()
|
||||
})
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: response.tenant.created_at || new Date().toISOString(),
|
||||
updated_at: response.tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
|
||||
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
||||
|
||||
const loadOIDCConfig = async () => {
|
||||
try {
|
||||
const response = await getOIDCConfig()
|
||||
oidcEnabled.value = !!response.success && !!response.enabled
|
||||
oidcProviderName.value = response.provider_display_name || ''
|
||||
} catch {
|
||||
oidcEnabled.value = false
|
||||
oidcProviderName.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleOIDCLogin = async () => {
|
||||
try {
|
||||
oidcLoading.value = true
|
||||
const response = await getOIDCAuthorizationURL(getBackendOIDCRedirectURI())
|
||||
const authorizationURL = response.authorization_url
|
||||
|
||||
if (!response.success || !authorizationURL) {
|
||||
MessagePlugin.error(response.message || t('auth.oidcLoginFailed'))
|
||||
return
|
||||
}
|
||||
|
||||
window.location.href = authorizationURL
|
||||
} catch (error: any) {
|
||||
console.error('OIDC 登录跳转失败:', error)
|
||||
MessagePlugin.error(error.message || t('auth.oidcLoginFailed'))
|
||||
} finally {
|
||||
oidcLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Handle login
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
@@ -530,37 +619,8 @@ const handleLogin = async () => {
|
||||
})
|
||||
|
||||
if (response.success) {
|
||||
// Save user info and token
|
||||
if (response.user && response.tenant && response.token) {
|
||||
authStore.setUser({
|
||||
id: response.user.id || '',
|
||||
username: response.user.username || '',
|
||||
email: response.user.email || '',
|
||||
avatar: response.user.avatar,
|
||||
tenant_id: String(response.tenant.id) || '',
|
||||
can_access_all_tenants: response.user.can_access_all_tenants || false,
|
||||
created_at: response.user.created_at || new Date().toISOString(),
|
||||
updated_at: response.user.updated_at || new Date().toISOString()
|
||||
})
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: response.tenant.created_at || new Date().toISOString(),
|
||||
updated_at: response.tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
}
|
||||
|
||||
MessagePlugin.success(t('auth.loginSuccess'))
|
||||
|
||||
// Wait for state update before redirect
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
await persistLoginResponse(response)
|
||||
} else {
|
||||
MessagePlugin.error(response.message || t('auth.loginError'))
|
||||
}
|
||||
@@ -611,8 +671,11 @@ const handleRegister = async () => {
|
||||
// Check if already logged in
|
||||
onMounted(() => {
|
||||
if (authStore.isLoggedIn) {
|
||||
router.replace('/platform/tenant/knowledge-bases')
|
||||
router.replace('/platform/knowledge-bases')
|
||||
return
|
||||
}
|
||||
|
||||
loadOIDCConfig()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -1083,6 +1146,37 @@ onMounted(() => {
|
||||
margin: 20px 0 16px 0;
|
||||
}
|
||||
|
||||
.oidc-divider {
|
||||
position: relative;
|
||||
margin: 4px 0 6px;
|
||||
text-align: center;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: 12px;
|
||||
|
||||
span {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
padding: 0 12px;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 50%;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
}
|
||||
|
||||
.oidc-button {
|
||||
height: 46px;
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-footer {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
@@ -1106,6 +1200,12 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.login-form-footer {
|
||||
border-bottom: none;
|
||||
padding-bottom: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.login-features {
|
||||
margin-top: 20px;
|
||||
padding: 0;
|
||||
@@ -1145,6 +1245,14 @@ onMounted(() => {
|
||||
|
||||
/* Responsive Design */
|
||||
@media (max-width: 1024px) {
|
||||
.knowledge-node:nth-of-type(n + 13) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.connection-line:nth-of-type(n + 13) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.showcase-subtitle {
|
||||
font-size: 18px;
|
||||
}
|
||||
@@ -1179,6 +1287,14 @@ onMounted(() => {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.knowledge-node:nth-of-type(n + 9) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.connection-line:nth-of-type(n + 9) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.showcase-section {
|
||||
flex: 0 0 auto;
|
||||
min-height: 50vh;
|
||||
@@ -1241,6 +1357,10 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.animated-bg {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.showcase-section {
|
||||
padding: 32px 20px;
|
||||
}
|
||||
@@ -1287,6 +1407,18 @@ onMounted(() => {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.knowledge-node,
|
||||
.connection-line {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.animated-bg {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
|
||||
@@ -4,8 +4,12 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -15,12 +19,19 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
type oidcAuthorizationState struct {
|
||||
Nonce string `json:"nonce"`
|
||||
RedirectURI string `json:"redirect_uri,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
jwtSecretOnce sync.Once
|
||||
jwtSecret string
|
||||
@@ -49,10 +60,12 @@ type userService struct {
|
||||
userRepo interfaces.UserRepository
|
||||
tokenRepo interfaces.AuthTokenRepository
|
||||
tenantService interfaces.TenantService
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
// NewUserService creates a new user service instance
|
||||
func NewUserService(
|
||||
configInfo *config.Config,
|
||||
userRepo interfaces.UserRepository,
|
||||
tokenRepo interfaces.AuthTokenRepository,
|
||||
tenantService interfaces.TenantService,
|
||||
@@ -61,6 +74,7 @@ func NewUserService(
|
||||
userRepo: userRepo,
|
||||
tokenRepo: tokenRepo,
|
||||
tenantService: tenantService,
|
||||
config: configInfo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,6 +212,116 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetOIDCAuthorizationURL builds the OIDC authorization URL.
|
||||
func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error) {
|
||||
cfg, err := s.getOIDCConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(redirectURI) == "" {
|
||||
return nil, errors.New("redirect_uri is required")
|
||||
}
|
||||
|
||||
nonce, err := generateRandomString(24)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate state: %w", err)
|
||||
}
|
||||
|
||||
state, err := encodeOIDCAuthorizationState(&oidcAuthorizationState{
|
||||
Nonce: nonce,
|
||||
RedirectURI: strings.TrimSpace(redirectURI),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encode OIDC state: %w", err)
|
||||
}
|
||||
|
||||
query := url.Values{}
|
||||
query.Set("response_type", "code")
|
||||
query.Set("client_id", cfg.ClientID)
|
||||
query.Set("redirect_uri", redirectURI)
|
||||
query.Set("scope", strings.Join(cfg.Scopes, " "))
|
||||
query.Set("state", state)
|
||||
|
||||
authURL := cfg.AuthorizationEndpoint
|
||||
if strings.Contains(authURL, "?") {
|
||||
authURL += "&" + query.Encode()
|
||||
} else {
|
||||
authURL += "?" + query.Encode()
|
||||
}
|
||||
|
||||
return &types.OIDCAuthURLResponse{
|
||||
Success: true,
|
||||
ProviderDisplayName: cfg.ProviderDisplayName,
|
||||
AuthorizationURL: authURL,
|
||||
State: state,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LoginWithOIDC exchanges code for tokens, loads user info, provisions user if needed, and returns local login tokens.
|
||||
func (s *userService) LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error) {
|
||||
if strings.TrimSpace(code) == "" {
|
||||
return nil, errors.New("code is required")
|
||||
}
|
||||
if strings.TrimSpace(redirectURI) == "" {
|
||||
return nil, errors.New("redirect_uri is required")
|
||||
}
|
||||
|
||||
cfg, err := s.getOIDCConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tokenResp, err := s.exchangeOIDCCode(ctx, cfg, code, redirectURI)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userInfo, err := s.resolveOIDCUserInfo(ctx, cfg, tokenResp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(userInfo.Email) == "" {
|
||||
return nil, errors.New("OIDC provider did not return email")
|
||||
}
|
||||
|
||||
user, err := s.userRepo.GetUserByEmail(ctx, userInfo.Email)
|
||||
if err != nil && !isUserLookupNotFound(err) {
|
||||
return nil, fmt.Errorf("failed to query user by email: %w", err)
|
||||
}
|
||||
isNewUser := false
|
||||
if isUserLookupNotFound(err) || user == nil {
|
||||
user, err = s.provisionOIDCUser(ctx, userInfo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
isNewUser = true
|
||||
}
|
||||
|
||||
if !user.IsActive {
|
||||
return &types.OIDCCallbackResponse{Success: false, Message: "Account is disabled"}, nil
|
||||
}
|
||||
|
||||
accessToken, refreshToken, err := s.GenerateTokens(ctx, user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate local tokens: %w", err)
|
||||
}
|
||||
|
||||
tenant, err := s.tenantService.GetTenantByID(ctx, user.TenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get tenant info after OIDC login: %v", err)
|
||||
}
|
||||
|
||||
return &types.OIDCCallbackResponse{
|
||||
Success: true,
|
||||
Message: "Login successful",
|
||||
User: user,
|
||||
Tenant: tenant,
|
||||
Token: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
IsNewUser: isNewUser,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetUserByID gets a user by ID
|
||||
func (s *userService) GetUserByID(ctx context.Context, id string) (*types.User, error) {
|
||||
return s.userRepo.GetUserByID(ctx, id)
|
||||
@@ -439,3 +563,296 @@ func (s *userService) SearchUsers(ctx context.Context, query string, limit int)
|
||||
}
|
||||
return s.userRepo.SearchUsers(ctx, query, limit)
|
||||
}
|
||||
|
||||
type oidcDiscoveryDocument struct {
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
TokenEndpoint string `json:"token_endpoint"`
|
||||
UserInfoEndpoint string `json:"userinfo_endpoint"`
|
||||
}
|
||||
|
||||
type oidcTokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
IDToken string `json:"id_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
|
||||
func (s *userService) getOIDCConfig(ctx context.Context) (*config.OIDCAuthConfig, error) {
|
||||
if s.config == nil || s.config.OIDCAuth == nil || !s.config.OIDCAuth.Enable {
|
||||
return nil, errors.New("OIDC login is disabled")
|
||||
}
|
||||
cfg := *s.config.OIDCAuth
|
||||
if cfg.UserInfoMapping == nil {
|
||||
cfg.UserInfoMapping = &config.OIDCUserInfoMapping{Username: "name", Email: "email"}
|
||||
}
|
||||
if err := s.populateOIDCEndpoints(ctx, &cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func (s *userService) populateOIDCEndpoints(ctx context.Context, cfg *config.OIDCAuthConfig) error {
|
||||
if strings.TrimSpace(cfg.AuthorizationEndpoint) != "" && strings.TrimSpace(cfg.TokenEndpoint) != "" {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(cfg.DiscoveryURL) == "" {
|
||||
return errors.New("OIDC discovery_url or explicit endpoints are required")
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.DiscoveryURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create OIDC discovery request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load OIDC discovery document: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
||||
return fmt.Errorf("OIDC discovery request failed: status=%d body=%s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
var doc oidcDiscoveryDocument
|
||||
if err := json.NewDecoder(resp.Body).Decode(&doc); err != nil {
|
||||
return fmt.Errorf("failed to decode OIDC discovery document: %w", err)
|
||||
}
|
||||
if cfg.AuthorizationEndpoint == "" {
|
||||
cfg.AuthorizationEndpoint = doc.AuthorizationEndpoint
|
||||
}
|
||||
if cfg.TokenEndpoint == "" {
|
||||
cfg.TokenEndpoint = doc.TokenEndpoint
|
||||
}
|
||||
if cfg.UserInfoEndpoint == "" {
|
||||
cfg.UserInfoEndpoint = doc.UserInfoEndpoint
|
||||
}
|
||||
if cfg.AuthorizationEndpoint == "" || cfg.TokenEndpoint == "" {
|
||||
return errors.New("OIDC discovery document missing required endpoints")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userService) exchangeOIDCCode(ctx context.Context, cfg *config.OIDCAuthConfig, code, redirectURI string) (*oidcTokenResponse, error) {
|
||||
form := url.Values{}
|
||||
form.Set("grant_type", "authorization_code")
|
||||
form.Set("code", code)
|
||||
form.Set("redirect_uri", redirectURI)
|
||||
form.Set("client_id", cfg.ClientID)
|
||||
form.Set("client_secret", cfg.ClientSecret)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.TokenEndpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create OIDC token request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to exchange OIDC code: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
||||
return nil, fmt.Errorf("OIDC token exchange failed: status=%d body=%s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
var tokenResp oidcTokenResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode OIDC token response: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(tokenResp.AccessToken) == "" && strings.TrimSpace(tokenResp.IDToken) == "" {
|
||||
return nil, errors.New("OIDC token response missing access_token and id_token")
|
||||
}
|
||||
return &tokenResp, nil
|
||||
}
|
||||
|
||||
func (s *userService) resolveOIDCUserInfo(ctx context.Context, cfg *config.OIDCAuthConfig, tokenResp *oidcTokenResponse) (*types.OIDCUserInfo, error) {
|
||||
claims := map[string]interface{}{}
|
||||
|
||||
if strings.TrimSpace(tokenResp.IDToken) != "" {
|
||||
idTokenClaims, err := decodeJWTClaims(tokenResp.IDToken)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to decode OIDC id_token claims: %v", err)
|
||||
} else {
|
||||
for k, v := range idTokenClaims {
|
||||
claims[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if strings.TrimSpace(cfg.UserInfoEndpoint) != "" && strings.TrimSpace(tokenResp.AccessToken) != "" {
|
||||
userInfoClaims, err := s.fetchOIDCUserInfo(ctx, cfg.UserInfoEndpoint, tokenResp.AccessToken)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch OIDC userinfo, fallback to id_token claims: %v", err)
|
||||
} else {
|
||||
for k, v := range userInfoClaims {
|
||||
claims[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info := &types.OIDCUserInfo{Claims: claims}
|
||||
if sub, _ := claims["sub"].(string); sub != "" {
|
||||
info.Subject = sub
|
||||
}
|
||||
info.Username = extractClaimAsString(claims, cfg.UserInfoMapping.Username)
|
||||
info.Email = extractClaimAsString(claims, cfg.UserInfoMapping.Email)
|
||||
if info.Username == "" {
|
||||
info.Username = extractClaimAsString(claims, "preferred_username")
|
||||
}
|
||||
if info.Username == "" {
|
||||
info.Username = extractClaimAsString(claims, "name")
|
||||
}
|
||||
if info.Username == "" && info.Email != "" {
|
||||
info.Username = strings.Split(info.Email, "@")[0]
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (s *userService) fetchOIDCUserInfo(ctx context.Context, endpoint, accessToken string) (map[string]interface{}, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
||||
return nil, fmt.Errorf("userinfo request failed: status=%d body=%s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
var claims map[string]interface{}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&claims); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func (s *userService) provisionOIDCUser(ctx context.Context, info *types.OIDCUserInfo) (*types.User, error) {
|
||||
username := s.generateOIDCUsername(ctx, info)
|
||||
randomPassword, err := generateRandomString(32)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate password for OIDC user: %w", err)
|
||||
}
|
||||
|
||||
user, err := s.Register(ctx, &types.RegisterRequest{
|
||||
Username: username,
|
||||
Email: info.Email,
|
||||
Password: randomPassword,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to auto-provision OIDC user: %w", err)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *userService) generateOIDCUsername(ctx context.Context, info *types.OIDCUserInfo) string {
|
||||
base := sanitizeUsernameCandidate(info.Username)
|
||||
if base == "" {
|
||||
base = sanitizeUsernameCandidate(strings.Split(info.Email, "@")[0])
|
||||
}
|
||||
if base == "" {
|
||||
base = "oidc-user"
|
||||
}
|
||||
|
||||
candidate := base
|
||||
for i := 0; i < 20; i++ {
|
||||
existing, err := s.userRepo.GetUserByUsername(ctx, candidate)
|
||||
if isUserLookupNotFound(err) || (err == nil && existing == nil) {
|
||||
return candidate
|
||||
}
|
||||
if err != nil && !isUserLookupNotFound(err) {
|
||||
logger.Warnf(ctx, "Failed to check existing OIDC username %q: %v", candidate, err)
|
||||
}
|
||||
candidate = fmt.Sprintf("%s-%d", base, i+1)
|
||||
}
|
||||
return fmt.Sprintf("%s-%d", base, time.Now().Unix())
|
||||
}
|
||||
|
||||
func generateRandomString(length int) (string, error) {
|
||||
buffer := make([]byte, length)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func encodeOIDCAuthorizationState(state *oidcAuthorizationState) (string, error) {
|
||||
payload, err := json.Marshal(state)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(payload), nil
|
||||
}
|
||||
|
||||
func decodeJWTClaims(token string) (map[string]interface{}, error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) < 2 {
|
||||
return nil, errors.New("invalid JWT format")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var claims map[string]interface{}
|
||||
if err := json.Unmarshal(payload, &claims); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func extractClaimAsString(claims map[string]interface{}, key string) string {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return ""
|
||||
}
|
||||
value, ok := claims[key]
|
||||
if !ok || value == nil {
|
||||
return ""
|
||||
}
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(v)
|
||||
default:
|
||||
return strings.TrimSpace(fmt.Sprint(v))
|
||||
}
|
||||
}
|
||||
|
||||
func sanitizeUsernameCandidate(value string) string {
|
||||
value = strings.TrimSpace(strings.ToLower(value))
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
lastDash := false
|
||||
for _, r := range value {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '.' {
|
||||
b.WriteRune(r)
|
||||
lastDash = false
|
||||
continue
|
||||
}
|
||||
if !lastDash {
|
||||
b.WriteByte('-')
|
||||
lastDash = true
|
||||
}
|
||||
}
|
||||
result := strings.Trim(b.String(), "-._")
|
||||
if len(result) > 50 {
|
||||
result = strings.Trim(result[:50], "-._")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func isUserLookupNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
return errors.Is(err, apprepo.ErrUserNotFound) || strings.Contains(strings.ToLower(err.Error()), "user not found")
|
||||
}
|
||||
|
||||
+115
-18
@@ -20,6 +20,7 @@ type Config struct {
|
||||
Server *ServerConfig `yaml:"server" json:"server"`
|
||||
KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"`
|
||||
Tenant *TenantConfig `yaml:"tenant" json:"tenant"`
|
||||
OIDCAuth *OIDCAuthConfig `yaml:"oidc_auth" json:"oidc_auth"`
|
||||
Models []ModelConfig `yaml:"models" json:"models"`
|
||||
VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"`
|
||||
DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"`
|
||||
@@ -85,13 +86,13 @@ type ConversationConfig struct {
|
||||
Summary *SummaryConfig `yaml:"summary" json:"summary"`
|
||||
|
||||
// Prompt template ID fields — resolved to text by backfillConversationDefaults
|
||||
FallbackPromptID string `yaml:"fallback_prompt_id" json:"fallback_prompt_id"`
|
||||
RewritePromptID string `yaml:"rewrite_prompt_id" json:"rewrite_prompt_id"`
|
||||
GenerateSessionTitlePromptID string `yaml:"generate_session_title_prompt_id" json:"generate_session_title_prompt_id"`
|
||||
GenerateSummaryPromptID string `yaml:"generate_summary_prompt_id" json:"generate_summary_prompt_id"`
|
||||
ExtractEntitiesPromptID string `yaml:"extract_entities_prompt_id" json:"extract_entities_prompt_id"`
|
||||
ExtractRelationshipsPromptID string `yaml:"extract_relationships_prompt_id" json:"extract_relationships_prompt_id"`
|
||||
GenerateQuestionsPromptID string `yaml:"generate_questions_prompt_id" json:"generate_questions_prompt_id"`
|
||||
FallbackPromptID string `yaml:"fallback_prompt_id" json:"fallback_prompt_id"`
|
||||
RewritePromptID string `yaml:"rewrite_prompt_id" json:"rewrite_prompt_id"`
|
||||
GenerateSessionTitlePromptID string `yaml:"generate_session_title_prompt_id" json:"generate_session_title_prompt_id"`
|
||||
GenerateSummaryPromptID string `yaml:"generate_summary_prompt_id" json:"generate_summary_prompt_id"`
|
||||
ExtractEntitiesPromptID string `yaml:"extract_entities_prompt_id" json:"extract_entities_prompt_id"`
|
||||
ExtractRelationshipsPromptID string `yaml:"extract_relationships_prompt_id" json:"extract_relationships_prompt_id"`
|
||||
GenerateQuestionsPromptID string `yaml:"generate_questions_prompt_id" json:"generate_questions_prompt_id"`
|
||||
|
||||
// Resolved prompt text fields (populated by backfill, not from YAML)
|
||||
FallbackPrompt string `yaml:"-" json:"fallback_prompt"`
|
||||
@@ -162,6 +163,25 @@ type TenantConfig struct {
|
||||
EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"`
|
||||
}
|
||||
|
||||
type OIDCUserInfoMapping struct {
|
||||
Username string `yaml:"username" json:"username"`
|
||||
Email string `yaml:"email" json:"email"`
|
||||
}
|
||||
|
||||
type OIDCAuthConfig struct {
|
||||
Enable bool `yaml:"enable" json:"enable"`
|
||||
IssuerURL string `yaml:"issuer_url" json:"issuer_url"`
|
||||
DiscoveryURL string `yaml:"discovery_url" json:"discovery_url"`
|
||||
ProviderDisplayName string `yaml:"provider_display_name" json:"provider_display_name"`
|
||||
ClientID string `yaml:"client_id" json:"client_id"`
|
||||
ClientSecret string `yaml:"client_secret" json:"-"`
|
||||
AuthorizationEndpoint string `yaml:"authorization_endpoint" json:"authorization_endpoint"`
|
||||
TokenEndpoint string `yaml:"token_endpoint" json:"token_endpoint"`
|
||||
UserInfoEndpoint string `yaml:"user_info_endpoint" json:"user_info_endpoint"`
|
||||
Scopes []string `yaml:"scopes" json:"scopes"`
|
||||
UserInfoMapping *OIDCUserInfoMapping `yaml:"user_info_mapping" json:"user_info_mapping"`
|
||||
}
|
||||
|
||||
// PromptTemplateI18n holds localized name and description for a prompt template.
|
||||
type PromptTemplateI18n struct {
|
||||
Name string `yaml:"name" json:"name"`
|
||||
@@ -175,16 +195,16 @@ type PromptTemplateI18n struct {
|
||||
// - user: 用户侧 Prompt(仅在需要 system+user 配对的模板中使用,如 rewrite、keywords_extraction)
|
||||
// - i18n: 多语言 name/description,键为 locale(如 "zh-CN"、"en-US"、"ko-KR"),后端根据请求语言替换 Name/Description 再返回
|
||||
type PromptTemplate struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Description string `yaml:"description" json:"description"`
|
||||
Content string `yaml:"content" json:"content"`
|
||||
User string `yaml:"user" json:"user,omitempty"`
|
||||
HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"`
|
||||
HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"`
|
||||
Default bool `yaml:"default" json:"default,omitempty"`
|
||||
Mode string `yaml:"mode" json:"mode,omitempty"`
|
||||
I18n map[string]PromptTemplateI18n `yaml:"i18n" json:"-"`
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Description string `yaml:"description" json:"description"`
|
||||
Content string `yaml:"content" json:"content"`
|
||||
User string `yaml:"user" json:"user,omitempty"`
|
||||
HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"`
|
||||
HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"`
|
||||
Default bool `yaml:"default" json:"default,omitempty"`
|
||||
Mode string `yaml:"mode" json:"mode,omitempty"`
|
||||
I18n map[string]PromptTemplateI18n `yaml:"i18n" json:"-"`
|
||||
}
|
||||
|
||||
// PromptTemplatesConfig 提示词模板配置
|
||||
@@ -386,6 +406,8 @@ func LoadConfig() (*Config, error) {
|
||||
}
|
||||
|
||||
// Validate configuration values
|
||||
applyOIDCEnvOverrides(&cfg)
|
||||
|
||||
if err := ValidateConfig(&cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -398,6 +420,19 @@ func LoadConfig() (*Config, error) {
|
||||
func ValidateConfig(cfg *Config) error {
|
||||
var errs []string
|
||||
|
||||
if cfg.OIDCAuth != nil && cfg.OIDCAuth.Enable {
|
||||
if strings.TrimSpace(cfg.OIDCAuth.ClientID) == "" {
|
||||
errs = append(errs, "oidc_auth.client_id is required when OIDC is enabled")
|
||||
}
|
||||
if strings.TrimSpace(cfg.OIDCAuth.ClientSecret) == "" {
|
||||
errs = append(errs, "oidc_auth.client_secret is required when OIDC is enabled")
|
||||
}
|
||||
if strings.TrimSpace(cfg.OIDCAuth.DiscoveryURL) == "" &&
|
||||
(strings.TrimSpace(cfg.OIDCAuth.AuthorizationEndpoint) == "" || strings.TrimSpace(cfg.OIDCAuth.TokenEndpoint) == "") {
|
||||
errs = append(errs, "oidc_auth.discovery_url or both oidc_auth.authorization_endpoint and oidc_auth.token_endpoint are required when OIDC is enabled")
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Conversation != nil {
|
||||
if cfg.Conversation.EmbeddingTopK < 0 {
|
||||
errs = append(errs, "conversation.embedding_top_k must be >= 0")
|
||||
@@ -437,6 +472,68 @@ func ValidateConfig(cfg *Config) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyOIDCEnvOverrides(cfg *Config) {
|
||||
if cfg.OIDCAuth == nil {
|
||||
cfg.OIDCAuth = &OIDCAuthConfig{}
|
||||
}
|
||||
if cfg.OIDCAuth.UserInfoMapping == nil {
|
||||
cfg.OIDCAuth.UserInfoMapping = &OIDCUserInfoMapping{}
|
||||
}
|
||||
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ENABLE")); value != "" {
|
||||
cfg.OIDCAuth.Enable = strings.EqualFold(value, "true")
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ISSUER_URL")); value != "" {
|
||||
cfg.OIDCAuth.IssuerURL = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_DISCOVERY_URL")); value != "" {
|
||||
cfg.OIDCAuth.DiscoveryURL = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_PROVIDER_DISPLAY_NAME")); value != "" {
|
||||
cfg.OIDCAuth.ProviderDisplayName = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_CLIENT_ID")); value != "" {
|
||||
cfg.OIDCAuth.ClientID = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_CLIENT_SECRET")); value != "" {
|
||||
cfg.OIDCAuth.ClientSecret = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_AUTHORIZATION_ENDPOINT")); value != "" {
|
||||
cfg.OIDCAuth.AuthorizationEndpoint = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_TOKEN_ENDPOINT")); value != "" {
|
||||
cfg.OIDCAuth.TokenEndpoint = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_USER_INFO_ENDPOINT")); value != "" {
|
||||
cfg.OIDCAuth.UserInfoEndpoint = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_SCOPES")); value != "" {
|
||||
cfg.OIDCAuth.Scopes = strings.Fields(strings.ReplaceAll(value, ",", " "))
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_USER_INFO_MAPPING_USER_NAME")); value != "" {
|
||||
cfg.OIDCAuth.UserInfoMapping.Username = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_USER_INFO_MAPPING_EMAIL")); value != "" {
|
||||
cfg.OIDCAuth.UserInfoMapping.Email = value
|
||||
}
|
||||
|
||||
if cfg.OIDCAuth.ProviderDisplayName == "" {
|
||||
cfg.OIDCAuth.ProviderDisplayName = "OIDC"
|
||||
}
|
||||
if len(cfg.OIDCAuth.Scopes) == 0 {
|
||||
cfg.OIDCAuth.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
if cfg.OIDCAuth.UserInfoMapping.Username == "" {
|
||||
cfg.OIDCAuth.UserInfoMapping.Username = "name"
|
||||
}
|
||||
if cfg.OIDCAuth.UserInfoMapping.Email == "" {
|
||||
cfg.OIDCAuth.UserInfoMapping.Email = "email"
|
||||
}
|
||||
if cfg.OIDCAuth.DiscoveryURL == "" && cfg.OIDCAuth.IssuerURL != "" {
|
||||
cfg.OIDCAuth.DiscoveryURL = strings.TrimRight(cfg.OIDCAuth.IssuerURL, "/") + "/.well-known/openid-configuration"
|
||||
}
|
||||
}
|
||||
|
||||
// backfillConversationDefaults resolves prompt template ID references
|
||||
// into actual prompt text content. Only xxx_id fields are used;
|
||||
// no fallback to default templates.
|
||||
@@ -592,7 +689,7 @@ func loadPromptTemplates(configDir string) (*PromptTemplatesConfig, error) {
|
||||
"agent_system_prompt.yaml": &config.AgentSystemPrompt,
|
||||
"graph_extraction.yaml": &config.GraphExtraction,
|
||||
"generate_questions.yaml": &config.GenerateQuestions,
|
||||
"intent_prompts.yaml": &config.IntentPrompts,
|
||||
"intent_prompts.yaml": &config.IntentPrompts,
|
||||
}
|
||||
|
||||
// 加载每个模板文件
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -157,6 +159,161 @@ func (h *AuthHandler) Login(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// GetOIDCAuthorizationURL godoc
|
||||
// @Summary 获取OIDC授权地址
|
||||
// @Description 根据后端OIDC配置生成第三方登录跳转地址
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param redirect_uri query string true "OIDC回调地址"
|
||||
// @Success 200 {object} types.OIDCAuthURLResponse
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "OIDC未启用"
|
||||
// @Router /auth/oidc/url [get]
|
||||
func (h *AuthHandler) GetOIDCAuthorizationURL(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
redirectURI := strings.TrimSpace(c.Query("redirect_uri"))
|
||||
if redirectURI == "" {
|
||||
appErr := errors.NewValidationError("redirect_uri is required")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.userService.GetOIDCAuthorizationURL(ctx, redirectURI)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to generate OIDC authorization URL: %v", err)
|
||||
appErr := errors.NewForbiddenError("OIDC authorization unavailable").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// GetOIDCConfig godoc
|
||||
// @Summary 获取OIDC登录配置
|
||||
// @Description 返回OIDC是否启用以及provider展示名称,供前端决定是否展示OIDC登录入口
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} types.OIDCConfigResponse
|
||||
// @Router /auth/oidc/config [get]
|
||||
func (h *AuthHandler) GetOIDCConfig(c *gin.Context) {
|
||||
providerDisplayName := ""
|
||||
enabled := false
|
||||
|
||||
if h.configInfo != nil && h.configInfo.OIDCAuth != nil {
|
||||
enabled = h.configInfo.OIDCAuth.Enable
|
||||
providerDisplayName = strings.TrimSpace(h.configInfo.OIDCAuth.ProviderDisplayName)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, &types.OIDCConfigResponse{
|
||||
Success: true,
|
||||
Enabled: enabled,
|
||||
ProviderDisplayName: providerDisplayName,
|
||||
})
|
||||
}
|
||||
|
||||
// OIDCRedirectCallback godoc
|
||||
// @Summary OIDC登录重定向回调
|
||||
// @Description 接收OIDC provider回调并由后端完成code交换,随后重定向回前端登录页
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param code query string false "OIDC授权码"
|
||||
// @Param state query string false "OIDC状态"
|
||||
// @Param error query string false "OIDC错误码"
|
||||
// @Success 302
|
||||
// @Router /auth/oidc/callback [get]
|
||||
func (h *AuthHandler) OIDCRedirectCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
frontendRedirectURI := "/"
|
||||
|
||||
if providerError := strings.TrimSpace(c.Query("error")); providerError != "" {
|
||||
redirectURL := frontendRedirectURI + "#oidc_error=" + urlQueryEscape(providerError)
|
||||
if description := strings.TrimSpace(c.Query("error_description")); description != "" {
|
||||
redirectURL += "&oidc_error_description=" + urlQueryEscape(description)
|
||||
}
|
||||
c.Redirect(http.StatusFound, redirectURL)
|
||||
return
|
||||
}
|
||||
|
||||
state := strings.TrimSpace(c.Query("state"))
|
||||
decodedState, err := decodeOIDCState(state)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to decode OIDC state: %v", err)
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("invalid_state"))
|
||||
return
|
||||
}
|
||||
|
||||
code := strings.TrimSpace(c.Query("code"))
|
||||
if code == "" {
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("missing_code"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.userService.LoginWithOIDC(ctx, code, strings.TrimSpace(decodedState.RedirectURI))
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to complete OIDC login via redirect callback: %v", err)
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(err.Error()))
|
||||
return
|
||||
}
|
||||
if !resp.Success {
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(resp.Message))
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := encodeOIDCCallbackPayload(resp)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to encode OIDC callback payload: %v", err)
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("payload_encode_failed"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_result="+urlQueryEscape(payload))
|
||||
}
|
||||
|
||||
func encodeOIDCCallbackPayload(resp *types.OIDCCallbackResponse) (string, error) {
|
||||
payload, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(payload), nil
|
||||
}
|
||||
|
||||
type oidcStatePayload struct {
|
||||
Nonce string `json:"nonce"`
|
||||
RedirectURI string `json:"redirect_uri,omitempty"`
|
||||
}
|
||||
|
||||
func decodeOIDCState(raw string) (*oidcStatePayload, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload oidcStatePayload
|
||||
if err := json.Unmarshal(decoded, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(payload.RedirectURI) == "" {
|
||||
return nil, errors.NewValidationError("state.redirect_uri is required")
|
||||
}
|
||||
return &payload, nil
|
||||
}
|
||||
|
||||
func urlQueryEscape(value string) string {
|
||||
replacer := strings.NewReplacer(
|
||||
"%", "%25",
|
||||
" ", "%20",
|
||||
"#", "%23",
|
||||
"&", "%26",
|
||||
"+", "%2B",
|
||||
"=", "%3D",
|
||||
"?", "%3F",
|
||||
)
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
// Logout godoc
|
||||
// @Summary 用户登出
|
||||
// @Description 撤销当前访问令牌并登出
|
||||
|
||||
@@ -18,10 +18,13 @@ import (
|
||||
|
||||
// 无需认证的API列表
|
||||
var noAuthAPI = map[string][]string{
|
||||
"/health": {"GET"},
|
||||
"/api/v1/auth/register": {"POST"},
|
||||
"/api/v1/auth/login": {"POST"},
|
||||
"/api/v1/auth/refresh": {"POST"},
|
||||
"/health": {"GET"},
|
||||
"/api/v1/auth/register": {"POST"},
|
||||
"/api/v1/auth/login": {"POST"},
|
||||
"/api/v1/auth/oidc/config": {"GET"},
|
||||
"/api/v1/auth/oidc/url": {"GET"},
|
||||
"/api/v1/auth/oidc/callback": {"GET"},
|
||||
"/api/v1/auth/refresh": {"POST"},
|
||||
}
|
||||
|
||||
// 检查请求是否在无需认证的API列表中
|
||||
|
||||
@@ -393,6 +393,9 @@ func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHan
|
||||
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
r.POST("/auth/register", handler.Register)
|
||||
r.POST("/auth/login", handler.Login)
|
||||
r.GET("/auth/oidc/config", handler.GetOIDCConfig)
|
||||
r.GET("/auth/oidc/url", handler.GetOIDCAuthorizationURL)
|
||||
r.GET("/auth/oidc/callback", handler.OIDCRedirectCallback)
|
||||
r.POST("/auth/refresh", handler.RefreshToken)
|
||||
r.GET("/auth/validate", handler.ValidateToken)
|
||||
r.POST("/auth/logout", handler.Logout)
|
||||
|
||||
@@ -12,6 +12,10 @@ type UserService interface {
|
||||
Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error)
|
||||
// Login authenticates a user and returns tokens
|
||||
Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error)
|
||||
// GetOIDCAuthorizationURL builds the third-party OIDC authorization URL
|
||||
GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error)
|
||||
// LoginWithOIDC exchanges the callback code, auto-provisions users if needed, and completes login
|
||||
LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error)
|
||||
// GetUserByID gets a user by ID
|
||||
GetUserByID(ctx context.Context, id string) (*types.User, error)
|
||||
// GetUserByEmail gets a user by email
|
||||
|
||||
@@ -64,6 +64,36 @@ type LoginRequest struct {
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
type OIDCAuthURLResponse struct {
|
||||
Success bool `json:"success"`
|
||||
ProviderDisplayName string `json:"provider_display_name,omitempty"`
|
||||
AuthorizationURL string `json:"authorization_url,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
}
|
||||
|
||||
type OIDCConfigResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ProviderDisplayName string `json:"provider_display_name,omitempty"`
|
||||
}
|
||||
|
||||
type OIDCCallbackResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
User *User `json:"user,omitempty"`
|
||||
Tenant *Tenant `json:"tenant,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
IsNewUser bool `json:"is_new_user,omitempty"`
|
||||
}
|
||||
|
||||
type OIDCUserInfo struct {
|
||||
Subject string `json:"subject,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Claims map[string]interface{} `json:"claims,omitempty"`
|
||||
}
|
||||
|
||||
// RegisterRequest represents a registration request
|
||||
type RegisterRequest struct {
|
||||
Username string `json:"username" binding:"required,min=2,max=50"`
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# config.yaml,reference https://github.com/dexidp/dex/blob/master/examples/config-dev.yaml
|
||||
issuer: http://127.0.0.1:5556/dex
|
||||
storage:
|
||||
type: memory
|
||||
web:
|
||||
http: 0.0.0.0:5556
|
||||
staticClients:
|
||||
- id: weknora
|
||||
redirectURIs:
|
||||
- 'http://127.0.0.1:5173/api/v1/auth/oidc/callback'
|
||||
- 'http://127.0.0.1/api/v1/auth/oidc/callback'
|
||||
name: 'WeKnora'
|
||||
# add a "secret" field here
|
||||
enablePasswordDB: true
|
||||
oauth2:
|
||||
responseTypes:
|
||||
- code
|
||||
- id_token
|
||||
- token
|
||||
skipApprovalScreen: true
|
||||
+10
-2
@@ -69,12 +69,14 @@ show_help() {
|
||||
echo " --qdrant 启动 Qdrant 向量数据库"
|
||||
echo " --neo4j 启动 Neo4j 图数据库"
|
||||
echo " --jaeger 启动 Jaeger 链路追踪"
|
||||
echo " --dex 启动 Dex(OIDC 身份认证)"
|
||||
echo " --full 启动所有可选服务"
|
||||
echo ""
|
||||
echo "示例:"
|
||||
echo " $0 start # 启动基础服务"
|
||||
echo " $0 start --qdrant # 启动基础服务 + Qdrant"
|
||||
echo " $0 start --qdrant --jaeger # 启动基础服务 + Qdrant + Jaeger"
|
||||
echo " $0 start --dex # 启动基础服务 + Dex"
|
||||
echo " $0 start --full # 启动所有服务"
|
||||
echo " $0 app # 在另一个终端启动后端"
|
||||
echo " $0 frontend # 在另一个终端启动前端"
|
||||
@@ -140,9 +142,13 @@ start_services() {
|
||||
PROFILES="$PROFILES --profile jaeger"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES jaeger"
|
||||
;;
|
||||
--dex)
|
||||
PROFILES="$PROFILES --profile dex"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES dex"
|
||||
;;
|
||||
--full)
|
||||
PROFILES="--profile full"
|
||||
ENABLED_SERVICES="minio qdrant neo4j jaeger"
|
||||
ENABLED_SERVICES="minio qdrant neo4j jaeger dex"
|
||||
break
|
||||
;;
|
||||
*)
|
||||
@@ -176,6 +182,9 @@ start_services() {
|
||||
if [[ "$ENABLED_SERVICES" == *"jaeger"* ]]; then
|
||||
echo " - Jaeger: localhost:16686"
|
||||
fi
|
||||
if [[ "$ENABLED_SERVICES" == *"dex"* ]]; then
|
||||
echo " - Dex: localhost:5556"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
log_info "接下来的步骤:"
|
||||
@@ -350,4 +359,3 @@ case "$CMD" in
|
||||
esac
|
||||
|
||||
exit 0
|
||||
|
||||
|
||||
Reference in New Issue
Block a user