45 lines
1022 B
Go
45 lines
1022 B
Go
package middleware
|
||
|
||
import (
|
||
"context"
|
||
"net/http"
|
||
|
||
"trade/web/internal/store"
|
||
)
|
||
|
||
type ctxKey string
|
||
|
||
const userKey ctxKey = "user"
|
||
|
||
type CtxUser struct {
|
||
ID int64
|
||
Username string
|
||
Role string
|
||
}
|
||
|
||
func FromContext(ctx context.Context) (CtxUser, bool) {
|
||
u, ok := ctx.Value(userKey).(CtxUser)
|
||
return u, ok
|
||
}
|
||
|
||
// RequireUser 不再校验 JWT,直接注入默认管理员用户,所有请求放行。
|
||
func RequireUser(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
ctx := context.WithValue(r.Context(), userKey, CtxUser{
|
||
ID: 1, Username: "admin", Role: store.RoleAdmin,
|
||
})
|
||
next.ServeHTTP(w, r.WithContext(ctx))
|
||
})
|
||
}
|
||
|
||
func RequireAdmin(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
u, ok := FromContext(r.Context())
|
||
if !ok || u.Role != store.RoleAdmin {
|
||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "admin only"})
|
||
return
|
||
}
|
||
next.ServeHTTP(w, r)
|
||
})
|
||
}
|