fix开关ssl失败

pull/79/head^2
zhangchenhao 2025-05-09 10:33:08 +08:00
parent 8c8c5104dc
commit 366904cc31
2 changed files with 51 additions and 3 deletions

View File

@ -2,10 +2,13 @@ package middleware
import (
"ALLinSSL/backend/public"
"crypto/md5"
"encoding/gob"
"encoding/hex"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"strings"
"time"
)
@ -20,6 +23,10 @@ var Html404 = []byte(`<html>
func SessionAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if checkApiKey(c) {
return
}
routePath := c.Request.URL.Path
method := c.Request.Method
paths := strings.Split(strings.TrimPrefix(routePath, "/"), "/")
@ -115,3 +122,42 @@ func SessionAuthMiddleware() gin.HandlerFunc {
}
}
}
func checkApiKey(c *gin.Context) bool {
var form struct {
ApiToken string `form:"api_token"`
Timestamp string `form:"timestamp"`
}
err := c.Bind(&form)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return false
}
apiKey := public.GetSettingIgnoreError("api_key")
// timestamp := time.Now().Unix()
ApiToken := generateSignature(form.Timestamp, apiKey)
if form.ApiToken != ApiToken {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return false
}
// 这里可以添加其他的验证逻辑,比如检查时间戳是否过期等
timestamp, err := strconv.ParseInt(form.Timestamp, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid timestamp"})
return false
}
if time.Now().Unix()-timestamp > 60*5 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "timestamp expired"})
return false
}
return true
}
func generateSignature(timestamp, apiKey string) string {
keyMd5 := md5.Sum([]byte(apiKey))
keyMd5Hex := strings.ToLower(hex.EncodeToString(keyMd5[:]))
signMd5 := md5.Sum([]byte(timestamp + keyMd5Hex))
signMd5Hex := strings.ToLower(hex.EncodeToString(signMd5[:]))
return signMd5Hex
}

View File

@ -8,7 +8,7 @@ import (
func Register(r *gin.Engine) {
v1 := r.Group("/v1")
login := v1.Group("/login")
{
login.POST("/sign", api.Sign)
@ -70,11 +70,13 @@ func Register(r *gin.Engine) {
{
overview.POST("/get_overviews", api.GetOverview)
}
// 1. 提供静态文件服务
r.StaticFS("/static", http.Dir("./frontend/static")) // 静态资源路径
r.StaticFS("/auto-deploy/static", http.Dir("./frontend/static")) // 静态资源路径
// icon
r.StaticFS("/favicon.ico", http.Dir("./frontend/favicon.ico")) // favicon.ico
// 3. 前端路由托管:匹配所有其他路由并返回 index.html
r.NoRoute(func(c *gin.Context) {
c.File("./frontend/index.html")