mirror of
https://github.com/0xJacky/nginx-ui.git
synced 2025-05-11 02:15:48 +02:00
107 lines
2.2 KiB
Go
107 lines
2.2 KiB
Go
package router
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"github.com/0xJacky/Nginx-UI/frontend"
|
|
"github.com/0xJacky/Nginx-UI/server/internal/logger"
|
|
"github.com/0xJacky/Nginx-UI/server/model"
|
|
"github.com/0xJacky/Nginx-UI/server/settings"
|
|
"github.com/gin-contrib/static"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/spf13/cast"
|
|
"io/fs"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
func recovery() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
errorAction := "panic"
|
|
if action, ok := c.Get("maybe_error"); ok {
|
|
errorActionMsg := cast.ToString(action)
|
|
if errorActionMsg != "" {
|
|
errorAction = errorActionMsg
|
|
}
|
|
}
|
|
logger.Error(err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
"message": err.(error).Error(),
|
|
"error": errorAction,
|
|
})
|
|
}
|
|
}()
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func authRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := c.GetHeader("Authorization")
|
|
if token == "" {
|
|
tmp, _ := base64.StdEncoding.DecodeString(c.Query("token"))
|
|
token = string(tmp)
|
|
if token == "" {
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"message": "Authorization failed",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
|
|
n := model.CheckToken(token)
|
|
|
|
if n < 1 {
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"message": "Authorization failed",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
type serverFileSystemType struct {
|
|
http.FileSystem
|
|
}
|
|
|
|
func (f serverFileSystemType) Exists(prefix string, _path string) bool {
|
|
file, err := f.Open(path.Join(prefix, _path))
|
|
if file != nil {
|
|
defer file.Close()
|
|
}
|
|
return err == nil
|
|
}
|
|
|
|
func mustFS(dir string) (serverFileSystem static.ServeFileSystem) {
|
|
|
|
sub, err := fs.Sub(frontend.DistFS, path.Join("dist", dir))
|
|
|
|
if err != nil {
|
|
logger.Error(err)
|
|
return
|
|
}
|
|
|
|
serverFileSystem = serverFileSystemType{
|
|
http.FS(sub),
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func cacheJs() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if strings.Contains(c.Request.URL.String(), "js") {
|
|
c.Header("Cache-Control", "max-age: 1296000")
|
|
if c.Request.Header.Get("If-Modified-Since") == settings.LastModified {
|
|
c.AbortWithStatus(http.StatusNotModified)
|
|
}
|
|
c.Header("Last-Modified", settings.LastModified)
|
|
}
|
|
}
|
|
}
|