Exemplo n.º 1
0
        public async Task <IActionResult> Edit(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(View("Resp", new ResponseObject(Alerts.danger, "Required data missing", "Sorry, the required User Id or Email Address is missing in the link you clicked on.")));
            }
            if (id.ToLower() != User.Identity.Name.ToLower() && id.ToLower() != User.GetEmail().ToLower() && !User.AdheresTo(PolicyTypes.EditOtherProfiles))
            {
                return(View("Resp", new ResponseObject(Alerts.danger, "Access denied", "Sorry, you do not have the required rights to edit other user's profile information.")));
            }
            var usr = await userManager.GetUserAsync(id);

            if (usr != null)
            {
                var model = new UserUpdateModel()
                {
                    UserId      = usr.UserId,
                    FirstName   = usr.FirstName,
                    LastName    = usr.LastName,
                    Email       = usr.Email,
                    PhoneNumber = usr.PhoneNumber
                };
                return(View(model));
            }
            else
            {
                return(View("Resp", new ResponseObject(Alerts.danger, "Invalid Id or Email Address", "Sorry, the user id or email address your entered is wrong.")));
            }
        }
Exemplo n.º 2
0
        public ActionResult UpdatePwd(UserUpdateModel model)
        {
            var user = new User();

            user.Id = model.Id;
            var item = userSrv.Get(user.Id);

            user.Account    = item.Account;
            user.Nickname   = item.Nickname;
            user.Memo       = item.Memo;
            user.Email      = item.Email;
            user.Password   = model.Password;
            user.CreateTime = item.CreateTime;
            user.UpdateTime = DateTime.UtcNow;
            user.Disabled   = item.Disabled;
            userSrv.Update(user);
            return(Json(new
            {
                success = true,
                data = new
                {
                    data = userSrv.Get(user.Id)
                },
            }));
        }
        public IResult Update(string userName, UserUpdateModel model)
        {
            var user = _userService.GetByUserName(userName);

            if (user == null)
            {
                return(new ErrorResult("Kullanici bulunamadi"));
            }
            else
            {
                if (!String.IsNullOrEmpty(model.UserName))
                {
                    user.UserName = model.UserName;
                }
                if (!String.IsNullOrEmpty(model.NameSurname))
                {
                    user.NameSurName = model.NameSurname;
                }

                if (!String.IsNullOrEmpty(model.Password))
                {
                    byte[] passwordHash, passwordSalt;
                    HashingHelper.CreatePasswordHash(model.Password, out passwordHash, out passwordSalt);

                    user.PasswordHash = passwordHash;
                    user.PasswordSalt = passwordSalt;
                }

                _userDal.Update(user);
                return(new SuccessResult("Kullanici başarıyla güncellendi!"));
            }
        }
        public async Task <ActionResult> UpdateUser([FromBody] JsonPatchDocument <UserUpdateModel> patchDoc)
        {
            var userId     = _identityService.GetUserIdentity();
            var userResult = await _usersService.GetAsync(userId);

            if (!userResult.Succeeded)
            {
                return(BadRequest(userResult.Errors));
            }

            var updateModel = UserUpdateModel.From(userResult.Data);

            patchDoc.ApplyTo(updateModel);
            if (!TryValidateModel(updateModel))
            {
                var validationErrors = ModelState
                                       .Keys
                                       .SelectMany(k => ModelState[k].Errors)
                                       .Select(e => e.ErrorMessage)
                                       .ToArray();

                return(BadRequest(validationErrors));
            }

            var updateResult = await _usersService.UpdateAsync(userId, updateModel);

            if (!updateResult.Succeeded)
            {
                return(BadRequest(updateResult.Errors));
            }

            return(Ok());
        }
        public async Task <IActionResult> UpdateUser(UserUpdateModel model)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            if (ModelState.IsValid)
            {
                if (model.Picture != null)
                {
                    var uygulamaninCalistigiYer = Directory.GetCurrentDirectory();
                    var uzantı          = Path.GetExtension(model.Picture.FileName);
                    var resimAd         = Guid.NewGuid() + uzantı;
                    var kaydedilecekYer = uygulamaninCalistigiYer + "/wwwroot/img/" + resimAd;
                    using var stream = new FileStream(kaydedilecekYer, FileMode.Create);
                    await model.Picture.CopyToAsync(stream);

                    user.PictureUrl = resimAd;
                }
                user.Name        = model.Name;
                user.SurName     = model.SurName;
                user.Email       = model.Email;
                user.PhoneNumber = model.PhoneNumber;
                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                foreach (var item in result.Errors)
                {
                    ModelState.AddModelError("", item.Description);
                }
            }
            return(View(model));
        }
        public async Task <dynamic> Update([FromBody] UserUpdateModel userUpdateModel)
        {
            string      accessToken = Request.Headers[HeaderNames.Authorization];
            string      token       = accessToken.Split("Bearer ")[1];
            UserReadDTO userRead    = TokenUtil.GetSubFromToken(token);

            if (ModelState.IsValid)
            {
                userRead.UserName = userUpdateModel.UserName;
                Services.Entities.CustomResponse updateUserInforTask = await _userService.UpdateUserInfor(userRead);

                if (updateUserInforTask.status)
                {
                    return(new
                    {
                        status = true,
                        code = ReturnCodes.DataUpdateSucceeded,
                        message = updateUserInforTask.message,
                        data = updateUserInforTask.userReadDTO
                    });
                }
            }

            return(new
            {
                status = false,
                code = ReturnCodes.DataUpdateFailed,
                message = "Có Lỗi Xảy Ra Khi Cố Gắng Cập Nhật Dữ Liệu"
            });
        }
        public void Put_Exception()
        {
            Guid         apiToken = new Guid("35b22f54-965c-4811-837a-feaafa728ef3");
            const string password = "******";

            var updateModel = new UserUpdateModel
            {
                EmailAddress = "*****@*****.**"
            };

            const string exceptionMessage = "exceptionMessage";

            //arrange
            _webPageHelper.Setup(x => x.UpdateUserInfo(It.IsAny <Guid>(), It.IsAny <string>(), It.IsAny <UserUpdateModel>())).Throws(new Exception(exceptionMessage));

            //act
            var result = _webPageController.Put(apiToken.ToString(), password, updateModel);

            //assert
            AssertWithMessage.IsOfType(result, typeof(ObjectResult));
            var response = result as ObjectResult;

            AssertWithMessage.AreEqual(response.StatusCode, (int)HttpStatusCode.InternalServerError, "status code");
            AssertWithMessage.AreEqual(response.Value.ToString(), exceptionMessage, "exception message");
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Edit(UserUpdateModel model)
        {
            await model.EditUser();

            model.LoadRoles();
            return(View(model));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> UpdateUser([FromBody] UserUpdateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(ReturnError(StatusCodes.Status400BadRequest, "Invalid UpdateUser Request", GetModelStateMessages()));
            }

            var user = await _dataStore.GetUserBySimpleIdAsync(model.SimpleId);

            var userId = Guid.Parse(User.GetUserId());

            if (userId != user.Id)
            {
                return(ReturnError(StatusCodes.Status403Forbidden, "Invalid UpdateUser Request", $"Logged in user cant update {userId.ToString()}"));
            }

            if (user == null)
            {
                return(ReturnError(StatusCodes.Status404NotFound, "Invalid UpdateUser Request", $"User {model.SimpleId} not found"));
            }

            model.UpdateUserFromModel(user, _passwordHasher);
            await _dataStore.UpdateAsync(user);

            return(Ok(user));
        }
Exemplo n.º 10
0
        public async Task <UserUpdateModel> GetOneUserAsync(string userId)
        {
            var userModel = new UserUpdateModel();

            if (string.IsNullOrWhiteSpace(userId))
            {
                userModel.Errors.Add(Constants.Errors.UserIdInvalid);
                return(userModel);
            }

            if (!long.TryParse(userId, out long _userId) && _userId <= 0)
            {
                userModel.Errors.Add(Constants.Errors.UserIdInvalid);
                return(userModel);
            }

            var user = await _userRepository.GetUserByIdAsync(_userId);

            if (user == null)
            {
                userModel.Errors.Add(Constants.Errors.UserNotFound);
                return(userModel);
            }

            userModel = _mapperHelper.Map <ApplicationUser, UserUpdateModel>(user);

            if (userModel == null)
            {
                userModel.Errors.Add(Constants.Errors.OccuredProcessing);
            }

            return(userModel);
        }
Exemplo n.º 11
0
        public IActionResult Put(int id, [FromForm] UserUpdateModel newUser)
        {
            if (!ModelState.IsValid || id < 0)
            {
                return(BadRequest());
            }

            var currentUser = _business.GetCurrentUser(User);

            if (currentUser == null)
            {
                return(Unauthorized());
            }

            if (currentUser.Id != id)
            {
                return(Unauthorized());
            }

            var success = _business.UpdateUserById(id, newUser, currentUser.Id);

            return(success switch
            {
                1 => (IActionResult)Ok(),
                2 => NotFound(),
                _ => BadRequest()
            });
        public string UpdateUser(UserUpdateModel userUpdateModel)
        {
            try
            {
                using (var myContext = new MyContext())
                {
                    var isExistUser = myContext.UserEntities.AsEnumerable().Where(e => e.UserId == userUpdateModel.UserId).FirstOrDefault();

                    if (isExistUser == null)
                    {
                        return("User not found!");
                    }
                    //isExistUser.UserId = userUpdateModel.UserId;
                    isExistUser.UserName       = string.IsNullOrWhiteSpace(userUpdateModel.UserName) ? isExistUser.UserName : userUpdateModel.UserName;
                    isExistUser.UserEmail      = string.IsNullOrWhiteSpace(userUpdateModel.UserEmail) ? isExistUser.UserEmail : userUpdateModel.UserEmail;
                    isExistUser.UserAddress    = string.IsNullOrWhiteSpace(userUpdateModel.UserAddress) ? isExistUser.UserAddress : userUpdateModel.UserAddress;
                    isExistUser.MobileNo       = string.IsNullOrWhiteSpace(userUpdateModel.MobileNo) ? isExistUser.MobileNo : userUpdateModel.MobileNo;
                    isExistUser.AdditionalInfo = string.IsNullOrWhiteSpace(userUpdateModel.AdditionalInfo) ? isExistUser.AdditionalInfo : userUpdateModel.AdditionalInfo;
                    isExistUser.DateOfBirth    = (userUpdateModel.DateOfBirth == null || userUpdateModel.DateOfBirth == default(DateTime)) ? isExistUser.DateOfBirth : userUpdateModel.DateOfBirth;

                    myContext.SaveChanges();
                    return("user updates succesfully!");
                }
            }catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Exemplo n.º 13
0
        public async Task <ActionResult> UpdateConfirmed(UserUpdateModel newUser)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(newUser.Id);

                if (user == null)
                {
                    return(HttpNotFound());
                }
                user.UserName = newUser.UserName;
                user.Email    = newUser.Email;
                var result = await UserManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(HttpNotFound());
                }
            }
            return(Redirect(Request.UrlReferrer.ToString()));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Edit(UserUpdateModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.UserId != User.Identity.Name && !User.AdheresTo(PolicyTypes.EditOtherProfiles))
                {
                    return(View("Resp", new ResponseObject(Alerts.danger, "Access denied", "Sorry, you do not have the required rights to edit other user's profile information.")));
                }
                var usr = await userManager.GetUserAsync(model.UserId);

                usr.FirstName   = model.FirstName;
                usr.LastName    = model.LastName;
                usr.Email       = model.Email;
                usr.PhoneNumber = model.PhoneNumber;
                var r = await userManager.UpdateAsync(usr);

                if (r.IsSuccessful)
                {
                    return(View("Resp", new ResponseObject(Alerts.success, "Profile updated", $"The profile information was updated successfully! <a href=\"{Request.RootUrl()}@{usr.UserId}\">Click here</a> to view the profile details.")));
                }
                else
                {
                    ViewBag.Msg = AppUtil.GetAlert(Alerts.danger, r.Message);
                }
            }
            return(View(model));
        }
Exemplo n.º 15
0
        public IActionResult Update(UserUpdateModel user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var userModel = user.ToModel();
                    userModel.Id = int.Parse(User.FindFirst("Id").Value);
                    var response = _usersService.Udpate(userModel);

                    if (response.IsSuccessful)
                    {
                        return(RedirectToAction("Details", new { SuccessMessage = "User udpated sucessfully" }));
                    }
                    else
                    {
                        return(RedirectToAction("Details", new { ErrorMessage = response.Message }));
                    }
                }
                catch (Exception)
                {
                    return(RedirectToAction("ErrorNotFound", "Info"));
                }
            }
            else
            {
                return(View(user));
            }
        }
Exemplo n.º 16
0
        public async Task <UserDto> UpdateUserAsync(UserUpdateModel userUpdateModel, int userId)
        {
            User user = await userRepository.GetByIdAsync(userId);

            UserAccess parseResult;

            if (user is null || !Enum.TryParse(userUpdateModel.Access, true, out parseResult))
            {
                return(null);
            }

            if (!user.Name.Equals(userUpdateModel.Name))
            {
                if (await GetUserByNameAsync(userUpdateModel.Name) is not null)
                {
                    return(null);
                }
            }

            user.Name   = userUpdateModel.Name;
            user.About  = userUpdateModel.About;
            user.Access = parseResult;

            UserDto dto = mapper.Map <User, UserDto>(await userRepository.UpdateAsync(user));
            await userRepository.SaveChangesAsync();

            return(dto);
        }
Exemplo n.º 17
0
        public async Task <UserModel> UpdateUser([FromBody] UserUpdateModel usrModel)
        {
            if (usrModel == null)
            {
                return(new UserModel()
                {
                    ErrorMessage = "Keine Benutzerdaten erhalten!"
                });
            }
            var _usrModel = await userProvider.FindUser(usrModel.Username);

            if (_usrModel != null && _usrModel.Id == usrModel.Id)
            {
                if (usrModel.NewPassword != "")
                {
                    if (verifyUser(_usrModel, usrModel.Password) == PasswordVerificationResult.Success)
                    {
                        usrModel.Password = new PasswordHasher <UserModel>().HashPassword(usrModel, usrModel.NewPassword);
                    }
                    else
                    {
                        usrModel.ErrorMessage = "Der das eingegebene Passwort ist stimmt nicht!";
                        return(usrModel);
                    }
                }
                await userProvider.UpdateUser(usrModel);
            }
            return(usrModel);
        }
Exemplo n.º 18
0
        public async Task <IResultModel> Update(UserUpdateModel model)
        {
            var entity = await _repository.GetAsync(model.Id);

            if (entity == null)
            {
                return(ResultModel.NotExists);
            }

            _mapper.Map(model, entity);

            var result = await _repository.UpdateAsync(entity);

            if (result)
            {
                var account = await _accountRepository.GetAsync(entity.AccountId);

                account.Phone = model.Phone;
                account.Email = model.Email;

                result = await _accountRepository.UpdateAsync(account);
            }

            return(ResultModel.Result(result));
        }
Exemplo n.º 19
0
        public IActionResult Put(string apiToken, string password, [FromBody] UserUpdateModel userUpdateModel)
        {
            try
            {
                ValidateModel(userUpdateModel);

                if (!Guid.TryParse(apiToken, out Guid apiTokenGuid))
                {
                    string msg = $"Could not parse API token passed in into a GUID.  API token: {apiToken}";
                    _logger.Error(msg);
                    return(StatusCode((int)HttpStatusCode.BadRequest, msg));
                }

                var result = _webPageHelper.UpdateUserInfo(apiTokenGuid, password, userUpdateModel);

                if (result == null)
                {
                    return(NotFound());
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.Error($"Unhandled exception occurred when attempting to update user data", ex);
                return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Exemplo n.º 20
0
        public IActionResult UpdateUser(string id, [FromBody] UserUpdateModel userUpdateModel)
        {
            if (userUpdateModel == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }
            if (id == "self")
            {
                id = _memoryRepository.GetUserId(this.User);
            }

            var userEntity = _memoryRepository.GetUser(id).Result;

            if (userEntity == null)
            {
                return(NotFound());
            }
            _mapper.Map <UserUpdateModel, GameUser>(userUpdateModel, userEntity);
            var userResult = _memoryRepository.UpdateGameUser(userEntity).Result;

            if (!userResult.Succeeded)
            {
                if (userResult.Errors != null)
                {
                    this.AddErrors(userResult);
                }
                return(new UnprocessableEntityObjectResult(ModelState));
            }
            return(NoContent());
        }
Exemplo n.º 21
0
        public async Task <IViewComponentResult> InvokeAsync(string UserId, string Tab)
        {
            switch (Tab.ToLower())
            {
            case (PTNames.Groups):
                var gs = await userManager.GetAssignedGroupsAsync(UserId);

                return(View("Groups", gs));

            case (PTNames.Edit):
                var usr = await userManager.GetUserAsync(UserId);

                var model = new UserUpdateModel()
                {
                    UserId      = usr.UserId,
                    FirstName   = usr.FirstName,
                    LastName    = usr.LastName,
                    Email       = usr.Email,
                    PhoneNumber = usr.PhoneNumber
                };
                return(View("Edit", model));

            default:
                return(View("Resp", new ResponseObject(Alerts.danger, "No view", "We do not have any view for the tab name you entered.")));
            }
        }
Exemplo n.º 22
0
        public async Task UpdateAsync(UserUpdateRequest rq)
        {
            UserUpdateModel dto  = rq.User;
            ApplicationUser user = await _userMgr.FindByIdAsync(dto.Id);

            // Map to model
            //ApplicationUser user2 = _mapper.Map<ApplicationUser>(dto);
            // Don't allow to change email as it's used as username
            user.FirstName   = dto.FirstName;
            user.LastName    = dto.LastName;
            user.UpdatedTime = DateTime.UtcNow;

            // Update user
            IdentityResult updateResult = await _userMgr.UpdateAsync(user);

            if (!updateResult.Succeeded)
            {
                throw new InvalidOperationException(string.Join('\n', updateResult.Errors.Select(e => $"Error code: {e.Code}. Message: {e.Description}")));
            }

            //IList<string> roles = await _userMgr.GetRolesAsync(user);
            //IdentityResult removeResult = await _userMgr.RemoveFromRolesAsync(user, roles);
            //if (!removeResult.Succeeded)
            //{
            //    throw new InvalidOperationException(string.Join('\n', updateResult.Errors.Select(e => $"Error code: {e.Code}. Message: {e.Description}")));
            //}

            //IdentityResult addResult = await _userMgr.AddToRoleAsync(user, rq.MainRole);
            //if (!addResult.Succeeded)
            //{
            //    throw new InvalidOperationException(string.Join('\n', updateResult.Errors.Select(e => $"Error code: {e.Code}. Message: {e.Description}")));
            //}
        }
        public async Task <ActionResult> Update(UserUpdateModel model)
        {
            if (ModelState.IsValid)
            {
                Application.Users.Commands.UpdateUserCommand updateUserCommand = model.ToUpdateUserCommand();
                updateUserCommand.CreatedBy = User.Identity.Name;
                updateUserCommand.CreatedOn = DateTime.Now;

                int result = await Mediator.Send(updateUserCommand);

                if (result > 0)
                {
                    return(View("List"));
                }
                else
                {
                    ModelState.AddModelError("", "Update User thất bại");
                }
            }

            model.AvailableDomains = GetDomains();
            model.Departments      = await GetDepartments();

            model.Users = await GetUsers();

            return(View(model));
        }
Exemplo n.º 24
0
        public void UpdateUserInfo_ShouldReturnOkResult_WhenCreateAsyncSucceded()
        {
            mapper.Execute();
            string testId = "testId";

            var users = new Mock <IUsersService>();

            users.Setup(x => x.IsCompanyAndBulstatCompatibiltyValid(It.IsAny <User>())).Returns(() => true);
            users.Setup(x => x.Update(It.IsAny <User>())).Returns(() => new User()
            {
                Id = testId
            });

            UserUpdateModel request = new UserUpdateModel()
            {
                Id = testId
            };
            var controller = new ManageUsersController(users.Object, null, null);

            var result = controller.UpdateUserInfo(request);

            Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult <UserResponseModel>));
            var responseContent = ((OkNegotiatedContentResult <UserResponseModel>)result).Content;

            Assert.AreEqual(responseContent.Id, testId);
            users.VerifyAll();
        }
Exemplo n.º 25
0
        public async Task Update(long id, UserUpdateModel updateModel)
        {
            var user = await dbContext.Users.GetAsync(id);

            user.Update(updateModel);
            await dbContext.SaveChangesAsync();
        }
        public async Task UpdatePersonalDataShouldUpdateUser()
        {
            var dbContext         = MockServices.DbContextMock();
            var authService       = MockServices.AuthenticationServiceMock().Object;
            var userId            = authService.UserId;
            var unmodifiedUser    = dbContext.Users.Single(x => x.Id == userId);
            var expectedFirstName = unmodifiedUser.FirstName;

            dbContext.Entry(unmodifiedUser).State = Microsoft.EntityFrameworkCore.EntityState.Detached;

            var target = CreateAccountManagementService(dbContext);


            var userUpdateModel = new UserUpdateModel
            {
                Email    = "*****@*****.**",
                LastName = "12343"
            };

            var actual = await target.UpdatePersonalData(userUpdateModel);

            var user = dbContext.Users.Single(x => x.Id == userId);

            Assert.AreEqual(userUpdateModel.Email, actual.Email);
            Assert.AreEqual(userUpdateModel.LastName, actual.LastName);
            Assert.AreEqual(expectedFirstName, user.FirstName);
        }
Exemplo n.º 27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public async Task UpdateUser(UserUpdateModel model, int ID)
        {
            try
            {
                await _connection.OpenAsync();

                var cmd = new MySqlCommand("Update_User", _connection);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("usrId", ID);
                cmd.Parameters.AddWithValue("frstName", model.FirstName);
                cmd.Parameters.AddWithValue("mdlName", model.MiddleName);
                cmd.Parameters.AddWithValue("lstName", model.LastName);
                cmd.Parameters.AddWithValue("ftrName", model.FatherName);
                cmd.Parameters.AddWithValue("mtrName", model.LastName);
                if (model.GuardianId.HasValue)
                {
                    cmd.Parameters.AddWithValue("grdId", model.GuardianId);
                }
                else
                {
                    cmd.Parameters.AddWithValue("grdId", DBNull.Value);
                }
                cmd.Parameters.AddWithValue("usrtypeId", model.UserTypeId);
                cmd.Parameters.AddWithValue("dob", model.DateOfBirth);
                cmd.Parameters.AddWithValue("usrStatusId", model.UserStatusId);
                cmd.Parameters.AddWithValue("modBy", model.Actor);
                cmd.ExecuteNonQuery();
            }
            catch { throw; }
            finally { await _connection.CloseAsync(); }
        }
        public IHttpActionResult UpdateUserInfo(UserUpdateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var user = this.Mapper.Map <User>(model);

                if (!this.users.IsCompanyAndBulstatCompatibiltyValid(user))
                {
                    return(BadRequest(GlobalConstants.InvalidCompanyBulstatCombination));
                }

                var updatedUser = this.Mapper.Map <UserResponseModel>(this.users.Update(user));

                return(this.Ok(updatedUser));
            }
            catch (Exception e)
            {
                HandlExceptionLogging(e, "", controllerName);
                return(InternalServerError());
            }
        }
        public async Task <IActionResult> Edit(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NotFound());
            }

            var userRole = await _userManager.GetRolesAsync(user);

            UserUpdateModel updateModel = new UserUpdateModel
            {
                UserId      = user.Id,
                Email       = user.Email,
                FirstName   = user.FirstName,
                LastName    = user.LastName,
                PhoneNumber = user.PhoneNumber,
                RoleName    = userRole[0]
            };

            return(View(updateModel));
        }
Exemplo n.º 30
0
        public IHttpActionResult UpdateUserProfile(string id, [FromBody] UserUpdateModel updateModel)
        {
            if (id == null)
            {
                return(BadRequest("Id is null."));
            }

            if (User.Identity.GetUserId() != id)
            {
                return(Unauthorized());
            }

            if (ModelState.IsValid)
            {
                var result = UserService.UpdateProfile(updateModel);
                if (result.Succedeed)
                {
                    return(Ok());
                }
                else
                {
                    return(BadRequest(result.Message));
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }