1
0

middleware.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package panelui
  2. import (
  3. "context"
  4. "net"
  5. "net/http"
  6. )
  7. type ctxKey int
  8. const (
  9. keyUser = iota
  10. )
  11. //HeaderAuth is a Negroni-compatible Middleware
  12. type HeaderAuth struct {
  13. AllowedNames []string
  14. AllowedIPs []net.IP
  15. RequireUser bool
  16. }
  17. func _getSourceIP(req *http.Request) (net.IP, error) {
  18. ip, _, err := net.SplitHostPort(req.RemoteAddr)
  19. if err != nil {
  20. return net.IP{}, err
  21. }
  22. userIP := net.ParseIP(ip)
  23. if userIP == nil {
  24. return net.IP{}, err
  25. }
  26. return userIP, nil
  27. }
  28. func (ha HeaderAuth) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  29. srcIP, err := _getSourceIP(r)
  30. if err != nil {
  31. rw.WriteHeader(501)
  32. return
  33. }
  34. found := false
  35. if len(ha.AllowedNames) == 0 && len(ha.AllowedIPs) == 0 {
  36. found = true
  37. }
  38. if !found && len(ha.AllowedIPs) > 0 {
  39. for _, allowedIP := range ha.AllowedIPs {
  40. if allowedIP.Equal(srcIP) {
  41. found = true
  42. break
  43. }
  44. }
  45. }
  46. if !found && len(ha.AllowedNames) > 0 {
  47. for _, name := range ha.AllowedNames {
  48. nameips, err := net.LookupIP(name)
  49. if err != nil {
  50. continue
  51. }
  52. for _, allowedIP := range nameips {
  53. if allowedIP.Equal(srcIP) {
  54. found = true
  55. break
  56. }
  57. }
  58. }
  59. }
  60. user := r.Header.Get("X-Forwarded-User")
  61. if !found || (ha.RequireUser && user == "") {
  62. rw.WriteHeader(http.StatusUnauthorized)
  63. return
  64. }
  65. ctx := r.Context()
  66. ctx = context.WithValue(ctx, keyUser, user)
  67. next(rw, r.WithContext(ctx))
  68. return
  69. }