Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

authMiddleware.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "git.x2erp.com/qdy/go-base/types"
  8. )
  9. // ResponseFormat 响应格式
  10. type ResponseFormat int
  11. const (
  12. FormatJSON ResponseFormat = iota
  13. FormatCSV
  14. )
  15. // JWT认证中间件(支持指定响应格式)
  16. func JWTAuthMiddleware(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. // 从Header获取Authorization
  19. authHeader := r.Header.Get("Authorization")
  20. // 检查Authorization头是否存在
  21. if authHeader == "" {
  22. sendAuthError(w, "Authorization header is required", getResponseFormat(r))
  23. return
  24. }
  25. // 检查Bearer格式
  26. if !strings.HasPrefix(authHeader, "Bearer ") {
  27. sendAuthError(w, "Authorization header must start with 'Bearer '", getResponseFormat(r))
  28. return
  29. }
  30. token := strings.TrimPrefix(authHeader, "Bearer ")
  31. // 验证JWT令牌
  32. if !isValidToken(token) {
  33. sendAuthError(w, "Invalid token", getResponseFormat(r))
  34. return
  35. }
  36. // 继续处理请求
  37. next.ServeHTTP(w, r)
  38. })
  39. }
  40. // 根据请求路径判断响应格式
  41. func getResponseFormat(r *http.Request) ResponseFormat {
  42. path := r.URL.Path
  43. // 判断是否为CSV接口(根据你的路由规则)
  44. if strings.Contains(path, "/csv") || strings.Contains(path, "/export") {
  45. return FormatCSV
  46. }
  47. // 默认返回JSON格式
  48. return FormatJSON
  49. }
  50. // 发送认证错误响应(根据格式)
  51. func sendAuthError(w http.ResponseWriter, message string, format ResponseFormat) {
  52. w.WriteHeader(http.StatusUnauthorized)
  53. switch format {
  54. case FormatCSV:
  55. w.Header().Set("Content-Type", "text/csv")
  56. w.Write([]byte("error,message\n"))
  57. w.Write([]byte("unauthorized," + message + "\n"))
  58. default:
  59. w.Header().Set("Content-Type", "application/json")
  60. json.NewEncoder(w).Encode(&types.QueryResult{
  61. Success: false,
  62. Error: message,
  63. Time: time.Now().Format(time.RFC3339),
  64. })
  65. }
  66. }
  67. // 验证令牌(需要根据实际项目实现)
  68. func isValidToken(token string) bool {
  69. // TODO: 实现真正的JWT验证逻辑
  70. // 暂时简化处理
  71. return token != ""
  72. }