forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
const (
|
||||
UserContextKey contextKey = "current_user"
|
||||
sessionTokenHashKey contextKey = "session_token_hash"
|
||||
)
|
||||
|
||||
type SessionAuthenticator interface {
|
||||
Authenticate(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (domain.User, []byte, 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
|
||||
}
|
||||
|
||||
user, tokenHash, err := authenticator.Authenticate(
|
||||
r.Context(),
|
||||
token,
|
||||
)
|
||||
if errors.Is(err, domain.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,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user