add oidc
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user