forked from mtusi2026/mtusi2026lab2
44 lines
1.2 KiB
Go
44 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"mtusi2026lab2/internal/domain"
|
|
"mtusi2026lab2/internal/store"
|
|
"mtusi2026lab2/internal/transport/http/response"
|
|
)
|
|
|
|
const UserContextKey contextKey = "current_user"
|
|
|
|
// RequireAuth проверяет наличие и валидность X-User-Id
|
|
func RequireAuth(st *store.MemoryStore, next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
reqID := GetRequestID(r.Context())
|
|
userID := r.Header.Get("X-User-Id")
|
|
|
|
if userID == "" {
|
|
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "missing X-User-Id header", reqID)
|
|
return
|
|
}
|
|
|
|
//существует ли чел
|
|
user, err := st.GetUserByID(userID)
|
|
if err != nil {
|
|
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "user not found", reqID)
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|
|
// чисто чтоб зареганного получить из контекста
|
|
func GetCurrentUser(ctx context.Context) domain.User {
|
|
if val, ok := ctx.Value(UserContextKey).(domain.User); ok {
|
|
return val
|
|
}
|
|
return domain.User{}
|
|
}
|