github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/middleware/common.go (about)

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	model "github.com/cloudreve/Cloudreve/v3/models"
     6  	"github.com/cloudreve/Cloudreve/v3/pkg/auth"
     7  	"github.com/cloudreve/Cloudreve/v3/pkg/hashid"
     8  	"github.com/cloudreve/Cloudreve/v3/pkg/serializer"
     9  	"github.com/gin-gonic/gin"
    10  	"net/http"
    11  )
    12  
    13  // HashID 将给定对象的HashID转换为真实ID
    14  func HashID(IDType int) gin.HandlerFunc {
    15  	return func(c *gin.Context) {
    16  		if c.Param("id") != "" {
    17  			id, err := hashid.DecodeHashID(c.Param("id"), IDType)
    18  			if err == nil {
    19  				c.Set("object_id", id)
    20  				c.Next()
    21  				return
    22  			}
    23  			c.JSON(200, serializer.ParamErr("Failed to parse object ID", nil))
    24  			c.Abort()
    25  			return
    26  
    27  		}
    28  		c.Next()
    29  	}
    30  }
    31  
    32  // IsFunctionEnabled 当功能未开启时阻止访问
    33  func IsFunctionEnabled(key string) gin.HandlerFunc {
    34  	return func(c *gin.Context) {
    35  		if !model.IsTrueVal(model.GetSettingByName(key)) {
    36  			c.JSON(200, serializer.Err(serializer.CodeFeatureNotEnabled, "This feature is not enabled", nil))
    37  			c.Abort()
    38  			return
    39  		}
    40  
    41  		c.Next()
    42  	}
    43  }
    44  
    45  // CacheControl 屏蔽客户端缓存
    46  func CacheControl() gin.HandlerFunc {
    47  	return func(c *gin.Context) {
    48  		c.Header("Cache-Control", "private, no-cache")
    49  	}
    50  }
    51  
    52  func Sandbox() gin.HandlerFunc {
    53  	return func(c *gin.Context) {
    54  		c.Header("Content-Security-Policy", "sandbox")
    55  	}
    56  }
    57  
    58  // StaticResourceCache 使用静态资源缓存策略
    59  func StaticResourceCache() gin.HandlerFunc {
    60  	return func(c *gin.Context) {
    61  		c.Header("Cache-Control", fmt.Sprintf("public, max-age=%d", model.GetIntSetting("public_resource_maxage", 86400)))
    62  
    63  	}
    64  }
    65  
    66  // MobileRequestOnly
    67  func MobileRequestOnly() gin.HandlerFunc {
    68  	return func(c *gin.Context) {
    69  		if c.GetHeader(auth.CrHeaderPrefix+"ios") == "" {
    70  			c.Redirect(http.StatusMovedPermanently, model.GetSiteURL().String())
    71  			c.Abort()
    72  			return
    73  		}
    74  
    75  		c.Next()
    76  	}
    77  }