32 lines
867 B
Go
Raw Normal View History

2025-03-18 07:43:46 +08:00
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)
})
}