From 3ae2d298b8d6cfbfa6463c652ece9c7eb8bbe993 Mon Sep 17 00:00:00 2001 From: Victor Zhu <2364305645@qq.com> Date: Wed, 14 Aug 2024 10:51:51 +0800 Subject: [PATCH] feat: Add authentication to UpdateUserProfileHandler and change save function parameter in repository/user.go from value to reference --- handler/user.go | 13 +++++++++++++ repository/user.go | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/handler/user.go b/handler/user.go index 3a40bda..407a536 100644 --- a/handler/user.go +++ b/handler/user.go @@ -131,11 +131,24 @@ func WatchUserHandler(c *gin.Context) {} func UnWatchUserHandler(c *gin.Context) {} func UpdateUserProfileHandler(c *gin.Context) { + userInterface, exists := c.Get(constant.CtxKeyUser) + if !exists { + c.JSON(http.StatusNotFound, dto.BaseResponse{Message: "用户未登录!"}) + return + } + user, _ := userInterface.(*domain.User) + var request dto.UserProfileDTO if err := c.ShouldBindJSON(&request); err != nil { c.JSON(http.StatusBadRequest, dto.BaseResponse{Message: "参数错误"}) return } + + if user.ID != request.UserID { + c.JSON(http.StatusForbidden, dto.BaseResponse{Message: "无权更新其他用户信息!"}) + return + } + err := service.UpdateUserProfileByID(c, &request) if err != nil { c.JSON(http.StatusInternalServerError, dto.BaseResponse{Message: "用户信息更新失败。"}) diff --git a/repository/user.go b/repository/user.go index 708d642..aa9caee 100644 --- a/repository/user.go +++ b/repository/user.go @@ -131,7 +131,7 @@ func (q *UserProfileQuery) GetUserProfileCount(ctx context.Context, opts ...DBOp } func (q *UserProfileQuery) UpdateUserProfileByID(ctx context.Context, userProfile *po.UserProfilePO) error { - result := q.optionDB(ctx, q.WithUserID(userProfile.UserID)).Save(userProfile).Error + result := q.optionDB(ctx, q.WithUserID(userProfile.UserID)).Save(&userProfile).Error return result } @@ -223,7 +223,7 @@ func (q *UserQuery) GetUserCount(ctx context.Context, opts ...DBOption) (int64, } func (q *UserQuery) UpdateUserByID(ctx context.Context, user *po.UserPO) error { - result := q.optionDB(ctx, q.WithID(int64(user.ID))).Save(user).Error + result := q.optionDB(ctx, q.WithID(int64(user.ID))).Save(&user).Error return result }