由于用户的登录涉及到了身份这一方面的认证,所以我们就可以通过
JWT
进行用户的鉴权,以确认用户的身份。
authed.PUT("user", api.UserUpdate)
//用户修改信息的服务
type UserUpdateService struct {
NickName string `form:"nickname" json:"nickname" binding:"required,min=5,max=10"`
UserName string `form:"user_name" json:"user_name" binding:"required,min=5,max=15"`
}
func (service UserUpdateService) Update(id uint) serializer.Response {...}
var userUpdateService service.UserUpdateService
Authorization
的值claims,_ := util.ParseToken(c.GetHeader("Authorization"))
c.ShouldBind(&userUpdateService)
update
方法res := userUpdateService.Update(claims.ID)
c.JSON(200, res)
func UserUpdate(c *gin.Context) {
var userUpdateService service.UserUpdateService
claims,_ := util.ParseToken(c.GetHeader("Authorization"))
if err := c.ShouldBind(&userUpdateService); err == nil {
res := userUpdateService.Update(claims.ID)
c.JSON(200, res)
} else {
c.JSON(200, ErrorResponse(err))
logging.Info(err)
}
}
Authorization
解析出来的id找到该用户var user model.User
code := e.SUCCESS
//找到用户
err := model.DB.First(&user, id).Error
if err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
user.Nickname = service.NickName
user.UserName = service.UserName
err = model.DB.Save(&user).Error
return serializer.Response{
Status: code,
Data: serializer.BuildUser(user),
Msg: e.GetMsg(code),
}
func (service UserUpdateService) Update(id uint) serializer.Response {
var user model.User
code := e.SUCCESS
//找到用户
err := model.DB.First(&user, id).Error
if err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
user.Nickname = service.NickName
user.UserName = service.UserName
err = model.DB.Save(&user).Error
if err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
return serializer.Response{
Status: code,
Data: serializer.BuildUser(user),
Msg: e.GetMsg(code),
}
}
联系客服