auth.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/samber/lo"
  6. "go_server/base/core"
  7. "go_server/model/common/response"
  8. "go_server/model/system"
  9. "net/http"
  10. "strings"
  11. )
  12. func Auth() gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. path := c.Request.URL.Path
  15. // /proxy/*path
  16. // /api/app/login/check
  17. // /api/sys/user/find
  18. api, err := system.NewApis().FindOrCreateAuth(core.MainDb(), path, c.Request.Method)
  19. if err == nil {
  20. // 必须存在用户ID 角色ID
  21. roleId := c.GetInt64("roleId")
  22. var role system.Role
  23. if err := core.MainDb().Model(&system.Role{}).Where("id", roleId).First(&role).Error; err != nil {
  24. // 角色不存在,继续执行(或者可以拒绝访问)
  25. c.Next()
  26. return
  27. }
  28. if role.Apis != "*" {
  29. authsList := strings.Split(role.Apis, ",") // 通过缓存获取角色配置的权限
  30. if !lo.Contains(authsList, fmt.Sprintf("%d", api.ID)) {
  31. c.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorObjByCode(response.ResponseCodeInsufficientAuthority))
  32. return
  33. }
  34. }
  35. }
  36. // 继续执行
  37. c.Next()
  38. }
  39. }