49 lines
1.2 KiB
Go
49 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/charawein/mtusi2026lab6/internal/service"
|
|
"github.com/charawein/mtusi2026lab6/internal/transport/httputil"
|
|
)
|
|
|
|
// Auth проверяет Authorization: Bearer <token> через AuthService.
|
|
func Auth(auth *service.AuthService) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
header := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
writeUnauthorized(w, r)
|
|
return
|
|
}
|
|
token := strings.TrimPrefix(header, "Bearer ")
|
|
if token == "" {
|
|
writeUnauthorized(w, r)
|
|
return
|
|
}
|
|
|
|
u, err := auth.ValidateSession(r.Context(), token)
|
|
if err != nil {
|
|
if errors.Is(err, service.ErrUnauthorized) {
|
|
writeUnauthorized(w, r)
|
|
return
|
|
}
|
|
slog.Error("auth: unexpected", "err", err)
|
|
httputil.WriteError(w, r, nil)
|
|
return
|
|
}
|
|
|
|
ctx := httputil.ContextWithUserID(r.Context(), u.ID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
func writeUnauthorized(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
|
httputil.WriteError(w, r, service.ErrUnauthorized)
|
|
}
|