41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
type contextKey struct{}
|
|
|
|
func WithOwner(ctx context.Context, ownerID int32) context.Context {
|
|
return context.WithValue(ctx, contextKey{}, ownerID)
|
|
}
|
|
|
|
func OwnerFromContext(ctx context.Context) (int32, bool) {
|
|
id, ok := ctx.Value(contextKey{}).(int32)
|
|
return id, ok
|
|
}
|
|
|
|
// Middleware extrait X-Owner-ID du header et l'injecte dans le contexte.
|
|
// Pour le dev, c'est l'ID numérique de l'owner. À remplacer par JWT en prod.
|
|
func Middleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
v := r.Header.Get("X-Owner-ID")
|
|
if v == "" {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
fmt.Fprintln(w, `{"error":"missing X-Owner-ID header"}`)
|
|
return
|
|
}
|
|
id, err := strconv.Atoi(v)
|
|
if err != nil || id <= 0 {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
fmt.Fprintln(w, `{"error":"invalid X-Owner-ID"}`)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(WithOwner(r.Context(), int32(id))))
|
|
})
|
|
}
|