refactor(api): introduce v1 response contract
This commit is contained in:
@@ -11,7 +11,7 @@ const CurrentUserIDKey = "currentUserID"
|
||||
|
||||
func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method == http.MethodPost && c.Request.URL.Path == "/api/auth/login" {
|
||||
if c.Request.Method == http.MethodPost && c.Request.URL.Path == "/api/v1/auth/login" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
@@ -19,12 +19,12 @@ func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
|
||||
header := c.GetHeader("Authorization")
|
||||
token := strings.TrimPrefix(header, "Bearer ")
|
||||
if token == "" || token == header {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
|
||||
abortWithError(c, http.StatusUnauthorized, "missing_bearer_token", "请先登录后再操作")
|
||||
return
|
||||
}
|
||||
userID, err := tokenVerifier(token)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"})
|
||||
abortWithError(c, http.StatusUnauthorized, "invalid_bearer_token", "登录状态无效或已过期,请重新登录")
|
||||
return
|
||||
}
|
||||
c.Set(CurrentUserIDKey, userID)
|
||||
@@ -32,6 +32,13 @@ func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// 认证包不能反向依赖路由包;此处保持与 httpx.Error 相同的安全错误边界。
|
||||
func abortWithError(c *gin.Context, status int, code, message string) {
|
||||
c.AbortWithStatusJSON(status, gin.H{
|
||||
"error": gin.H{"code": code, "message": message},
|
||||
})
|
||||
}
|
||||
|
||||
func CurrentUserID(c *gin.Context) (uint, bool) {
|
||||
value, ok := c.Get(CurrentUserIDKey)
|
||||
if !ok {
|
||||
|
||||
Reference in New Issue
Block a user