chore: port lab 1 solution
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type userIDContextKey struct{}
|
||||
|
||||
func Auth(userService *service.UserService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
raw := r.Header.Get("X-User-Id")
|
||||
if raw == "" {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"missing X-User-Id header",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"invalid X-User-Id header",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := userService.GetByID(userID); err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"unknown user",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userIDContextKey{}, userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserID(ctx context.Context) uuid.UUID {
|
||||
id, _ := ctx.Value(userIDContextKey{}).(uuid.UUID)
|
||||
return id
|
||||
}
|
||||
Reference in New Issue
Block a user