Skip to content

Commit

Permalink
feat: Add authentication to UpdateUserProfileHandler and change save …
Browse files Browse the repository at this point in the history
…function parameter in repository/user.go from value to reference
  • Loading branch information
victorzhu30 committed Aug 14, 2024
1 parent 16cae31 commit 3ae2d29
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
13 changes: 13 additions & 0 deletions handler/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: "用户信息更新失败。"})
Expand Down
4 changes: 2 additions & 2 deletions repository/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}

Expand Down

0 comments on commit 3ae2d29

Please sign in to comment.