forked from mtusi2026/mtusi2026lab2
87 lines
2.0 KiB
Go
87 lines
2.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"mtusi2026lab2/internal/model"
|
|
"mtusi2026lab2/internal/storage"
|
|
)
|
|
|
|
const currentUserKey contextKey = "current_user"
|
|
|
|
type authErrorBody struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestID string `json:"request_id"`
|
|
}
|
|
|
|
type authErrorResponse struct {
|
|
Error authErrorBody `json:"error"`
|
|
}
|
|
|
|
func Auth(store *storage.SessionService) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
authorization := r.Header.Get("Authorization")
|
|
|
|
if !strings.HasPrefix(authorization, "Bearer ") {
|
|
writeAuthError(w, r)
|
|
return
|
|
}
|
|
|
|
token := strings.TrimPrefix(authorization, "Bearer ")
|
|
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
|
writeAuthError(w, r)
|
|
return
|
|
}
|
|
|
|
user, err := store.GetSessionUser(r.Context(), token)
|
|
|
|
if errors.Is(err, storage.ErrSessionNotFound) {
|
|
writeAuthError(w, r)
|
|
return
|
|
}
|
|
|
|
if err != nil {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
|
|
_ = json.NewEncoder(w).Encode(authErrorResponse{
|
|
Error: authErrorBody{
|
|
Code: "unavailable",
|
|
Message: "service unavailable",
|
|
RequestID: GetRequestID(r.Context()),
|
|
},
|
|
})
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), currentUserKey, user)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
func GetCurrentUser(ctx context.Context) (model.User, bool) {
|
|
user, ok := ctx.Value(currentUserKey).(model.User)
|
|
return user, ok
|
|
}
|
|
|
|
func writeAuthError(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
_ = json.NewEncoder(w).Encode(authErrorResponse{
|
|
Error: authErrorBody{
|
|
Code: "unauthorized",
|
|
Message: "authentication required",
|
|
RequestID: GetRequestID(r.Context()),
|
|
},
|
|
})
|
|
}
|