You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
1.9 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. // Copyright 2018 Lars Hoogestraat
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "encoding/base64"
  7. "net"
  8. "net/http"
  9. "strings"
  10. "time"
  11. "git.hoogi.eu/snafu/go-blog/logger"
  12. )
  13. var locals = [...]net.IPNet{
  14. {
  15. IP: net.IPv4(10, 0, 0, 0),
  16. Mask: net.CIDRMask(8, 32),
  17. },
  18. {
  19. IP: net.IPv4(172, 16, 0, 0),
  20. Mask: net.CIDRMask(12, 32),
  21. },
  22. {
  23. IP: net.IPv4(192, 168, 0, 0),
  24. Mask: net.CIDRMask(16, 32),
  25. },
  26. }
  27. func getIP(r *http.Request) string {
  28. xfo := r.Header.Get("X-Forwarded-For")
  29. xre := r.Header.Get("X-Real-IP")
  30. if len(xre) > 0 {
  31. ips := strings.Split(xre, ", ")
  32. for _, ip := range ips {
  33. parsedIP := net.ParseIP(ip)
  34. for _, local := range locals {
  35. if !local.Contains(parsedIP) && !parsedIP.IsLoopback() {
  36. return ip
  37. }
  38. }
  39. }
  40. }
  41. if len(xfo) > 0 {
  42. ips := strings.Split(xfo, ", ")
  43. for _, ip := range ips {
  44. parsedIP := net.ParseIP(ip)
  45. for _, local := range locals {
  46. if !local.Contains(parsedIP) && !parsedIP.IsLoopback() {
  47. return ip
  48. }
  49. }
  50. }
  51. }
  52. ip, _, err := net.SplitHostPort(r.RemoteAddr)
  53. if err != nil {
  54. logger.Log.Errorf("error while determining ip address from request %v", err)
  55. }
  56. return ip
  57. }
  58. func setCookie(rw http.ResponseWriter, name, path, data string) {
  59. c := &http.Cookie{
  60. Name: name,
  61. Path: path,
  62. Value: base64.StdEncoding.EncodeToString([]byte(data)),
  63. }
  64. http.SetCookie(rw, c)
  65. }
  66. func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, error) {
  67. c, err := r.Cookie(name)
  68. if err != nil {
  69. switch err {
  70. case http.ErrNoCookie:
  71. return "", nil
  72. default:
  73. return "", err
  74. }
  75. }
  76. value, err := base64.StdEncoding.DecodeString(c.Value)
  77. if err != nil {
  78. return "", err
  79. }
  80. //Remove temporary cookie immediately
  81. dc := &http.Cookie{
  82. Name: name,
  83. MaxAge: -1,
  84. Expires: time.Unix(1, 0),
  85. Path: "/",
  86. }
  87. http.SetCookie(w, dc)
  88. return string(value), nil
  89. }