forked from mtusi2026/mtusi2026lab2
118 lines
2.2 KiB
Go
118 lines
2.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"mtusi2026lab2/internal/domain"
|
|
"mtusi2026lab2/internal/security"
|
|
"mtusi2026lab2/internal/store"
|
|
"mtusi2026lab2/internal/transport/http/response"
|
|
)
|
|
|
|
const bearerChallenge = `Bearer realm="messenger"`
|
|
|
|
const (
|
|
UserContextKey contextKey = "current_user"
|
|
sessionTokenHashKey contextKey = "session_token_hash"
|
|
)
|
|
|
|
type SessionAuthenticator interface {
|
|
GetUserBySession(
|
|
ctx context.Context,
|
|
tokenHash []byte,
|
|
) (domain.User, error)
|
|
}
|
|
|
|
func RequireAuth(
|
|
authenticator SessionAuthenticator,
|
|
next http.HandlerFunc,
|
|
) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := GetRequestID(r.Context())
|
|
|
|
token, ok := bearerToken(r.Header.Get("Authorization"))
|
|
if !ok {
|
|
writeBearerUnauthorized(w, requestID)
|
|
return
|
|
}
|
|
|
|
tokenHash := security.HashSessionToken(token)
|
|
|
|
user, err := authenticator.GetUserBySession(
|
|
r.Context(),
|
|
tokenHash,
|
|
)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeBearerUnauthorized(w, requestID)
|
|
return
|
|
}
|
|
if err != nil {
|
|
response.WriteError(
|
|
w,
|
|
http.StatusServiceUnavailable,
|
|
response.CodeUnavailable,
|
|
"service is temporarily unavailable",
|
|
requestID,
|
|
)
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(
|
|
r.Context(),
|
|
UserContextKey,
|
|
user,
|
|
)
|
|
ctx = context.WithValue(
|
|
ctx,
|
|
sessionTokenHashKey,
|
|
tokenHash,
|
|
)
|
|
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|
|
func GetCurrentUser(ctx context.Context) domain.User {
|
|
user, _ := ctx.Value(UserContextKey).(domain.User)
|
|
return user
|
|
}
|
|
|
|
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
|
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
|
|
|
result := make([]byte, len(tokenHash))
|
|
copy(result, tokenHash)
|
|
|
|
return result
|
|
}
|
|
|
|
func bearerToken(authorization string) (string, bool) {
|
|
parts := strings.Fields(authorization)
|
|
|
|
if len(parts) != 2 ||
|
|
!strings.EqualFold(parts[0], "Bearer") ||
|
|
parts[1] == "" {
|
|
return "", false
|
|
}
|
|
|
|
return parts[1], true
|
|
}
|
|
|
|
func writeBearerUnauthorized(
|
|
w http.ResponseWriter,
|
|
requestID string,
|
|
) {
|
|
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
|
|
|
response.WriteError(
|
|
w,
|
|
http.StatusUnauthorized,
|
|
response.CodeUnauthorized,
|
|
"invalid or expired bearer token",
|
|
requestID,
|
|
)
|
|
}
|