Ejemplo n.º 1
0
        public IHttpActionResult UpdateUser([FromBody] UpdateUserRequestDTO payload)
        {
            using (var _db = new DatabaseContext())
            {
                try
                {
                    // Throws ExceptionService.NoTokenProvidedException
                    // Throws ExceptionService.SessionNotFoundException
                    var session = ControllerHelpers.ValidateAndUpdateSession(Request);

                    // Throws ExceptionService.InvalidModelPayloadException
                    ControllerHelpers.ValidateModelAndPayload(ModelState, payload);

                    // Throws ExceptionService.InvalidGuidException
                    var UserId = ControllerHelpers.ParseAndCheckId(payload.Id);


                    var _userManager = new UserManagementManager(_db);
                    var user         = _userManager.GetUser(session.UserId);
                    if (user.IsAdministrator)
                    {
                        var userToUpdate = _userManager.GetUser(UserId);
                        _userManager.ToUpdateUser(userToUpdate, payload);

                        _userManager.UpdateUser(userToUpdate);
                        _db.SaveChanges();
                        return(Content(HttpStatusCode.OK, "User updated"));
                    }
                    else
                    {
                        return(Content(HttpStatusCode.Unauthorized, "Non-administrators cannot delete users."));
                    }
                }
                catch (Exception e) when(e is UserNotFoundException)
                {
                    return(Content(HttpStatusCode.NotFound, e.Message));
                }
                catch (Exception e) when(e is InvalidGuidException)
                {
                    return(Content(HttpStatusCode.BadRequest, e.Message));
                }
                catch (Exception e) when(e is NoTokenProvidedException ||
                                         e is SessionNotFoundException)
                {
                    return(Content(HttpStatusCode.Unauthorized, e.Message));
                }
                catch (Exception e) when(e is InvalidModelPayloadException)
                {
                    return(Content(HttpStatusCode.PreconditionFailed, e.Message));
                }
                catch (Exception e)
                {
                    if (e is DbUpdateException ||
                        e is DbEntityValidationException)
                    {
                        _db.RevertDatabaseChanges(_db);
                    }
                    return(InternalServerError());
                }
            }
        }