auth.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package auth
  2. import (
  3. "encoding/json"
  4. "net"
  5. "net/http"
  6. "strings"
  7. "quickip/internal/config"
  8. "quickip/internal/model"
  9. )
  10. func Middleware(cfg config.Config, next http.Handler) http.Handler {
  11. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. if !allowedSource(r.RemoteAddr) {
  13. writeJSON(w, http.StatusForbidden, model.APIResponse{Code: 1003, Message: "来源 IP 不允许", Data: nil})
  14. return
  15. }
  16. password := r.Header.Get("X-Admin-Password")
  17. if password == "" {
  18. writeJSON(w, http.StatusUnauthorized, model.APIResponse{Code: 1001, Message: "缺少密码", Data: nil})
  19. return
  20. }
  21. if password != cfg.AdminPassword {
  22. writeJSON(w, http.StatusUnauthorized, model.APIResponse{Code: 1002, Message: "密码错误", Data: nil})
  23. return
  24. }
  25. next.ServeHTTP(w, r)
  26. })
  27. }
  28. func allowedSource(remoteAddr string) bool {
  29. host, _, err := net.SplitHostPort(remoteAddr)
  30. if err != nil {
  31. host = remoteAddr
  32. }
  33. ip := net.ParseIP(strings.TrimSpace(host))
  34. if ip == nil {
  35. return false
  36. }
  37. _, subnet, _ := net.ParseCIDR("169.254.0.0/16")
  38. return subnet.Contains(ip)
  39. }
  40. func writeJSON(w http.ResponseWriter, status int, payload model.APIResponse) {
  41. w.Header().Set("Content-Type", "application/json")
  42. w.WriteHeader(status)
  43. _ = json.NewEncoder(w).Encode(payload)
  44. }