auth.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. "web-training/pkg/auth"
  6. "web-training/internal/utils"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // AuthMiddleware JWT认证中间件
  10. func AuthMiddleware(jwtService *auth.JWTService) gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. // 从请求头获取Authorization
  13. authHeader := c.GetHeader("Authorization")
  14. if authHeader == "" {
  15. utils.ErrorResponse(c, http.StatusUnauthorized, "缺少认证令牌", "")
  16. c.Abort()
  17. return
  18. }
  19. // 检查Bearer前缀
  20. parts := strings.Split(authHeader, " ")
  21. if len(parts) != 2 || parts[0] != "Bearer" {
  22. utils.ErrorResponse(c, http.StatusUnauthorized, "令牌格式错误", "")
  23. c.Abort()
  24. return
  25. }
  26. // 验证令牌
  27. token := parts[1]
  28. claims, err := jwtService.ValidateToken(token)
  29. if err != nil {
  30. utils.ErrorResponse(c, http.StatusUnauthorized, "无效令牌", err.Error())
  31. c.Abort()
  32. return
  33. }
  34. // 将用户信息存储到上下文
  35. c.Set("userID", claims.UserID)
  36. c.Set("userRoles", claims.Roles)
  37. c.Set("claims", claims)
  38. c.Next()
  39. }
  40. }
  41. // RoleBasedAuthMiddleware 基于角色的权限控制中间件
  42. func RoleBasedAuthMiddleware(requiredRoles ...string) gin.HandlerFunc {
  43. return func(c *gin.Context) {
  44. // 获取用户角色
  45. userRoles, exists := c.Get("userRoles")
  46. if !exists {
  47. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "无法获取用户角色")
  48. c.Abort()
  49. return
  50. }
  51. // 检查用户角色是否包含所需角色
  52. userRolesSlice, ok := userRoles.([]string)
  53. if !ok {
  54. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "角色格式错误")
  55. c.Abort()
  56. return
  57. }
  58. hasPermission := false
  59. for _, requiredRole := range requiredRoles {
  60. for _, userRole := range userRolesSlice {
  61. if userRole == requiredRole {
  62. hasPermission = true
  63. break
  64. }
  65. }
  66. if hasPermission {
  67. break
  68. }
  69. }
  70. if !hasPermission {
  71. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "角色权限不足")
  72. c.Abort()
  73. return
  74. }
  75. c.Next()
  76. }
  77. }
  78. // AdminOnlyMiddleware 仅管理员访问中间件
  79. func AdminOnlyMiddleware() gin.HandlerFunc {
  80. return RoleBasedAuthMiddleware("admin")
  81. }
  82. // SelfOrAdminMiddleware 用户本人或管理员访问中间件
  83. func SelfOrAdminMiddleware() gin.HandlerFunc {
  84. return func(c *gin.Context) {
  85. userID, exists := c.Get("userID")
  86. if !exists {
  87. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "无法获取用户ID")
  88. c.Abort()
  89. return
  90. }
  91. userRoles, exists := c.Get("userRoles")
  92. if !exists {
  93. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "无法获取用户角色")
  94. c.Abort()
  95. return
  96. }
  97. // 获取请求中的用户ID
  98. paramID := c.Param("id")
  99. if paramID == "" {
  100. utils.ErrorResponse(c, http.StatusBadRequest, "请求参数错误", "缺少用户ID参数")
  101. c.Abort()
  102. return
  103. }
  104. // 检查是否是管理员
  105. userRolesSlice, ok := userRoles.([]string)
  106. if !ok {
  107. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "角色格式错误")
  108. c.Abort()
  109. return
  110. }
  111. isAdmin := false
  112. for _, role := range userRolesSlice {
  113. if role == "admin" {
  114. isAdmin = true
  115. break
  116. }
  117. }
  118. // 如果不是管理员,检查是否是用户本人
  119. if !isAdmin {
  120. userIDUint, ok := userID.(uint)
  121. if !ok {
  122. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "用户ID格式错误")
  123. c.Abort()
  124. return
  125. }
  126. if paramID != string(rune(userIDUint)) {
  127. utils.ErrorResponse(c, http.StatusForbidden, "权限不足", "只能访问自己的资源")
  128. c.Abort()
  129. return
  130. }
  131. }
  132. c.Next()
  133. }
  134. }