This commit is contained in:
2025-03-18 07:43:46 +08:00
commit d2e93a2736
26 changed files with 918 additions and 0 deletions

View 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)
})
}