Done
This commit is contained in:
21
backend/middleware/audit.go
Normal file
21
backend/middleware/audit.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 审计日志中间件
|
||||
func AuditLog(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
next.ServeHTTP(w, r)
|
||||
log.Printf(
|
||||
"Method=%s Path=%s Duration=%s",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
time.Since(start),
|
||||
)
|
||||
})
|
||||
}
|
32
backend/middleware/auth.go
Normal file
32
backend/middleware/auth.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
var store = sessions.NewCookieStore([]byte("your-secret-key"))
|
||||
|
||||
// 用户认证中间件
|
||||
func Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := store.Get(r, "session")
|
||||
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
|
||||
http.Error(w, "未授权访问", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// 管理员认证中间件
|
||||
func AdminAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := store.Get(r, "session")
|
||||
if role, ok := session.Values["role"].(string); !ok || role != "admin" {
|
||||
http.Error(w, "需要管理员权限", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
19
backend/middleware/rate_limit.go
Normal file
19
backend/middleware/rate_limit.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
var limiter = rate.NewLimiter(rate.Every(1*time.Minute), 5)
|
||||
|
||||
// 请求频率限制中间件
|
||||
func RateLimit(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !limiter.Allow() {
|
||||
http.Error(w, "请求过于频繁", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user