add like functionality with Like model, implement like/unlike methods, and update Post and Comment models to track like counts

This commit is contained in:
2025-07-22 22:45:55 +08:00
parent cbe73121f2
commit 562b9bd17f
15 changed files with 216 additions and 33 deletions

View File

@ -11,11 +11,13 @@ import (
"time"
)
func UseAuth() app.HandlerFunc {
func UseAuth(block bool) app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
// For cookie
token := string(c.Cookie("token"))
refreshToken := string(c.Cookie("refresh_token"))
// 尝试用普通 token 认证
tokenClaims, err := utils.Jwt.ParseJsonWebTokenWithoutState(token)
if err == nil && tokenClaims != nil {
ctx = context.WithValue(ctx, "user_id", tokenClaims.UserID)
@ -23,27 +25,41 @@ func UseAuth() app.HandlerFunc {
return
}
// token 失效 使用refresh token重新签发和鉴权
// token 失效 使用 refresh token 重新签发和鉴权
refreshTokenClaims, err := utils.Jwt.ParseJsonWebTokenWithoutState(refreshToken)
if err == nil && refreshTokenClaims != nil {
ok, err := isStatefulJwtValid(refreshTokenClaims)
if err == nil && ok {
ctx = context.WithValue(ctx, "user_id", refreshTokenClaims.UserID) // 修改这里使用refreshTokenClaims
c.Next(ctx)
newTokenClaims := utils.Jwt.NewClaims(refreshTokenClaims.UserID, refreshTokenClaims.SessionKey, refreshTokenClaims.Stateful, time.Duration(utils.Env.GetAsInt(constant.EnvKeyRefreshTokenDuration, 30)*int(time.Hour)))
ctx = context.WithValue(ctx, "user_id", refreshTokenClaims.UserID)
// 生成新 token
newTokenClaims := utils.Jwt.NewClaims(
refreshTokenClaims.UserID,
refreshTokenClaims.SessionKey,
refreshTokenClaims.Stateful,
time.Duration(utils.Env.GetAsInt(constant.EnvKeyRefreshTokenDuration, 30)*int(time.Hour)),
)
newToken, err := newTokenClaims.ToString()
if err == nil {
ctxutils.SetTokenCookie(c, newToken)
} else {
resps.InternalServerError(c, resps.ErrInternalServerError)
}
c.Next(ctx)
return
}
}
// 所有认证方式都失败,返回未授权错误
resps.UnAuthorized(c, resps.ErrUnauthorized)
c.Abort()
// 所有认证方式都失败
if block {
// 若需要阻断,返回未授权错误并中止请求
resps.UnAuthorized(c, resps.ErrUnauthorized)
c.Abort()
} else {
// 若不需要阻断继续请求但不设置用户ID
c.Next(ctx)
}
}
}