Files
mtusi2026lab2/internal/middleware/auth.go
T

51 lines
1.1 KiB
Go

package middleware
import (
"context"
"errors"
"net/http"
"github.com/google/uuid"
"mtusi2026-messenger/internal/httpx"
"mtusi2026-messenger/internal/service"
)
type userIDContextKey struct{}
type authenticator interface {
Authenticate(ctx context.Context, token string) (uuid.UUID, error)
}
func Auth(auth authenticator) 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())
token, ok := httpx.BearerToken(r)
if !ok {
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
}
userID, err := auth.Authenticate(r.Context(), token)
if errors.Is(err, service.ErrUnauthorized) {
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
}
if err != nil {
httpx.WriteInternalError(w, requestID, err)
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
}