Files
nepiedg 9200600b1c Enhance smoking tracking API with new features and improvements
- Added a new API endpoint `GET /api/v1/smoke/home` to consolidate core modules for the home dashboard, reducing the need for multiple requests.
- Updated the `smoke` routes to include the new home endpoint and improved user profile management with the addition of a `quit_date` field.
- Enhanced the algorithm for calculating daily targets and next smoke suggestions, ensuring accurate future time handling and user-specific recommendations.
- Improved API documentation to reflect new endpoints, response formats, and detailed field descriptions for better clarity and usability.
- Refactored user authentication handling in various handlers to streamline the process and ensure consistent error responses.
2026-01-29 17:16:35 +00:00

52 lines
1.4 KiB
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"wx_service/internal/model"
)
// CurrentUser 从 gin.Context 中取出鉴权中间件写入的当前用户。
// 返回值 ok=false 表示:未经过鉴权中间件,或 token 无效导致未设置用户。
func CurrentUser(c *gin.Context) (*model.User, bool) {
userVal, exists := c.Get(ContextCurrentUserKey)
if !exists {
return nil, false
}
user, ok := userVal.(*model.User)
return user, ok
}
// MustCurrentUser 仅用于已通过鉴权中间件的路由,避免每个 handler 重复判断。
func MustCurrentUser(c *gin.Context) *model.User {
userVal := c.MustGet(ContextCurrentUserKey)
user, ok := userVal.(*model.User)
if !ok || user == nil {
panic("current user missing in context")
}
return user
}
// RequireUser 是对 CurrentUser 的封装,复用统一的未登录响应。
func RequireUser(c *gin.Context) (*model.User, bool) {
user, ok := CurrentUser(c)
if ok {
return user, true
}
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
return nil, false
}
// RequireUserMiddleware 将登录校验统一下沉到路由层。
func RequireUserMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if _, ok := CurrentUser(c); !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
return
}
c.Next()
}
}