add oidc
This commit is contained in:
@@ -27,6 +27,13 @@ const (
|
||||
|
||||
// maxLLMRetries is the maximum number of retries for transient LLM errors.
|
||||
maxLLMRetries = 2
|
||||
|
||||
// maxEmptyResponseRetries is the maximum number of retries when the LLM
|
||||
// returns an empty content with a natural stop (no tool calls). This guards
|
||||
// against the agent completing with an empty answer when the LLM fails to
|
||||
// produce content (e.g., thinking-only loops without KB).
|
||||
// Trade-off: each retry costs ~2s of LLM latency; 2 retries = max 4s extra.
|
||||
maxEmptyResponseRetries = 2
|
||||
)
|
||||
|
||||
// transientErrorMarkers are substrings that indicate a transient (retryable) error.
|
||||
|
||||
@@ -270,6 +270,7 @@ func (e *AgentEngine) executeLoop(
|
||||
common.PipelineInfo(ctx, "Agent", "loop_start", map[string]interface{}{
|
||||
"max_iterations": e.config.MaxIterations,
|
||||
})
|
||||
emptyRetries := 0
|
||||
for state.CurrentRound < e.config.MaxIterations {
|
||||
// Check for context cancellation (request timeout, user cancel, etc.)
|
||||
select {
|
||||
@@ -336,6 +337,28 @@ func (e *AgentEngine) executeLoop(
|
||||
// 2. Analyze: Check for stop conditions (natural stop or final_answer tool)
|
||||
verdict := e.analyzeResponse(ctx, response, step, state.CurrentRound, sessionID, roundStart)
|
||||
if verdict.isDone {
|
||||
// Guard against empty content: when the LLM stops naturally with no
|
||||
// content and no tool calls (e.g., thinking-only loop without KB),
|
||||
// retry with a nudge message instead of accepting an empty answer.
|
||||
if verdict.emptyContent {
|
||||
emptyRetries++
|
||||
if emptyRetries <= maxEmptyResponseRetries {
|
||||
logger.Warnf(ctx, "[Agent][Round-%d] Empty content with stop - retrying (%d/%d)",
|
||||
state.CurrentRound+1, emptyRetries, maxEmptyResponseRetries)
|
||||
messages = append(messages, chat.Message{
|
||||
Role: "user",
|
||||
Content: "Please provide your answer by calling the final_answer tool.",
|
||||
})
|
||||
continue
|
||||
}
|
||||
// Retries exhausted — use fallback message rather than empty answer
|
||||
logger.Warnf(ctx, "[Agent][Round-%d] Empty content after %d retries - using fallback",
|
||||
state.CurrentRound+1, maxEmptyResponseRetries)
|
||||
state.FinalAnswer = "I'm sorry, I was unable to generate a response. Please try again."
|
||||
state.IsComplete = true
|
||||
state.RoundSteps = append(state.RoundSteps, verdict.step)
|
||||
break
|
||||
}
|
||||
state.FinalAnswer = verdict.finalAnswer
|
||||
state.IsComplete = true
|
||||
state.RoundSteps = append(state.RoundSteps, verdict.step)
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock: chat.Chat
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type mockResponse struct {
|
||||
chunks []types.StreamResponse
|
||||
}
|
||||
|
||||
type mockChat struct {
|
||||
mu sync.Mutex
|
||||
responses []mockResponse
|
||||
callCount int
|
||||
}
|
||||
|
||||
func (m *mockChat) ChatStream(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.callCount >= len(m.responses) {
|
||||
return nil, fmt.Errorf("unexpected ChatStream call #%d (only %d responses prepared)", m.callCount, len(m.responses))
|
||||
}
|
||||
resp := m.responses[m.callCount]
|
||||
m.callCount++
|
||||
|
||||
ch := make(chan types.StreamResponse, len(resp.chunks))
|
||||
for _, chunk := range resp.chunks {
|
||||
ch <- chunk
|
||||
}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (m *mockChat) Chat(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
|
||||
return nil, fmt.Errorf("not implemented")
|
||||
}
|
||||
|
||||
func (m *mockChat) GetModelName() string { return "mock-model" }
|
||||
func (m *mockChat) GetModelID() string { return "mock-id" }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type testEngineOption func(*types.AgentConfig)
|
||||
|
||||
func withMaxIterations(n int) testEngineOption {
|
||||
return func(cfg *types.AgentConfig) {
|
||||
cfg.MaxIterations = n
|
||||
}
|
||||
}
|
||||
|
||||
func newTestEngine(t *testing.T, chatModel chat.Chat, opts ...testEngineOption) *AgentEngine {
|
||||
t.Helper()
|
||||
cfg := &types.AgentConfig{
|
||||
MaxIterations: 10,
|
||||
Temperature: 0.7,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
engine := NewAgentEngine(
|
||||
cfg,
|
||||
chatModel,
|
||||
nil,
|
||||
event.NewEventBus(),
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
"test-session",
|
||||
"",
|
||||
)
|
||||
require.NotNil(t, engine, "NewAgentEngine returned nil (agenttoken.NewEstimator failed?)")
|
||||
return engine
|
||||
}
|
||||
|
||||
func emptyMessages() []chat.Message {
|
||||
return []chat.Message{
|
||||
{Role: "system", Content: "You are a test agent."},
|
||||
{Role: "user", Content: "test query"},
|
||||
}
|
||||
}
|
||||
|
||||
func emptyTools() []chat.Tool {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TC1: Empty content + stop → should NOT complete with empty FinalAnswer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestExecuteLoop_EmptyContentWithStop_ShouldNotCompleteWithEmpty(t *testing.T) {
|
||||
// Simulate: LLM returns empty content with no tool calls (natural stop).
|
||||
// The stream closes with no content chunks → streamLLMToEventBus returns fullContent="".
|
||||
// streamThinkingToEventBus wraps it as ChatResponse{Content:"", FinishReason:"stop"}.
|
||||
// analyzeResponse() returns verdict{isDone:true, finalAnswer:""} → BUG: empty answer.
|
||||
//
|
||||
// Prepare 3 responses for initial attempt + 2 retries (after fix).
|
||||
mock := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{chunks: []types.StreamResponse{{Done: true}}},
|
||||
{chunks: []types.StreamResponse{{Done: true}}},
|
||||
{chunks: []types.StreamResponse{{Done: true}}},
|
||||
},
|
||||
}
|
||||
|
||||
engine := newTestEngine(t, mock)
|
||||
state := &types.AgentState{}
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := engine.executeLoop(ctx, state, "test query", emptyMessages(), emptyTools(), "sess-1", "msg-1")
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, state.IsComplete)
|
||||
assert.NotEmpty(t, state.FinalAnswer,
|
||||
"BUG: FinalAnswer is empty when LLM returns empty content with stop. "+
|
||||
"analyzeResponse() should not allow empty content to be accepted as final answer.")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TC2: Non-empty content + stop → normal completion (regression guard)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestExecuteLoop_NonEmptyContentWithStop_ShouldComplete(t *testing.T) {
|
||||
mock := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{chunks: []types.StreamResponse{
|
||||
{Content: "Here is my answer", Done: true},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
engine := newTestEngine(t, mock)
|
||||
state := &types.AgentState{}
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := engine.executeLoop(ctx, state, "test query", emptyMessages(), emptyTools(), "sess-1", "msg-1")
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, state.IsComplete)
|
||||
assert.Equal(t, "Here is my answer", state.FinalAnswer)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TC4: Empty → retry with nudge → non-empty → success
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestExecuteLoop_EmptyThenNonEmpty_ShouldRetryAndComplete(t *testing.T) {
|
||||
mock := &mockChat{
|
||||
responses: []mockResponse{
|
||||
// Round 1: empty content → triggers retry + nudge
|
||||
{chunks: []types.StreamResponse{{Done: true}}},
|
||||
// Round 2: after nudge, LLM produces answer
|
||||
{chunks: []types.StreamResponse{
|
||||
{Content: "Here is the answer.", Done: true},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
engine := newTestEngine(t, mock)
|
||||
state := &types.AgentState{}
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := engine.executeLoop(ctx, state, "test query", emptyMessages(), emptyTools(), "sess-1", "msg-1")
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, state.IsComplete)
|
||||
assert.Equal(t, "Here is the answer.", state.FinalAnswer)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TC5: FinishReason propagation through streamThinkingToEventBus
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestStreamThinkingToEventBus_PropagatesFinishReason(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
finishReason string
|
||||
wantReason string
|
||||
}{
|
||||
{"stop", "stop", "stop"},
|
||||
{"tool_calls", "tool_calls", "tool_calls"},
|
||||
{"length", "length", "length"},
|
||||
{"empty_fallback", "", "stop"}, // empty FinishReason → fallback to "stop"
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mock := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{chunks: []types.StreamResponse{
|
||||
{Content: "test content", Done: true, FinishReason: tt.finishReason},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
engine := newTestEngine(t, mock)
|
||||
ctx := context.Background()
|
||||
msgs := []chat.Message{{Role: "user", Content: "test"}}
|
||||
tools := []chat.Tool{}
|
||||
|
||||
resp, err := engine.streamThinkingToEventBus(ctx, msgs, tools, 0, "sess-1")
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.wantReason, resp.FinishReason)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -51,9 +51,10 @@ func (e *AgentEngine) manageContextWindow(ctx context.Context, messages []chat.M
|
||||
// responseVerdict captures the result of analyzing an LLM response to determine
|
||||
// whether the agent loop should stop and what the final answer is (if any).
|
||||
type responseVerdict struct {
|
||||
isDone bool
|
||||
finalAnswer string
|
||||
step types.AgentStep
|
||||
isDone bool
|
||||
finalAnswer string
|
||||
emptyContent bool // LLM returned stop with no tool calls and empty content
|
||||
step types.AgentStep
|
||||
}
|
||||
|
||||
// analyzeResponse inspects the LLM response for stop conditions:
|
||||
@@ -102,9 +103,10 @@ func (e *AgentEngine) analyzeResponse(
|
||||
})
|
||||
|
||||
return responseVerdict{
|
||||
isDone: true,
|
||||
finalAnswer: response.Content,
|
||||
step: step,
|
||||
isDone: true,
|
||||
finalAnswer: response.Content,
|
||||
emptyContent: response.Content == "",
|
||||
step: step,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+17
-4
@@ -15,9 +15,10 @@ import (
|
||||
|
||||
// streamLLMResult holds accumulated output from a streaming LLM call.
|
||||
type streamLLMResult struct {
|
||||
Content string
|
||||
ToolCalls []types.LLMToolCall
|
||||
Usage *types.TokenUsage
|
||||
Content string
|
||||
ToolCalls []types.LLMToolCall
|
||||
Usage *types.TokenUsage
|
||||
FinishReason string // actual finish_reason from LLM (captured from last stream chunk)
|
||||
}
|
||||
|
||||
// streamLLMToEventBus streams LLM response through EventBus (generic method)
|
||||
@@ -66,6 +67,10 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
result.Usage = chunk.Usage
|
||||
}
|
||||
|
||||
if chunk.FinishReason != "" {
|
||||
result.FinishReason = chunk.FinishReason
|
||||
}
|
||||
|
||||
if emitFunc != nil {
|
||||
emitFunc(&chunk, result.Content)
|
||||
}
|
||||
@@ -205,10 +210,18 @@ func (e *AgentEngine) streamThinkingToEventBus(
|
||||
|
||||
fullContent := agenttools.StripThinkBlocks(llmResult.Content)
|
||||
|
||||
// Use actual finish_reason from LLM stream instead of hardcoding "stop".
|
||||
// Fallback to "stop" when the stream did not report a finish_reason
|
||||
// (e.g., certain Ollama models or providers that omit the field).
|
||||
finishReason := llmResult.FinishReason
|
||||
if finishReason == "" {
|
||||
finishReason = "stop"
|
||||
}
|
||||
|
||||
resp := &types.ChatResponse{
|
||||
Content: fullContent,
|
||||
ToolCalls: llmResult.ToolCalls,
|
||||
FinishReason: "stop",
|
||||
FinishReason: finishReason,
|
||||
}
|
||||
if llmResult.Usage != nil {
|
||||
resp.Usage = *llmResult.Usage
|
||||
|
||||
@@ -12,6 +12,15 @@ import (
|
||||
|
||||
var ErrKnowledgeNotFound = errors.New("knowledge not found")
|
||||
|
||||
// escapeLikeKeyword escapes SQL LIKE wildcards (%, _) in a keyword
|
||||
// so they are treated as literal characters.
|
||||
func escapeLikeKeyword(keyword string) string {
|
||||
keyword = strings.ReplaceAll(keyword, `\`, `\\`)
|
||||
keyword = strings.ReplaceAll(keyword, "%", `\%`)
|
||||
keyword = strings.ReplaceAll(keyword, "_", `\_`)
|
||||
return keyword
|
||||
}
|
||||
|
||||
// omitFieldsOnUpdate defines fields to omit when updating knowledge
|
||||
var omitFieldsOnUpdate = []string{"DeletedAt"}
|
||||
|
||||
@@ -90,7 +99,8 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
|
||||
query = query.Where("tag_id = ?", tagID)
|
||||
}
|
||||
if keyword != "" {
|
||||
query = query.Where("(file_name LIKE ? OR title LIKE ?)", "%"+keyword+"%", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
query = query.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
if fileType != "" {
|
||||
if fileType == "manual" {
|
||||
@@ -108,13 +118,14 @@ func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
|
||||
}
|
||||
|
||||
// Then query paginated data
|
||||
dataQuery := r.db.WithContext(ctx).
|
||||
dataQuery := r.db.Debug().WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if tagID != "" {
|
||||
dataQuery = dataQuery.Where("tag_id = ?", tagID)
|
||||
}
|
||||
if keyword != "" {
|
||||
dataQuery = dataQuery.Where("(file_name LIKE ? OR title LIKE ?)", "%"+keyword+"%", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
dataQuery = dataQuery.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
if fileType != "" {
|
||||
if fileType == "manual" {
|
||||
@@ -313,6 +324,29 @@ func (r *knowledgeRepository) CountKnowledgeByStatus(
|
||||
// If keyword is empty, returns recent files
|
||||
// Only returns documents from document-type knowledge bases (excludes FAQ)
|
||||
// Returns (results, hasMore, error)
|
||||
// FindByMetadataKey finds a knowledge item by a key-value pair in the metadata JSON column.
|
||||
// Uses Postgres jsonb operator: metadata->>'key' = 'value'.
|
||||
func (r *knowledgeRepository) FindByMetadataKey(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
key string,
|
||||
value string,
|
||||
) (*types.Knowledge, error) {
|
||||
var knowledge types.Knowledge
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ? AND deleted_at IS NULL", tenantID, kbID).
|
||||
Where("metadata->>? = ?", key, value).
|
||||
First(&knowledge).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &knowledge, nil
|
||||
}
|
||||
|
||||
func (r *knowledgeRepository) SearchKnowledge(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
@@ -337,7 +371,8 @@ func (r *knowledgeRepository) SearchKnowledge(
|
||||
|
||||
// If keyword is provided, filter by file_name or title
|
||||
if keyword != "" {
|
||||
query = query.Where("(knowledges.file_name LIKE ? OR knowledges.title LIKE ?)", "%"+keyword+"%", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
query = query.Where("(knowledges.file_name LIKE ? OR knowledges.title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
|
||||
// If fileTypes is provided, filter by file extension or type
|
||||
@@ -455,7 +490,8 @@ func (r *knowledgeRepository) SearchKnowledgeInScopes(
|
||||
Where("knowledges.deleted_at IS NULL")
|
||||
|
||||
if keyword != "" {
|
||||
query = query.Where("(knowledges.file_name LIKE ? OR knowledges.title LIKE ?)", "%"+keyword+"%", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
query = query.Where("(knowledges.file_name LIKE ? OR knowledges.title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
|
||||
if len(fileTypes) > 0 {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
// 加载每个模板文件
|
||||
|
||||
@@ -56,6 +56,7 @@ import (
|
||||
imPkg "github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/im/dingtalk"
|
||||
"github.com/Tencent/WeKnora/internal/im/feishu"
|
||||
"github.com/Tencent/WeKnora/internal/im/mattermost"
|
||||
"github.com/Tencent/WeKnora/internal/im/slack"
|
||||
"github.com/Tencent/WeKnora/internal/im/telegram"
|
||||
"github.com/Tencent/WeKnora/internal/im/wecom"
|
||||
@@ -1171,6 +1172,40 @@ func registerIMAdapterFactories(imService *imPkg.Service) {
|
||||
}
|
||||
})
|
||||
|
||||
// Register Mattermost adapter factory (outgoing webhook + REST API).
|
||||
imService.RegisterAdapterFactory("mattermost", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) {
|
||||
creds, err := parseCredentials(channel.Credentials)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("parse mattermost credentials: %w", err)
|
||||
}
|
||||
|
||||
mode := channel.Mode
|
||||
if mode == "" {
|
||||
mode = "webhook"
|
||||
}
|
||||
if mode != "webhook" {
|
||||
return nil, nil, fmt.Errorf("unsupported mattermost mode: %s (only webhook is supported)", mode)
|
||||
}
|
||||
|
||||
siteURL := getString(creds, "site_url")
|
||||
botToken := getString(creds, "bot_token")
|
||||
outgoingToken := getString(creds, "outgoing_token")
|
||||
botUserID := getString(creds, "bot_user_id")
|
||||
|
||||
if outgoingToken == "" {
|
||||
return nil, nil, fmt.Errorf("mattermost outgoing_token is required")
|
||||
}
|
||||
|
||||
client, err := mattermost.NewClient(siteURL, botToken)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
postReplyToMain := credentialBool(creds, "post_to_main")
|
||||
adapter := mattermost.NewAdapter(client, outgoingToken, botUserID, postReplyToMain)
|
||||
return adapter, func() {}, nil
|
||||
})
|
||||
|
||||
// Load and start all enabled channels from database
|
||||
if err := imService.LoadAndStartChannels(); err != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to load channels from database: %v", err)
|
||||
@@ -1198,3 +1233,24 @@ func getString(creds map[string]interface{}, key string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// credentialBool reads a boolean from JSON credentials (bool, string "true"/"1", or non-zero number).
|
||||
func credentialBool(creds map[string]interface{}, key string) bool {
|
||||
v, ok := creds[key]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case bool:
|
||||
return x
|
||||
case string:
|
||||
s := strings.TrimSpace(strings.ToLower(x))
|
||||
return s == "true" || s == "1" || s == "yes"
|
||||
case float64:
|
||||
return x != 0
|
||||
case int:
|
||||
return x != 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 撤销当前访问令牌并登出
|
||||
|
||||
+16
-3
@@ -12,7 +12,9 @@ import (
|
||||
)
|
||||
|
||||
// validIMPlatforms is the set of supported IM platforms.
|
||||
var validIMPlatforms = map[string]bool{"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true}
|
||||
var validIMPlatforms = map[string]bool{
|
||||
"wecom": true, "feishu": true, "slack": true, "telegram": true, "dingtalk": true, "mattermost": true,
|
||||
}
|
||||
|
||||
// IMHandler handles IM platform callback requests and channel CRUD.
|
||||
type IMHandler struct {
|
||||
@@ -57,7 +59,7 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
}
|
||||
|
||||
if !validIMPlatforms[req.Platform] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram' or 'dingtalk'"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack', 'telegram', 'dingtalk' or 'mattermost'"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -76,7 +78,11 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
|
||||
channel.Enabled = *req.Enabled
|
||||
}
|
||||
if channel.Mode == "" {
|
||||
channel.Mode = "websocket"
|
||||
if channel.Platform == "mattermost" {
|
||||
channel.Mode = "webhook"
|
||||
} else {
|
||||
channel.Mode = "websocket"
|
||||
}
|
||||
}
|
||||
if channel.OutputMode == "" {
|
||||
channel.OutputMode = "stream"
|
||||
@@ -265,6 +271,8 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[IM] Callback received platform=%s path_channel_id=%s", channel.Platform, channelID)
|
||||
|
||||
// Handle URL verification
|
||||
if adapter.HandleURLVerification(c) {
|
||||
return
|
||||
@@ -287,6 +295,11 @@ func (h *IMHandler) IMCallback(c *gin.Context) {
|
||||
|
||||
// If nil, it's a non-message event - just acknowledge
|
||||
if msg == nil {
|
||||
if channel.Platform == "mattermost" {
|
||||
logger.Infof(ctx, "[IM] Mattermost callback ignored (no message): path_channel_id=%s — check: (1) trigger word must be the *first word* of the post; (2) if channel+trigger are both set, post must be in that channel; (3) bot_user_id must not match the sender", channelID)
|
||||
} else {
|
||||
logger.Infof(ctx, "[IM] Callback parsed no message to process platform=%s path_channel_id=%s", channel.Platform, channelID)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -11,11 +11,12 @@ import (
|
||||
type Platform string
|
||||
|
||||
const (
|
||||
PlatformWeCom Platform = "wecom"
|
||||
PlatformFeishu Platform = "feishu"
|
||||
PlatformSlack Platform = "slack"
|
||||
PlatformTelegram Platform = "telegram"
|
||||
PlatformDingtalk Platform = "dingtalk"
|
||||
PlatformWeCom Platform = "wecom"
|
||||
PlatformFeishu Platform = "feishu"
|
||||
PlatformSlack Platform = "slack"
|
||||
PlatformTelegram Platform = "telegram"
|
||||
PlatformDingtalk Platform = "dingtalk"
|
||||
PlatformMattermost Platform = "mattermost"
|
||||
)
|
||||
|
||||
// MessageType identifies the kind of IM message.
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
package mattermost
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// Compile-time checks.
|
||||
var (
|
||||
_ im.Adapter = (*Adapter)(nil)
|
||||
_ im.StreamSender = (*Adapter)(nil)
|
||||
_ im.FileDownloader = (*Adapter)(nil)
|
||||
)
|
||||
|
||||
const (
|
||||
extraKeyThreadRoot = "thread_root_id"
|
||||
extraKeyChannelID = "channel_id"
|
||||
)
|
||||
|
||||
// Adapter implements im integration for Mattermost (outgoing webhook inbound + REST outbound).
|
||||
type Adapter struct {
|
||||
client *Client
|
||||
outgoingToken string
|
||||
botUserID string
|
||||
// postReplyToMain: when true, bot replies are new top-level channel posts (visible in main timeline).
|
||||
// When false (default), replies use root_id tied to the trigger post so they appear in Mattermost threads.
|
||||
postReplyToMain bool
|
||||
}
|
||||
|
||||
// NewAdapter creates a Mattermost adapter.
|
||||
func NewAdapter(client *Client, outgoingToken, botUserID string, postReplyToMain bool) *Adapter {
|
||||
return &Adapter{
|
||||
client: client,
|
||||
outgoingToken: strings.TrimSpace(outgoingToken),
|
||||
botUserID: strings.TrimSpace(botUserID),
|
||||
postReplyToMain: postReplyToMain,
|
||||
}
|
||||
}
|
||||
|
||||
// outgoingPayload matches Mattermost outgoing webhook parameters (JSON or form).
|
||||
type outgoingPayload struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"user_id"`
|
||||
UserName string `json:"user_name"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
PostID string `json:"post_id"`
|
||||
Text string `json:"text"`
|
||||
RootID string `json:"root_id"`
|
||||
FileIDsRaw json.RawMessage `json:"file_ids"`
|
||||
}
|
||||
|
||||
func (a *Adapter) Platform() im.Platform {
|
||||
return im.PlatformMattermost
|
||||
}
|
||||
|
||||
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *Adapter) VerifyCallback(c *gin.Context) error {
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read body: %w", err)
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
payload, err := parseOutgoingBody(c.Request.Header.Get("Content-Type"), bodyBytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse outgoing payload: %w", err)
|
||||
}
|
||||
|
||||
if a.outgoingToken != "" && payload.Token != a.outgoingToken {
|
||||
return fmt.Errorf("invalid outgoing webhook token")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read body: %w", err)
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
payload, err := parseOutgoingBody(c.Request.Header.Get("Content-Type"), bodyBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if a.botUserID != "" && payload.UserID == a.botUserID {
|
||||
logger.Infof(c.Request.Context(), "[Mattermost] Skip callback: user_id matches bot_user_id (avoid self-reply loop)")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if strings.TrimSpace(payload.Text) == "" && len(parseFileIDs(payload.FileIDsRaw)) == 0 {
|
||||
logger.Infof(c.Request.Context(), "[Mattermost] Skip callback: empty text and no file_ids")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var threadRoot string
|
||||
if a.postReplyToMain {
|
||||
threadRoot = ""
|
||||
} else {
|
||||
threadRoot = payload.RootID
|
||||
if threadRoot == "" {
|
||||
threadRoot = payload.PostID
|
||||
}
|
||||
}
|
||||
|
||||
msg := &im.IncomingMessage{
|
||||
Platform: im.PlatformMattermost,
|
||||
UserID: payload.UserID,
|
||||
UserName: payload.UserName,
|
||||
ChatID: payload.ChannelID,
|
||||
ChatType: im.ChatTypeGroup,
|
||||
Content: strings.TrimSpace(payload.Text),
|
||||
MessageID: payload.PostID,
|
||||
Extra: map[string]string{
|
||||
extraKeyThreadRoot: threadRoot,
|
||||
extraKeyChannelID: payload.ChannelID,
|
||||
},
|
||||
}
|
||||
|
||||
fileIDs := parseFileIDs(payload.FileIDsRaw)
|
||||
if len(fileIDs) > 0 {
|
||||
msg.MessageType = im.MessageTypeFile
|
||||
msg.FileKey = fileIDs[0]
|
||||
if len(fileIDs) > 1 {
|
||||
msg.Extra["file_ids"] = strings.Join(fileIDs, ",")
|
||||
}
|
||||
} else {
|
||||
msg.MessageType = im.MessageTypeText
|
||||
}
|
||||
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func parseOutgoingBody(contentType string, body []byte) (*outgoingPayload, error) {
|
||||
ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
|
||||
|
||||
switch {
|
||||
case ct == "application/json" || strings.HasSuffix(ct, "+json"):
|
||||
var p outgoingPayload
|
||||
if err := json.Unmarshal(body, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
|
||||
case ct == "application/x-www-form-urlencoded" || ct == "":
|
||||
// Parse as form (Mattermost default for some configs).
|
||||
values, err := parseFormBody(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := &outgoingPayload{
|
||||
Token: values.Get("token"),
|
||||
UserID: values.Get("user_id"),
|
||||
UserName: values.Get("user_name"),
|
||||
ChannelID: values.Get("channel_id"),
|
||||
PostID: values.Get("post_id"),
|
||||
Text: values.Get("text"),
|
||||
RootID: values.Get("root_id"),
|
||||
}
|
||||
if f := values.Get("file_ids"); f != "" {
|
||||
p.FileIDsRaw = json.RawMessage(jsonArrayFromCSV(f))
|
||||
}
|
||||
return p, nil
|
||||
|
||||
default:
|
||||
// Try JSON fallback for unknown types.
|
||||
var p outgoingPayload
|
||||
if err := json.Unmarshal(body, &p); err == nil && (p.Token != "" || p.ChannelID != "") {
|
||||
return &p, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unsupported content-type: %s", contentType)
|
||||
}
|
||||
}
|
||||
|
||||
func parseFileIDs(raw json.RawMessage) []string {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var arr []string
|
||||
if err := json.Unmarshal(raw, &arr); err == nil {
|
||||
return arr
|
||||
}
|
||||
var s string
|
||||
if err := json.Unmarshal(raw, &s); err == nil && s != "" {
|
||||
return splitFileIDs(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func splitFileIDs(s string) []string {
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
channelID := incoming.ChatID
|
||||
if channelID == "" {
|
||||
channelID = incoming.Extra[extraKeyChannelID]
|
||||
}
|
||||
if channelID == "" {
|
||||
return fmt.Errorf("missing channel_id")
|
||||
}
|
||||
|
||||
threadRoot := ""
|
||||
if incoming.Extra != nil {
|
||||
threadRoot = incoming.Extra[extraKeyThreadRoot]
|
||||
}
|
||||
|
||||
_, err := a.client.CreatePost(ctx, channelID, threadRoot, reply.Content)
|
||||
return err
|
||||
}
|
||||
|
||||
type mmStreamState struct {
|
||||
mu sync.Mutex
|
||||
content strings.Builder
|
||||
postID string
|
||||
channel string
|
||||
}
|
||||
|
||||
var (
|
||||
mmStreamsMu sync.Mutex
|
||||
mmStreams = map[string]*mmStreamState{}
|
||||
)
|
||||
|
||||
func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
|
||||
channelID := incoming.ChatID
|
||||
if channelID == "" {
|
||||
channelID = incoming.Extra[extraKeyChannelID]
|
||||
}
|
||||
threadRoot := ""
|
||||
if incoming.Extra != nil {
|
||||
threadRoot = incoming.Extra[extraKeyThreadRoot]
|
||||
}
|
||||
|
||||
postID, err := a.client.CreatePost(ctx, channelID, threadRoot, "正在思考...")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
streamID := channelID + ":" + postID
|
||||
mmStreamsMu.Lock()
|
||||
mmStreams[streamID] = &mmStreamState{postID: postID, channel: channelID}
|
||||
mmStreamsMu.Unlock()
|
||||
|
||||
logger.Infof(ctx, "[Mattermost] Streaming started: stream_id=%s", streamID)
|
||||
return streamID, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
|
||||
if content == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
mmStreamsMu.Lock()
|
||||
state, ok := mmStreams[streamID]
|
||||
mmStreamsMu.Unlock()
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown stream ID: %s", streamID)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
state.content.WriteString(content)
|
||||
full := state.content.String()
|
||||
postID := state.postID
|
||||
state.mu.Unlock()
|
||||
|
||||
if err := a.client.PatchPostMessage(ctx, postID, full); err != nil {
|
||||
logger.Warnf(ctx, "[Mattermost] Patch post failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
|
||||
mmStreamsMu.Lock()
|
||||
state, ok := mmStreams[streamID]
|
||||
delete(mmStreams, streamID)
|
||||
mmStreamsMu.Unlock()
|
||||
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
full := state.content.String()
|
||||
postID := state.postID
|
||||
state.mu.Unlock()
|
||||
|
||||
if err := a.client.PatchPostMessage(ctx, postID, full); err != nil {
|
||||
logger.Warnf(ctx, "[Mattermost] EndStream patch failed: %v", err)
|
||||
}
|
||||
logger.Infof(ctx, "[Mattermost] Streaming ended: post_id=%s", postID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) {
|
||||
if msg.FileKey == "" {
|
||||
return nil, "", fmt.Errorf("file_key is required")
|
||||
}
|
||||
|
||||
info, err := a.client.GetFileInfo(ctx, msg.FileKey)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("file info: %w", err)
|
||||
}
|
||||
|
||||
name := info.Name
|
||||
if name == "" {
|
||||
name = msg.FileName
|
||||
}
|
||||
if name == "" {
|
||||
name = msg.FileKey
|
||||
}
|
||||
|
||||
rc, err := a.client.GetFileReader(ctx, msg.FileKey)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return rc, name, nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package mattermost
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client calls Mattermost REST API v4.
|
||||
type Client struct {
|
||||
baseURL string
|
||||
httpClient *http.Client
|
||||
token string
|
||||
}
|
||||
|
||||
// NewClient builds an API client. siteURL is the Mattermost server root (e.g. https://mm.example.com).
|
||||
func NewClient(siteURL, botToken string) (*Client, error) {
|
||||
siteURL = strings.TrimSpace(siteURL)
|
||||
siteURL = strings.TrimRight(siteURL, "/")
|
||||
if siteURL == "" {
|
||||
return nil, fmt.Errorf("site_url is required")
|
||||
}
|
||||
if strings.TrimSpace(botToken) == "" {
|
||||
return nil, fmt.Errorf("bot_token is required")
|
||||
}
|
||||
return &Client{
|
||||
baseURL: siteURL + "/api/v4",
|
||||
httpClient: &http.Client{
|
||||
Timeout: 60 * time.Second,
|
||||
},
|
||||
token: strings.TrimSpace(botToken),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) authHeader(req *http.Request) {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
// CreatePost creates a channel post. rootID is the thread root post id (empty for new top-level post).
|
||||
func (c *Client) CreatePost(ctx context.Context, channelID, rootID, message string) (postID string, err error) {
|
||||
body := map[string]string{
|
||||
"channel_id": channelID,
|
||||
"message": message,
|
||||
}
|
||||
if rootID != "" {
|
||||
body["root_id"] = rootID
|
||||
}
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/posts", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
c.authHeader(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
if resp.StatusCode == http.StatusForbidden {
|
||||
return "", fmt.Errorf("mattermost create post: 403 forbidden — add the bot user to this Mattermost channel (Channel menu → Members → Add); body=%s", truncateForErr(respBody))
|
||||
}
|
||||
return "", fmt.Errorf("mattermost create post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
|
||||
}
|
||||
|
||||
var created struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(respBody, &created); err != nil {
|
||||
return "", fmt.Errorf("decode create post: %w", err)
|
||||
}
|
||||
if created.ID == "" {
|
||||
return "", fmt.Errorf("mattermost create post: empty id")
|
||||
}
|
||||
return created.ID, nil
|
||||
}
|
||||
|
||||
// PatchPostMessage updates a post's message field.
|
||||
func (c *Client) PatchPostMessage(ctx context.Context, postID, message string) error {
|
||||
payload, err := json.Marshal(map[string]string{"message": message})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s/posts/%s/patch", c.baseURL, postID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.authHeader(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("mattermost patch post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FileInfo holds metadata from GET /files/{id}/info.
|
||||
type FileInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
// GetFileInfo fetches file metadata.
|
||||
func (c *Client) GetFileInfo(ctx context.Context, fileID string) (*FileInfo, error) {
|
||||
url := fmt.Sprintf("%s/files/%s/info", c.baseURL, fileID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.authHeader(req)
|
||||
req.Header.Del("Content-Type")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("mattermost file info: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
|
||||
}
|
||||
|
||||
var info FileInfo
|
||||
if err := json.Unmarshal(respBody, &info); err != nil {
|
||||
return nil, fmt.Errorf("decode file info: %w", err)
|
||||
}
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// GetFileReader opens a download stream for file content.
|
||||
func (c *Client) GetFileReader(ctx context.Context, fileID string) (io.ReadCloser, error) {
|
||||
url := fmt.Sprintf("%s/files/%s", c.baseURL, fileID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.authHeader(req)
|
||||
req.Header.Del("Content-Type")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("mattermost get file: status=%d body=%s", resp.StatusCode, truncateForErr(body))
|
||||
}
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
func truncateForErr(b []byte) string {
|
||||
const max = 512
|
||||
s := string(b)
|
||||
if len(s) > max {
|
||||
return s[:max] + "..."
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package mattermost
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func parseFormBody(body []byte) (url.Values, error) {
|
||||
values, err := url.ParseQuery(string(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse form: %w", err)
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func jsonArrayFromCSV(csv string) []byte {
|
||||
parts := splitFileIDs(csv)
|
||||
if len(parts) == 0 {
|
||||
return []byte("[]")
|
||||
}
|
||||
b, err := json.Marshal(parts)
|
||||
if err != nil {
|
||||
return []byte("[]")
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -39,7 +39,11 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {
|
||||
ch.ID = uuid.New().String()
|
||||
}
|
||||
if ch.Mode == "" {
|
||||
ch.Mode = "websocket"
|
||||
if ch.Platform == "mattermost" {
|
||||
ch.Mode = "webhook"
|
||||
} else {
|
||||
ch.Mode = "websocket"
|
||||
}
|
||||
}
|
||||
if ch.OutputMode == "" {
|
||||
ch.OutputMode = "stream"
|
||||
@@ -104,6 +108,10 @@ func (ch *IMChannel) computeBotIdentity() string {
|
||||
if clientID := str("client_id"); clientID != "" {
|
||||
return "dingtalk:" + clientID
|
||||
}
|
||||
case "mattermost":
|
||||
if tok := str("outgoing_token"); tok != "" {
|
||||
return "mattermost:wh:" + tok
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -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列表中
|
||||
|
||||
@@ -510,6 +510,7 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
|
||||
Done: true,
|
||||
ToolCalls: state.buildOrderedToolCalls(),
|
||||
Usage: state.usage,
|
||||
FinishReason: state.lastFinishReason,
|
||||
}
|
||||
} else {
|
||||
streamChan <- types.StreamResponse{
|
||||
@@ -633,6 +634,7 @@ type streamState struct {
|
||||
hasThinking bool
|
||||
fieldExtractors map[int]*jsonFieldExtractor // per tool-call-index extractors for streaming field extraction
|
||||
usage *types.TokenUsage // captured from the final stream chunk when include_usage is enabled
|
||||
lastFinishReason string // last observed finish_reason for EOF handler fallback
|
||||
}
|
||||
|
||||
func newStreamState() *streamState {
|
||||
@@ -666,6 +668,11 @@ func (c *RemoteAPIChat) processStreamDelta(ctx context.Context, choice *openai.C
|
||||
delta := choice.Delta
|
||||
isDone := string(choice.FinishReason) != ""
|
||||
|
||||
// Track finish_reason for EOF handler fallback
|
||||
if isDone {
|
||||
state.lastFinishReason = string(choice.FinishReason)
|
||||
}
|
||||
|
||||
// 处理 tool calls
|
||||
if len(delta.ToolCalls) > 0 {
|
||||
c.processToolCallsDelta(ctx, delta.ToolCalls, state, streamChan)
|
||||
@@ -698,6 +705,7 @@ func (c *RemoteAPIChat) processStreamDelta(ctx context.Context, choice *openai.C
|
||||
Content: delta.Content,
|
||||
Done: isDone,
|
||||
ToolCalls: state.buildOrderedToolCalls(),
|
||||
FinishReason: string(choice.FinishReason),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -707,6 +715,7 @@ func (c *RemoteAPIChat) processStreamDelta(ctx context.Context, choice *openai.C
|
||||
Content: "",
|
||||
Done: true,
|
||||
ToolCalls: state.buildOrderedToolCalls(),
|
||||
FinishReason: string(choice.FinishReason),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -720,6 +729,17 @@ func (c *RemoteAPIChat) processStreamDelta(ctx context.Context, choice *openai.C
|
||||
}
|
||||
state.hasThinking = false
|
||||
}
|
||||
|
||||
// Catch-all: isDone but none of the above branches sent a response with
|
||||
// FinishReason (empty content, no tool calls, no thinking). This prevents
|
||||
// the finish_reason from being lost in the streaming pipeline.
|
||||
if isDone && delta.Content == "" && len(state.toolCallMap) == 0 && !state.hasThinking {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: string(choice.FinishReason),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// processToolCallsDelta 处理 tool calls 的增量更新
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -71,6 +71,7 @@ type StreamResponse struct {
|
||||
ToolCalls []LLMToolCall `json:"tool_calls,omitempty"`
|
||||
Data map[string]interface{} `json:"data,omitempty"`
|
||||
Usage *TokenUsage `json:"usage,omitempty"`
|
||||
FinishReason string `json:"finish_reason,omitempty"`
|
||||
}
|
||||
|
||||
// References references
|
||||
|
||||
@@ -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"`
|
||||
|
||||
Reference in New Issue
Block a user