chore: port lab 1 solution

This commit is contained in:
kk10
2026-10-02 11:45:26 +03:00
parent 65003b6119
commit 2f279a1715
43 changed files with 2402 additions and 0 deletions
+65
View File
@@ -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
}