middleware.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. func AuthRequired() gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. abortWithAuthFailure := func() {
  15. c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
  16. "message": "Authorization failed",
  17. })
  18. }
  19. token := c.GetHeader("Authorization")
  20. if token == "" {
  21. if token = c.GetHeader("X-Node-Secret"); token != "" && token == settings.NodeSettings.Secret {
  22. c.Set("Secret", token)
  23. c.Next()
  24. return
  25. } else {
  26. c.Set("ProxyNodeID", c.Query("x_node_id"))
  27. tokenBytes, _ := base64.StdEncoding.DecodeString(c.Query("token"))
  28. token = string(tokenBytes)
  29. if token == "" {
  30. abortWithAuthFailure()
  31. return
  32. }
  33. }
  34. }
  35. u, ok := user.GetTokenUser(token)
  36. if !ok {
  37. abortWithAuthFailure()
  38. return
  39. }
  40. c.Set("user", u)
  41. if nodeID := c.GetHeader("X-Node-ID"); nodeID != "" {
  42. c.Set("ProxyNodeID", nodeID)
  43. }
  44. c.Next()
  45. }
  46. }
  47. type ServerFileSystemType struct {
  48. http.FileSystem
  49. }
  50. func (f ServerFileSystemType) Exists(prefix string, _path string) bool {
  51. file, err := f.Open(path.Join(prefix, _path))
  52. if file != nil {
  53. defer func(file http.File) {
  54. err = file.Close()
  55. if err != nil {
  56. logger.Error("file not found", err)
  57. }
  58. }(file)
  59. }
  60. return err == nil
  61. }
  62. func CacheJs() gin.HandlerFunc {
  63. return func(c *gin.Context) {
  64. if strings.Contains(c.Request.URL.String(), "js") {
  65. c.Header("Cache-Control", "max-age: 1296000")
  66. if c.Request.Header.Get("If-Modified-Since") == settings.LastModified {
  67. c.AbortWithStatus(http.StatusNotModified)
  68. }
  69. c.Header("Last-Modified", settings.LastModified)
  70. }
  71. }
  72. }