79 lines
1.9 KiB
Go
79 lines
1.9 KiB
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"net/http"
|
||
|
|
"net/http/httptest"
|
||
|
|
"testing"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
"github.com/stretchr/testify/assert"
|
||
|
|
|
||
|
|
"github.com/geo-platform/tenant-api/internal/shared/auth"
|
||
|
|
)
|
||
|
|
|
||
|
|
func init() {
|
||
|
|
gin.SetMode(gin.TestMode)
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestTenantScope_ValidActor(t *testing.T) {
|
||
|
|
r := gin.New()
|
||
|
|
r.Use(func(c *gin.Context) {
|
||
|
|
actor := auth.Actor{UserID: 1, TenantID: 10, Role: "editor"}
|
||
|
|
c.Request = c.Request.WithContext(auth.WithActor(c.Request.Context(), actor))
|
||
|
|
c.Next()
|
||
|
|
})
|
||
|
|
r.Use(TenantScope())
|
||
|
|
|
||
|
|
var gotTenantID int64
|
||
|
|
r.GET("/test", func(c *gin.Context) {
|
||
|
|
gotTenantID = TenantIDFromCtx(c.Request.Context())
|
||
|
|
c.Status(http.StatusOK)
|
||
|
|
})
|
||
|
|
|
||
|
|
w := httptest.NewRecorder()
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||
|
|
r.ServeHTTP(w, req)
|
||
|
|
|
||
|
|
assert.Equal(t, http.StatusOK, w.Code)
|
||
|
|
assert.Equal(t, int64(10), gotTenantID)
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestTenantScope_MissingActor(t *testing.T) {
|
||
|
|
r := gin.New()
|
||
|
|
r.Use(TenantScope())
|
||
|
|
r.GET("/test", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||
|
|
|
||
|
|
w := httptest.NewRecorder()
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||
|
|
r.ServeHTTP(w, req)
|
||
|
|
|
||
|
|
assert.Equal(t, http.StatusUnauthorized, w.Code)
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestTenantScope_ZeroTenantID(t *testing.T) {
|
||
|
|
r := gin.New()
|
||
|
|
r.Use(func(c *gin.Context) {
|
||
|
|
actor := auth.Actor{UserID: 1, TenantID: 0, Role: "editor"}
|
||
|
|
c.Request = c.Request.WithContext(auth.WithActor(c.Request.Context(), actor))
|
||
|
|
c.Next()
|
||
|
|
})
|
||
|
|
r.Use(TenantScope())
|
||
|
|
r.GET("/test", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||
|
|
|
||
|
|
w := httptest.NewRecorder()
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||
|
|
r.ServeHTTP(w, req)
|
||
|
|
|
||
|
|
assert.Equal(t, http.StatusUnauthorized, w.Code)
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestTenantIDFromCtx_RoundTrip(t *testing.T) {
|
||
|
|
ctx := WithTenantID(context.Background(), 42)
|
||
|
|
assert.Equal(t, int64(42), TenantIDFromCtx(ctx))
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestTenantIDFromCtx_Missing(t *testing.T) {
|
||
|
|
assert.Equal(t, int64(0), TenantIDFromCtx(context.Background()))
|
||
|
|
}
|