Refactor handlers to use MustGetUserID
- Fix: replace repeated authorization checks in handlers with the new MustGetUserID helper, which panics if the user ID is missing. This simplifies handler code by eliminating redundant error handling. - Tests: update auth tests to verify the panic behavior in unprotected routes.
This commit is contained in:
@@ -17,7 +17,7 @@ func setupTestRouter(secret []byte) *gin.Engine {
|
||||
r := gin.New()
|
||||
r.Use(AuthRequired(secret))
|
||||
r.GET("/protected", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"user_id": GetUserID(c)})
|
||||
c.JSON(http.StatusOK, gin.H{"user_id": MustGetUserID(c)})
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -137,6 +137,47 @@ func TestGetUserID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMustGetUserID(t *testing.T) {
|
||||
secret := []byte("test-secret")
|
||||
token, err := auth.GenerateAccessToken("bob-99", secret, 15*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateAccessToken = %v", err)
|
||||
}
|
||||
|
||||
r := setupTestRouter(secret)
|
||||
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
|
||||
body := rec.Body.String()
|
||||
if !strings.Contains(body, "bob-99") {
|
||||
t.Errorf("response body %q does not contain user id", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMustGetUserIDPanics(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.GET("/naked", func(c *gin.Context) {
|
||||
MustGetUserID(c) // should panic — no AuthRequired middleware applied
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/naked", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Error("expected panic, got none")
|
||||
}
|
||||
}()
|
||||
r.ServeHTTP(rec, req)
|
||||
}
|
||||
|
||||
func TestAuthRequiredWrongSecret(t *testing.T) {
|
||||
secret := []byte("test-secret")
|
||||
token, err := auth.GenerateAccessToken("user-1", secret, 15*time.Minute)
|
||||
|
||||
Reference in New Issue
Block a user