2
0
mirror of https://github.com/acepanel/panel.git synced 2026-02-04 10:17:17 +08:00

feat: 实现安全登录

This commit is contained in:
耗子
2024-12-03 03:46:28 +08:00
parent 128f44ca55
commit 7bc716cff6
16 changed files with 322 additions and 105 deletions

View File

@@ -2,12 +2,15 @@ package middleware
import (
"context"
"fmt"
"net"
"net/http"
"slices"
"strings"
"github.com/go-rat/chix"
"github.com/spf13/cast"
"golang.org/x/crypto/sha3"
"github.com/TheTNB/panel/internal/app"
)
@@ -16,6 +19,7 @@ import (
func MustLogin(next http.Handler) http.Handler {
// 白名单
whiteList := []string{
"/api/user/key",
"/api/user/login",
"/api/user/logout",
"/api/user/isLogin",
@@ -57,6 +61,22 @@ func MustLogin(next http.Handler) http.Handler {
return
}
safeLogin := cast.ToBool(sess.Get("safe_login"))
if safeLogin {
safeClientHash := cast.ToString(sess.Get("safe_client"))
ip, _, _ := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
ua := r.Header.Get("User-Agent")
clientHash := fmt.Sprintf("%x", sha3.Sum256([]byte(ip+"|"+ua)))
if safeClientHash != clientHash || safeClientHash == "" {
render := chix.NewRender(w)
render.Status(http.StatusUnauthorized)
render.JSON(chix.M{
"message": "客户端IP/UA变化请重新登录",
})
return
}
}
r = r.WithContext(context.WithValue(r.Context(), "user_id", userID)) // nolint:staticcheck
next.ServeHTTP(w, r)
})