middleware.go 2.2 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. if token := c.GetHeader("X-Node-Secret"); token != "" && token == settings.NodeSettings.Secret {
  46. c.Set("Secret", token)
  47. c.Next()
  48. return
  49. }
  50. token := getToken(c)
  51. if token == "" {
  52. abortWithAuthFailure()
  53. return
  54. }
  55. u, ok := user.GetTokenUser(token)
  56. if !ok {
  57. abortWithAuthFailure()
  58. return
  59. }
  60. c.Set("user", u)
  61. c.Next()
  62. }
  63. }
  64. type ServerFileSystemType struct {
  65. http.FileSystem
  66. }
  67. func (f ServerFileSystemType) Exists(prefix string, _path string) bool {
  68. file, err := f.Open(path.Join(prefix, _path))
  69. if file != nil {
  70. defer func(file http.File) {
  71. err = file.Close()
  72. if err != nil {
  73. logger.Error("file not found", err)
  74. }
  75. }(file)
  76. }
  77. return err == nil
  78. }
  79. // CacheJs is a middleware that send header to client to cache js file
  80. func CacheJs() gin.HandlerFunc {
  81. return func(c *gin.Context) {
  82. if strings.Contains(c.Request.URL.String(), "js") {
  83. c.Header("Cache-Control", "max-age: 1296000")
  84. if c.Request.Header.Get("If-Modified-Since") == settings.LastModified {
  85. c.AbortWithStatus(http.StatusNotModified)
  86. }
  87. c.Header("Last-Modified", settings.LastModified)
  88. }
  89. }
  90. }