UpdateUserByID updates and user by id swagger:operation POST /user/{id} user updateUser Update a user. --- consumes: [application/json] produces: [application/json] security: [clientTokenAuthorizationHeader: [], clientTokenHeader: [], clientTokenQuery: [], basicAuth: []] parameters: - name:
(ctx *gin.Context)
| 416 | // schema: |
| 417 | // $ref: "#/definitions/Error" |
| 418 | func (a *UserAPI) UpdateUserByID(ctx *gin.Context) { |
| 419 | withID(ctx, "id", func(id uint) { |
| 420 | var user *model.UpdateUserExternal |
| 421 | if err := ctx.Bind(&user); err == nil { |
| 422 | oldUser, err := a.DB.GetUserByID(id) |
| 423 | if success := successOrAbort(ctx, 500, err); !success { |
| 424 | return |
| 425 | } |
| 426 | if oldUser != nil { |
| 427 | adminCount, err := a.DB.CountUser(&model.User{Admin: true}) |
| 428 | if success := successOrAbort(ctx, 500, err); !success { |
| 429 | return |
| 430 | } |
| 431 | if !user.Admin && oldUser.Admin && adminCount == 1 { |
| 432 | ctx.AbortWithError(400, errors.New("cannot delete last admin")) |
| 433 | return |
| 434 | } |
| 435 | internal := &model.User{ |
| 436 | ID: oldUser.ID, |
| 437 | Name: user.Name, |
| 438 | Admin: user.Admin, |
| 439 | Pass: oldUser.Pass, |
| 440 | } |
| 441 | if user.Pass != "" { |
| 442 | internal.Pass = password.CreatePassword(user.Pass, a.PasswordStrength) |
| 443 | } |
| 444 | if success := successOrAbort(ctx, 500, a.DB.UpdateUser(internal)); !success { |
| 445 | return |
| 446 | } |
| 447 | ctx.JSON(200, toExternalUser(internal)) |
| 448 | } else { |
| 449 | ctx.AbortWithError(404, errors.New("user does not exist")) |
| 450 | } |
| 451 | } |
| 452 | }) |
| 453 | } |
| 454 | |
| 455 | func toExternalUser(internal *model.User) *model.UserExternal { |
| 456 | return &model.UserExternal{ |