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:
@@ -49,6 +49,7 @@ func AuthRequired(jwtSecret []byte) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// GetUserID extracts the user ID injected by AuthRequired.
|
||||
// Returns an empty string if the key is not present (e.g., optional auth contexts).
|
||||
func GetUserID(c *gin.Context) string {
|
||||
v, _ := c.Get(userIDKey)
|
||||
if v == nil {
|
||||
@@ -56,3 +57,14 @@ func GetUserID(c *gin.Context) string {
|
||||
}
|
||||
return v.(string)
|
||||
}
|
||||
|
||||
// MustGetUserID extracts the user ID injected by AuthRequired.
|
||||
// It panics if the key is missing — this indicates a programming error
|
||||
// (a handler registered without the AuthRequired middleware).
|
||||
func MustGetUserID(c *gin.Context) string {
|
||||
userID := GetUserID(c)
|
||||
if userID == "" {
|
||||
panic("user_id not found in context — is AuthRequired middleware applied?")
|
||||
}
|
||||
return userID
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user