middleware.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package middleware
  2. import (
  3. "encoding/base64"
  4. "net/http"
  5. "path"
  6. "strings"
  7. "github.com/0xJacky/Nginx-UI/internal/user"
  8. "github.com/0xJacky/Nginx-UI/settings"
  9. "github.com/gin-gonic/gin"
  10. "github.com/uozi-tech/cosy/logger"
  11. )
  12. // getToken from header, cookie or query
  13. func getToken(c *gin.Context) (token string) {
  14. if token = c.GetHeader("Authorization"); token != "" {
  15. return
  16. }
  17. if token, _ = c.Cookie("token"); token != "" {
  18. return token
  19. }
  20. if token = c.Query("token"); token != "" {
  21. tokenBytes, _ := base64.StdEncoding.DecodeString(token)
  22. return string(tokenBytes)
  23. }
  24. return ""
  25. }
  26. // getXNodeID from header or query
  27. func getXNodeID(c *gin.Context) (xNodeID string) {
  28. if xNodeID = c.GetHeader("X-Node-ID"); xNodeID != "" {
  29. return xNodeID
  30. }
  31. return c.Query("x_node_id")
  32. }
  33. // AuthRequired is a middleware that checks if the user is authenticated
  34. func AuthRequired() gin.HandlerFunc {
  35. return func(c *gin.Context) {
  36. abortWithAuthFailure := func() {
  37. c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
  38. "message": "Authorization failed",
  39. })
  40. }
  41. xNodeID := getXNodeID(c)
  42. if xNodeID != "" {
  43. c.Set("ProxyNodeID", xNodeID)
  44. }
  45. token := getToken(c)
  46. if token == "" {
  47. if token = c.GetHeader("X-Node-Secret"); token != "" && token == settings.NodeSettings.Secret {
  48. c.Set("Secret", token)
  49. c.Next()
  50. return
  51. } else {
  52. abortWithAuthFailure()
  53. return
  54. }
  55. }
  56. u, ok := user.GetTokenUser(token)
  57. if !ok {
  58. abortWithAuthFailure()
  59. return
  60. }
  61. c.Set("user", u)
  62. c.Next()
  63. }
  64. }
  65. type ServerFileSystemType struct {
  66. http.FileSystem
  67. }
  68. func (f ServerFileSystemType) Exists(prefix string, _path string) bool {
  69. file, err := f.Open(path.Join(prefix, _path))
  70. if file != nil {
  71. defer func(file http.File) {
  72. err = file.Close()
  73. if err != nil {
  74. logger.Error("file not found", err)
  75. }
  76. }(file)
  77. }
  78. return err == nil
  79. }
  80. // CacheJs is a middleware that send header to client to cache js file
  81. func CacheJs() gin.HandlerFunc {
  82. return func(c *gin.Context) {
  83. if strings.Contains(c.Request.URL.String(), "js") {
  84. c.Header("Cache-Control", "max-age: 1296000")
  85. if c.Request.Header.Get("If-Modified-Since") == settings.LastModified {
  86. c.AbortWithStatus(http.StatusNotModified)
  87. }
  88. c.Header("Last-Modified", settings.LastModified)
  89. }
  90. }
  91. }