forked from mtusi2026/mtusi2026lab2
feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
@@ -15,8 +16,10 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
headerRequestID = "X-Request-Id"
|
||||
headerUserID = "X-User-Id"
|
||||
headerRequestID = "X-Request-Id"
|
||||
headerWWWAuthenticate = "WWW-Authenticate"
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
@@ -66,26 +69,44 @@ func (h *Handler) Recoverer(next http.Handler) http.Handler {
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
type principal struct {
|
||||
user domain.User
|
||||
token string
|
||||
}
|
||||
|
||||
func (h *Handler) Authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseUUID(r.Header.Get(headerUserID))
|
||||
if !ok {
|
||||
token, ok := authCredentials(r, "Bearer")
|
||||
if !ok || token == "" {
|
||||
h.fail(w, r, domain.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
user, err := h.users.Authenticate(r.Context(), id)
|
||||
user, err := h.auth.Authenticate(r.Context(), token)
|
||||
if err != nil {
|
||||
h.fail(w, r, err)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, user)))
|
||||
ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token})
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func actor(r *http.Request) domain.User {
|
||||
u, ok := r.Context().Value(ctxKey{}).(domain.User)
|
||||
func authCredentials(r *http.Request, scheme string) (string, bool) {
|
||||
gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(gotScheme, scheme) {
|
||||
return "", false
|
||||
}
|
||||
return credentials, true
|
||||
}
|
||||
|
||||
func current(r *http.Request) principal {
|
||||
p, ok := r.Context().Value(ctxKey{}).(principal)
|
||||
if !ok {
|
||||
panic(errors.New("handler: actor requested on unauthenticated route"))
|
||||
}
|
||||
return u
|
||||
return p
|
||||
}
|
||||
|
||||
func actor(r *http.Request) domain.User {
|
||||
return current(r).user
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user