feat: add user token secret management for channels
- Implemented user token secret generation and retrieval in channel service. - Added ResetUserTokenSecret method to reset the user token secret for channels. - Updated channel configuration parsing to include user token secret. - Enhanced WebSocket service to utilize user token secret for external info retrieval. - Modified dashboard channel edit component to support user token secret display and reset functionality. - Introduced API endpoint for resetting user token secret. - Updated IM and SDK configurations to include user token. - Added tests for user token verification logic.
This commit is contained in:
@@ -102,6 +102,22 @@ func (c *ChannelController) PostUpdate_status() *web.JsonResult {
|
||||
return web.JsonSuccess()
|
||||
}
|
||||
|
||||
func (c *ChannelController) PostReset_user_token_secret() *web.JsonResult {
|
||||
operator, err := services.AuthService.RequirePermission(c.Ctx, constants.PermissionChannelUpdate)
|
||||
if err != nil {
|
||||
return web.JsonError(err)
|
||||
}
|
||||
req := request.ResetChannelUserTokenSecretRequest{}
|
||||
if err := params.ReadJSON(c.Ctx, &req); err != nil {
|
||||
return web.JsonError(err)
|
||||
}
|
||||
secret, err := services.ChannelService.ResetUserTokenSecret(req.ID, operator)
|
||||
if err != nil {
|
||||
return web.JsonError(err)
|
||||
}
|
||||
return web.JsonData(map[string]string{"userTokenSecret": secret})
|
||||
}
|
||||
|
||||
func (c *ChannelController) PostDelete() *web.JsonResult {
|
||||
operator, err := services.AuthService.RequirePermission(c.Ctx, constants.PermissionChannelDelete)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,13 +3,19 @@ package middleware
|
||||
import (
|
||||
"cs-agent/internal/pkg/irisx"
|
||||
"cs-agent/internal/pkg/openidentity"
|
||||
"cs-agent/internal/services"
|
||||
|
||||
"github.com/kataras/iris/v12"
|
||||
"github.com/mlogclub/simple/web"
|
||||
)
|
||||
|
||||
func ExternalInfoMiddleware(ctx iris.Context) {
|
||||
ext, err := openidentity.GetExternalInfo(ctx)
|
||||
channel := services.ChannelService.GetEnabledChannel(ctx)
|
||||
var userTokenSecret string
|
||||
if channel != nil {
|
||||
userTokenSecret = services.ChannelService.GetUserTokenSecret(channel)
|
||||
}
|
||||
ext, err := openidentity.GetExternalInfoWithUserTokenSecret(ctx, userTokenSecret)
|
||||
if err != nil {
|
||||
ctx.StopExecution()
|
||||
_ = ctx.JSON(web.JsonError(err))
|
||||
|
||||
+10
-8
@@ -17,15 +17,17 @@ type WxWorkKFChannelConfig struct {
|
||||
}
|
||||
|
||||
type WebChannelConfig struct {
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
ThemeColor string `json:"themeColor"`
|
||||
Position string `json:"position"`
|
||||
Width string `json:"width"`
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
ThemeColor string `json:"themeColor"`
|
||||
Position string `json:"position"`
|
||||
Width string `json:"width"`
|
||||
UserTokenSecret string `json:"userTokenSecret,omitempty"`
|
||||
}
|
||||
|
||||
type WechatMPChannelConfig struct {
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
ThemeColor string `json:"themeColor"`
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle"`
|
||||
ThemeColor string `json:"themeColor"`
|
||||
UserTokenSecret string `json:"userTokenSecret,omitempty"`
|
||||
}
|
||||
|
||||
@@ -22,3 +22,7 @@ type UpdateChannelStatusRequest struct {
|
||||
type DeleteChannelRequest struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
type ResetChannelUserTokenSecretRequest struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ func GetExternalSourceLabel(v ExternalSource) string {
|
||||
// IsAllowedOpenImExternalSource 开放 IM 入口允许的外部来源(闭集校验)。
|
||||
func IsAllowedOpenImExternalSource(s ExternalSource) bool {
|
||||
switch s {
|
||||
case ExternalSourceGuest:
|
||||
case ExternalSourceGuest, ExternalSourceUser:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -4,9 +4,11 @@ package openidentity
|
||||
import (
|
||||
"cs-agent/internal/pkg/enums"
|
||||
"cs-agent/internal/pkg/errorsx"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/kataras/iris/v12"
|
||||
"github.com/mlogclub/simple/common/strs"
|
||||
"github.com/mlogclub/simple/web/params"
|
||||
@@ -19,8 +21,36 @@ type ExternalInfo struct {
|
||||
ExternalName string `json:"externalName"`
|
||||
}
|
||||
|
||||
type UserTokenClaims struct {
|
||||
UserID string `json:"userId"`
|
||||
Name string `json:"name"`
|
||||
Exp int64 `json:"exp"`
|
||||
Iat int64 `json:"iat"`
|
||||
}
|
||||
|
||||
type userTokenJWTClaims struct {
|
||||
UserID string `json:"userId"`
|
||||
Name string `json:"name"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// GetExternalInfo 从 Header(X-External-*)或 query(externalSource、externalId、externalName)解析身份。
|
||||
func GetExternalInfo(ctx iris.Context) (*ExternalInfo, error) {
|
||||
return GetExternalInfoWithUserTokenSecret(ctx, "")
|
||||
}
|
||||
|
||||
func GetExternalInfoWithUserTokenSecret(ctx iris.Context, userTokenSecret string) (*ExternalInfo, error) {
|
||||
if userToken := parseUserToken(ctx); userToken != "" {
|
||||
claims, err := VerifyUserToken(userToken, userTokenSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ExternalInfo{
|
||||
ExternalSource: enums.ExternalSourceUser,
|
||||
ExternalID: claims.UserID,
|
||||
ExternalName: claims.Name,
|
||||
}, nil
|
||||
}
|
||||
externalSource, err := parseExternalSource(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -28,6 +58,9 @@ func GetExternalInfo(ctx iris.Context) (*ExternalInfo, error) {
|
||||
if !enums.IsAllowedOpenImExternalSource(externalSource) {
|
||||
return nil, errorsx.InvalidParam("不支持的外部来源")
|
||||
}
|
||||
if externalSource == enums.ExternalSourceUser {
|
||||
return nil, errorsx.Unauthorized("用户身份不能为空")
|
||||
}
|
||||
externalID, err := parseExternalID(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -40,6 +73,71 @@ func GetExternalInfo(ctx iris.Context) (*ExternalInfo, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func VerifyUserToken(userToken, secret string) (*UserTokenClaims, error) {
|
||||
userToken = strings.TrimSpace(userToken)
|
||||
secret = strings.TrimSpace(secret)
|
||||
if userToken == "" {
|
||||
return nil, errorsx.Unauthorized("用户身份不能为空")
|
||||
}
|
||||
if secret == "" {
|
||||
return nil, errorsx.Unauthorized("用户身份校验未配置")
|
||||
}
|
||||
|
||||
claims := &userTokenJWTClaims{}
|
||||
token, err := jwt.ParseWithClaims(userToken, claims, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unsupported signing method")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}, jwt.WithExpirationRequired(), jwt.WithValidMethods([]string{
|
||||
jwt.SigningMethodHS256.Alg(),
|
||||
jwt.SigningMethodHS384.Alg(),
|
||||
jwt.SigningMethodHS512.Alg(),
|
||||
}))
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
return nil, errorsx.Unauthorized("用户身份已过期")
|
||||
}
|
||||
return nil, errorsx.Unauthorized("用户身份校验失败")
|
||||
}
|
||||
if token == nil || !token.Valid {
|
||||
return nil, errorsx.Unauthorized("用户身份校验失败")
|
||||
}
|
||||
|
||||
userID := strings.TrimSpace(claims.UserID)
|
||||
name := strings.TrimSpace(claims.Name)
|
||||
if userID == "" {
|
||||
return nil, errorsx.Unauthorized("用户标识不能为空")
|
||||
}
|
||||
if name == "" {
|
||||
return nil, errorsx.Unauthorized("用户名称不能为空")
|
||||
}
|
||||
if claims.ExpiresAt == nil {
|
||||
return nil, errorsx.Unauthorized("用户身份已过期")
|
||||
}
|
||||
|
||||
result := &UserTokenClaims{
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
Exp: claims.ExpiresAt.Unix(),
|
||||
}
|
||||
if claims.IssuedAt != nil {
|
||||
result.Iat = claims.IssuedAt.Unix()
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func parseUserToken(ctx iris.Context) string {
|
||||
auth := strings.TrimSpace(ctx.GetHeader("Authorization"))
|
||||
if len(auth) > 7 && strings.EqualFold(auth[:7], "Bearer ") {
|
||||
if token := strings.TrimSpace(auth[7:]); token != "" {
|
||||
return token
|
||||
}
|
||||
}
|
||||
userToken, _ := params.Get(ctx, "userToken")
|
||||
return strings.TrimSpace(userToken)
|
||||
}
|
||||
|
||||
func parseExternalSource(ctx iris.Context) (enums.ExternalSource, error) {
|
||||
externalSource := ctx.GetHeader("X-External-Source")
|
||||
if strs.IsBlank(externalSource) {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package openidentity
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func TestVerifyUserTokenOK(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}, "secret")
|
||||
|
||||
claims, err := VerifyUserToken(token, "secret")
|
||||
if err != nil {
|
||||
t.Fatalf("expected token to verify: %v", err)
|
||||
}
|
||||
if claims.UserID != "u_10001" || claims.Name != "张三" {
|
||||
t.Fatalf("unexpected claims: %#v", claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenUsesJWTHeaderAlgorithm(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS384, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}, "secret")
|
||||
|
||||
claims, err := VerifyUserToken(token, "secret")
|
||||
if err != nil {
|
||||
t.Fatalf("expected HS384 token to verify from JWT header: %v", err)
|
||||
}
|
||||
if claims.UserID != "u_10001" || claims.Name != "张三" {
|
||||
t.Fatalf("unexpected claims: %#v", claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenRejectsInvalidSignature(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}, "secret")
|
||||
|
||||
if _, err := VerifyUserToken(token, "other-secret"); err == nil {
|
||||
t.Fatalf("expected invalid signature to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenRejectsExpiredToken(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(-time.Minute).Unix(),
|
||||
}, "secret")
|
||||
|
||||
if _, err := VerifyUserToken(token, "secret"); err == nil {
|
||||
t.Fatalf("expected expired token to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenRequiresUserIDAndName(t *testing.T) {
|
||||
tests := []map[string]any{
|
||||
{"name": "张三", "exp": time.Now().Add(time.Hour).Unix()},
|
||||
{"userId": "u_10001", "exp": time.Now().Add(time.Hour).Unix()},
|
||||
}
|
||||
for _, payload := range tests {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, payload, "secret")
|
||||
if _, err := VerifyUserToken(token, "secret"); err == nil {
|
||||
t.Fatalf("expected payload %#v to fail", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func signTestUserToken(t *testing.T, method jwt.SigningMethod, payload map[string]any, secret string) string {
|
||||
t.Helper()
|
||||
token, err := jwt.NewWithClaims(method, jwt.MapClaims(payload)).SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"cs-agent/internal/models"
|
||||
"cs-agent/internal/pkg/dto"
|
||||
"cs-agent/internal/pkg/dto/request"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"cs-agent/internal/pkg/utils"
|
||||
"cs-agent/internal/repositories"
|
||||
"cs-agent/internal/wxwork"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -236,6 +238,7 @@ func (s *channelService) ParseWebChannelConfig(raw string) (*dto.WebChannelConfi
|
||||
if cfg.Width == "" {
|
||||
cfg.Width = "380px"
|
||||
}
|
||||
cfg.UserTokenSecret = strings.TrimSpace(cfg.UserTokenSecret)
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -260,9 +263,91 @@ func (s *channelService) ParseWechatMPChannelConfig(raw string) (*dto.WechatMPCh
|
||||
if cfg.ThemeColor == "" {
|
||||
cfg.ThemeColor = "#2563eb"
|
||||
}
|
||||
cfg.UserTokenSecret = strings.TrimSpace(cfg.UserTokenSecret)
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (s *channelService) GetUserTokenSecret(channel *models.Channel) string {
|
||||
if channel == nil {
|
||||
return ""
|
||||
}
|
||||
switch channel.ChannelType {
|
||||
case enums.ChannelTypeWeb:
|
||||
cfg, err := s.ParseWebChannelConfig(channel.ConfigJSON)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(cfg.UserTokenSecret)
|
||||
case enums.ChannelTypeWechatMP:
|
||||
cfg, err := s.ParseWechatMPChannelConfig(channel.ConfigJSON)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(cfg.UserTokenSecret)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (s *channelService) ResetUserTokenSecret(channelID int64, operator *dto.AuthPrincipal) (string, error) {
|
||||
if operator == nil {
|
||||
return "", errorsx.Unauthorized("未登录或登录已过期")
|
||||
}
|
||||
channel := s.Get(channelID)
|
||||
if channel == nil || channel.Status == enums.StatusDeleted {
|
||||
return "", errorsx.InvalidParam("接入渠道不存在")
|
||||
}
|
||||
if channel.ChannelType != enums.ChannelTypeWeb && channel.ChannelType != enums.ChannelTypeWechatMP {
|
||||
return "", errorsx.InvalidParam("当前渠道不支持用户 JWT Secret")
|
||||
}
|
||||
secret, err := generateUserTokenSecret()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var configJSON string
|
||||
switch channel.ChannelType {
|
||||
case enums.ChannelTypeWeb:
|
||||
cfg, err := s.ParseWebChannelConfig(channel.ConfigJSON)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cfg.UserTokenSecret = secret
|
||||
raw, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
configJSON = string(raw)
|
||||
case enums.ChannelTypeWechatMP:
|
||||
cfg, err := s.ParseWechatMPChannelConfig(channel.ConfigJSON)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cfg.UserTokenSecret = secret
|
||||
raw, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
configJSON = string(raw)
|
||||
}
|
||||
if err := repositories.ChannelRepository.Updates(sqls.DB(), channelID, map[string]any{
|
||||
"config_json": configJSON,
|
||||
"update_user_id": operator.UserID,
|
||||
"update_user_name": operator.Username,
|
||||
"updated_at": time.Now(),
|
||||
}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
func generateUserTokenSecret() (string, error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func (s *channelService) GetEnabledWxWorkKFChannelByOpenKfID(openKfID string) *models.Channel {
|
||||
openKfID = strings.TrimSpace(openKfID)
|
||||
if openKfID == "" {
|
||||
@@ -341,6 +426,13 @@ func (s *channelService) buildChannelModel(id int64, req request.CreateChannelRe
|
||||
if err != nil {
|
||||
return nil, errorsx.InvalidParam("Web渠道配置不合法")
|
||||
}
|
||||
if strings.TrimSpace(cfg.UserTokenSecret) == "" {
|
||||
secret, err := generateUserTokenSecret()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.UserTokenSecret = secret
|
||||
}
|
||||
configBytes, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -357,6 +449,13 @@ func (s *channelService) buildChannelModel(id int64, req request.CreateChannelRe
|
||||
if err != nil {
|
||||
return nil, errorsx.InvalidParam("微信公众号渠道配置不合法")
|
||||
}
|
||||
if strings.TrimSpace(cfg.UserTokenSecret) == "" {
|
||||
secret, err := generateUserTokenSecret()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.UserTokenSecret = secret
|
||||
}
|
||||
configBytes, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -66,7 +66,7 @@ func (s *wsService) HandleOpenWS(ctx iris.Context) {
|
||||
external *openidentity.ExternalInfo
|
||||
)
|
||||
if principal == nil {
|
||||
ext, err := openidentity.GetExternalInfo(ctx)
|
||||
ext, err := openidentity.GetExternalInfoWithUserTokenSecret(ctx, ChannelService.GetUserTokenSecret(channel))
|
||||
if err != nil {
|
||||
_ = ctx.StopWithJSON(iris.StatusUnauthorized, web.JsonError(err))
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user