feat: support merchant team roles and permissions

This commit is contained in:
yml2213
2026-08-13 11:41:34 +08:00
parent 6c98fa557e
commit a4791decb0
21 changed files with 969 additions and 201 deletions
+51 -5
View File
@@ -3,6 +3,7 @@ package middleware
import (
"strings"
"affiliate_dash/internal/model"
"affiliate_dash/internal/pkg/jwt"
"affiliate_dash/internal/pkg/response"
"affiliate_dash/internal/service"
@@ -11,10 +12,11 @@ import (
)
const (
CtxUserID = "user_id"
CtxUsername = "username"
CtxRole = "role"
CtxMerchantRole = "merchant_role"
CtxUserID = "user_id"
CtxUsername = "username"
CtxRole = "role"
CtxMerchantRole = "merchant_role"
CtxMerchantPermissions = "merchant_permissions"
)
func Auth(jm *jwt.Manager) gin.HandlerFunc {
@@ -77,7 +79,22 @@ func GetRole(c *gin.Context) string {
// 未指定时选择该账号的默认商户,确保旧后台继续落到“自营商户”。
func Tenant(tenantSvc *service.TenantService) gin.HandlerFunc {
return func(c *gin.Context) {
member, err := tenantSvc.ResolveMember(GetUserID(c), c.GetHeader("X-Merchant-ID"))
merchantRef := c.GetHeader("X-Merchant-ID")
if GetRole(c) == model.RoleAdmin && merchantRef != "" {
merchant, err := tenantSvc.ResolveMerchantForAdmin(merchantRef)
if err != nil {
response.Forbidden(c, err.Error())
c.Abort()
return
}
c.Set(CtxMerchantID, merchant.ID)
c.Set(CtxMerchantRole, model.MemberRoleOwner)
permissions, _ := tenantSvc.MerchantRolePermissions(merchant.ID, model.MemberRoleOwner)
c.Set(CtxMerchantPermissions, permissions)
c.Next()
return
}
member, err := tenantSvc.ResolveMember(GetUserID(c), merchantRef)
if err != nil {
response.Forbidden(c, err.Error())
c.Abort()
@@ -85,6 +102,13 @@ func Tenant(tenantSvc *service.TenantService) gin.HandlerFunc {
}
c.Set(CtxMerchantID, member.MerchantID)
c.Set(CtxMerchantRole, member.Role)
permissions, err := tenantSvc.MerchantRolePermissions(member.MerchantID, member.Role)
if err != nil {
response.Forbidden(c, err.Error())
c.Abort()
return
}
c.Set(CtxMerchantPermissions, permissions)
c.Next()
}
}
@@ -106,6 +130,28 @@ func RequireMerchantRole(roles ...string) gin.HandlerFunc {
}
}
// RequireMerchantPermissions 按当前商户的角色权限校验。保留角色通过兼容权限集计算,
// 自定义角色从 merchant_roles 读取,所有列出的权限均需具备。
func RequireMerchantPermissions(tenantSvc *service.TenantService, permissions ...string) gin.HandlerFunc {
return func(c *gin.Context) {
granted := GetMerchantPermissions(c)
for _, permission := range permissions {
if _, ok := granted[permission]; !ok {
response.Forbidden(c, "商户权限不足")
c.Abort()
return
}
}
c.Next()
}
}
func GetMerchantPermissions(c *gin.Context) map[string]struct{} {
value, _ := c.Get(CtxMerchantPermissions)
permissions, _ := value.(map[string]struct{})
return permissions
}
func GetMerchantRole(c *gin.Context) string {
value, _ := c.Get(CtxMerchantRole)
role, _ := value.(string)