public ActionResult Edit(UserEditViewModel model)
        {
            try
            {
                var exist = _adminService.CheckIfUserWithUsernameExist(model.Username);
                if (!exist)
                {
                    var editedUserUsernameOld = _adminService.EditUser(model);
                    if (string.Equals(User.Identity.Name, editedUserUsernameOld) && !string.Equals(model.Username, editedUserUsernameOld))
                    {
                        FormsAuthentication.SignOut();
                        FormsAuthentication.SetAuthCookie(editedUserUsernameOld, false);
                    }

                    return RedirectToAction("Index");
                }
            }
            catch
            {
                ModelState.AddModelError(string.Empty, "Что-то пошло не так. Попробуйте ещё раз!");
                return View(model);
            }

            return View(model);
        }
        public ActionResult Update(UserEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (User.Identity.GetUserId() != model.Id)
                {
                    throw new HttpException(401, ErrorMessagesConstants.YouCanUpdateOnlyYourProfile);
                }

                this.users.Update(model.Id, model.UserName, model.FirstName, model.LastName, model.PhoneNumber, model.Email);

                TempData["Success"] = SuccessMessagesConstants.UserProfileUpdated;
            }

            return View("Update", model);
        }
        public ActionResult Details(UserEditViewModel user)
        {
            if (this.ModelState.IsValid)
            {
                var entity = this.UserService.GetById(user.Id);
                entity.FirstName = user.FirstName;
                entity.LastName = user.LastName;
                entity.Salary = user.Salary;
                entity.Skills.Clear();

                if (user.Skills != null)
                {
                    foreach (string skill in user.Skills)
                    {
                        var dbskill = this.skillService.GetAll().FirstOrDefault(x => x.Name == skill);
                        entity.Skills.Add(dbskill);
                    }
                }

                if (user.UploadedImage != null)
                {
                    using (var memory = new MemoryStream())
                    {
                        user.UploadedImage.InputStream.CopyTo(memory);
                        var content = memory.GetBuffer();

                        entity.Image = new Image
                                           {
                                               Content = content, 
                                               FileExtension =
                                                   user.UploadedImage.FileName.Split(new[] { '.' }).Last()
                                           };
                    }
                }

                this.UserService.Update(entity);
                this.UserService.SetRoleName(entity, user.RoleId);
                this.AddToastMessage(string.Empty, NotificationMessages.ProfileUpdated, ToastType.Success);
                return this.RedirectToAction("Index");
            }

            return this.View(user);
        }
        public ActionResult Update([DataSourceRequest]DataSourceRequest request, UserEditViewModel model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                var roles = this.GetUserRoles(model.Id);

                if (roles == null || roles.Count == 0)
                {
                    var entity = this.moderatorService.GetById(model.Id);

                    this.Mapper.Map(model, entity);

                    this.moderatorService.Update(entity);

                    var viewModel = this.Mapper.Map<UserViewModel>(entity);

                    return this.Json(new[] { viewModel }.ToDataSourceResult(request, this.ModelState));
                }
            }

            return this.Json(new[] { model }.ToDataSourceResult(request, this.ModelState));
        }
Example #5
0
 public bool Put(Guid id, UserEditViewModel model) => id == model.Id && UsersBL.Put(model);
        public ActionResult Edit(UserEditViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                this.ViewBag.Error = "Invalid model data";
                return this.View(model);
            }

            ApplicationUser user = this.users.GetById(model.Id);
            this.Mapper.Map(model, user);
            this.users.Update();
            this.TempData["Success"] = "Successful edit.";
            return this.RedirectToAction("Index");
        }
        public ActionResult EditPOST(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
            {
                return(new HttpUnauthorizedResult());
            }

            var user = Services.ContentManager.Get <UserPart>(id, VersionOptions.DraftRequired);

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

            string previousName = user.UserName;

            var model = Services.ContentManager.UpdateEditor(user, this);

            var editModel = new UserEditViewModel {
                User = user
            };

            if (TryUpdateModel(editModel))
            {
                if (!_userService.VerifyUserUnicity(id, editModel.UserName, editModel.Email))
                {
                    AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
                }
                else if (!Regex.IsMatch(editModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase))
                {
                    // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
                    ModelState.AddModelError("Email", T("You must specify a valid email address."));
                }
                else
                {
                    // also update the Super user if this is the renamed account
                    if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, previousName, StringComparison.Ordinal))
                    {
                        _siteService.GetSiteSettings().As <SiteSettingsPart>().SuperUser = editModel.UserName;
                    }

                    user.NormalizedUserName = editModel.UserName.ToLowerInvariant();
                }
            }

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

                var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: editModel, Prefix: null);
                editor.Metadata.Position = "2";
                model.Content.Add(editor);

                return(View(model));
            }

            Services.ContentManager.Publish(user.ContentItem);

            Services.Notifier.Information(T("User information updated"));
            return(RedirectToAction("Index"));
        }
Example #8
0
        public async Task <IActionResult> Save([FromBody] UserEditViewModel model)
        {
            // Refresh roles in the model if validation fails
            //var temp = UserEditModel.Create(_db);
            //model.Roles = temp.Roles;

            if (model.User == null)
            {
                return(BadRequest("The user could not be found."));
            }

            try
            {
                var userId = model.User.Id;
                var isNew  = userId == Guid.Empty;

                if (string.IsNullOrWhiteSpace(model.User.UserName))
                {
                    return(BadRequest("Username is mandatory."));
                }

                if (string.IsNullOrWhiteSpace(model.User.Email))
                {
                    return(BadRequest("Email address is mandatory."));
                }

                if (!string.IsNullOrWhiteSpace(model.Password) && model.Password != model.PasswordConfirm)
                {
                    return(BadRequest(string.Format("{0} {1} - {2}", "The new passwords does not match.", model.Password, model.PasswordConfirm)));
                }

                if (model.User.Id == Guid.Empty && string.IsNullOrWhiteSpace(model.Password))
                {
                    return(BadRequest("Password is mandatory when creating a new user."));
                }



                if (!string.IsNullOrWhiteSpace(model.Password) && _userManager.PasswordValidators.Count > 0)
                {
                    var errors = new List <string>();
                    foreach (var validator in _userManager.PasswordValidators)
                    {
                        var errorResult = await validator.ValidateAsync(_userManager, model.User, model.Password);

                        if (!errorResult.Succeeded)
                        {
                            errors.AddRange(errorResult.Errors.Select(msg => msg.Description));
                        }
                        if (errors.Count > 0)
                        {
                            return(BadRequest(string.Join("<br />", errors)));
                        }
                    }
                }

                //check username
                //if (await _userManager.CountAsync(u => u.UserName.ToLower().Trim() == model.User.UserName.ToLower().Trim() && u.Id != userId) > 0)
                //{
                //    return BadRequest(GetErrorMessage(_localizer.Security["Username is used by another user."]));
                //}

                ////check email
                //if (await _db.Users.CountAsync(u => u.Email.ToLower().Trim() == model.User.Email.ToLower().Trim() && u.Id != userId) > 0)
                //{
                //    return BadRequest(GetErrorMessage(_localizer.Security["Email address is used by another user."]));
                //}

                res = await model.Save(_userManager);

                var result = res;
                if (result.Succeeded)
                {
                    return(Ok(Get(model.User.Id)));
                }

                var errorMessages = new List <string>();
                errorMessages.AddRange(result.Errors.Select(msg => msg.Description));

                return(BadRequest("The user could not be saved." + "<br/><br/>" + string.Join("<br />", errorMessages)));
            }

            catch (Exception ex)
            {
                IdentityResult temp = res;
                return(BadRequest(ex.Message));
            }
        }
Example #9
0
        public IActionResult Getalluseranddep()
        {
            //1、获取access_token
            string access_token = Haikan3.Utils.DingDingHelper.GetAccessToken0().access_token;
            var    response     = ResponseModelFactory.CreateResultInstance;

            using (_dbContext)
            {
                try
                {
                    UserEditViewModel model = new UserEditViewModel();

                    string pas         = "******";
                    var    code        = access_token;
                    string suiteKey    = "dinga7xg5vjb2lwwvicu";
                    string suiteSecret = "pUiI0xvN0ZEbsFavSbuaLqctwHL2p9cIRlQ4HU5GS7y-TmYngcTjJGuI309ZLR_h";
                    string timestamp   = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000).ToString();
                    string suiteTicket = "TestSuiteTicket";
                    string signature1  = timestamp + "\n" + suiteTicket;
                    string signature2  = HmacSHA256(signature1, suiteSecret);
                    string signature   = System.Web.HttpUtility.UrlEncode(signature2, System.Text.Encoding.UTF8);
                    string auth_corpid = access_token;
                    //string url = "https://oapi.dingtalk.com/service/get_corp_token?signature=" + signature + "&timestamp=" + timestamp + "&suiteTicket=" + suiteTicket + "&accessKey=" + suiteKey;
                    string url = "https://oapi.dingtalk.com/gettoken?appkey=" + suiteKey + "&appsecret=" + suiteSecret;
                    //string param = "{ \"auth_corpid\": \"ding5998aa137739c847bc961a6cb783455b\"}";
                    //var response11 = Haikan3.Utils.DingDingHelper.HttpPost(url, param);
                    var response11 = Haikan3.Utils.DingDingHelper.HttpGet(url);
                    var result     = Newtonsoft.Json.JsonConvert.DeserializeObject <HaikanCRM.Api.ViewModels.DIngDing.PersistentCodeResult>(response11);
                    if (result != null && result.errcode == "0")
                    {
                        //获取部门列表
                        string urldep       = "https://oapi.dingtalk.com/department/list?access_token=" + result.access_token;
                        var    responseldep = Haikan3.Utils.DingDingHelper.HttpGet(urldep);
                        var    resultdep    = Newtonsoft.Json.JsonConvert.DeserializeObject <HaikanCRM.Api.ViewModels.DIngDing.departmentAlldata>(responseldep);
                        //将获取的部门信息保存到数据库
                        //if (resultdep.department == null)
                        //{
                        //    response.SetFailed(resultdep.errmsg);
                        //    return Ok(response);
                        //}
                        for (int i = 0; i < resultdep.department.Count; i++)
                        {
                            var depid = _dbContext.SystemDepartment.Count(x => x.Dingid == resultdep.department[i].id);
                            //数据库中没有查到此部门--将数据添加到数据库中
                            if (depid == 0)
                            {
                                var entity = new SystemDepartment();
                                entity.Name           = resultdep.department[i].name;                 //部门名称
                                entity.Dingid         = resultdep.department[i].id;                   //部门钉钉id
                                entity.IsDeleted      = 0;                                            //未删除
                                entity.EstablishTime  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //添加时间
                                entity.EstablishName  = "钉钉同步";                                       //添加人
                                entity.Remark         = "";                                           //备注
                                entity.DepartmentUuid = Guid.NewGuid();                               //部门guid
                                _dbContext.SystemDepartment.Add(entity);                              //添加
                                _dbContext.SaveChanges();
                            }
                            else//此部门已存在---更新部门数据
                            {
                                var entity = _dbContext.SystemDepartment.FirstOrDefault(x => x.Dingid == resultdep.department[i].id);
                                entity.Name = resultdep.department[i].name;//更新部门名称
                                _dbContext.SaveChanges();
                            }

                            //获取该部门的所有用户
                            string urldepuser = "******" + result.access_token + "&department_id=" + resultdep.department[i].id;

                            //获取部门uuid
                            var depuuid = _dbContext.SystemDepartment.FirstOrDefault(x => x.Dingid == resultdep.department[i].id).DepartmentUuid;

                            var responsedepuser = Haikan3.Utils.DingDingHelper.HttpGet(urldepuser);
                            var resdepuser      = Newtonsoft.Json.JsonConvert.DeserializeObject <HaikanCRM.Api.ViewModels.DIngDing.depauser>(responsedepuser);
                            //将获取到的人员信息保存到数据库中
                            for (int j = 0; j < resdepuser.userlist.Count; j++)
                            {
                                var userid = _dbContext.SystemUser.Count(x => x.Streets == resdepuser.userlist[j].userid);

                                //获取人员信息
                                var results    = Haikan3.Utils.DingDingHelper.HttpGet("https://oapi.dingtalk.com/user/get?access_token=" + result.access_token + "&userid=" + resdepuser.userlist[j].userid);
                                var usersxinxi = Newtonsoft.Json.JsonConvert.DeserializeObject <HaikanCRM.Api.ViewModels.DIngDing.usersdata>(results);
                                var roiduuid   = _dbContext.SystemRole.FirstOrDefault(x => x.RoleName == "客户经理");
                                //数据库中没有该人员信息--添加到数据库中
                                if (userid == 0)
                                {
                                    var entity = new SystemUser();
                                    entity.SystemUserUuid = Guid.NewGuid();
                                    entity.LoginName      = resdepuser.userlist[j].name;
                                    entity.RealName       = resdepuser.userlist[j].name;
                                    entity.Streets        = resdepuser.userlist[j].userid;
                                    entity.DepartmentUuid = depuuid;//部门uuid
                                    entity.AddTime        = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    //entity.PassWord = Haikan3.Utils.DesEncrypt.Encrypt(pas.Trim(), MdDesEncrypt.SecretKey);
                                    entity.PassWord       = Security.GenerateMD5(pas.Trim());;
                                    entity.SystemRoleUuid = roiduuid.SystemRoleUuid.ToString();
                                    entity.IsDeleted      = 0;
                                    entity.ZaiGang        = "在岗";
                                    entity.UserType       = 2;
                                    _dbContext.SystemUser.Add(entity);
                                    _dbContext.SaveChanges();

                                    _dbContext.Database.ExecuteSqlRaw("DELETE FROM SystemUserRoleMapping WHERE SystemUserUUID={0}", entity.SystemUserUuid);
                                    var success = true;
                                    ////循环加权限
                                    //for (int i = 0; i < model.SystemRoleUuid.Count; i++)
                                    //{
                                    if (entity.SystemRoleUuid != null)
                                    {
                                        var roles = new SystemUserRoleMapping();
                                        roles.SystemUserUuid = entity.SystemUserUuid;
                                        roles.SystemRoleUuid = Guid.Parse(entity.SystemRoleUuid);
                                        roles.AddTime        = DateTime.Now.ToString("yyyy-MM-dd");
                                        roles.AddPeople      = AuthContextService.CurrentUser.DisplayName;

                                        _dbContext.SystemUserRoleMapping.Add(roles);
                                    }
                                    //}
                                    success = _dbContext.SaveChanges() > 0;
                                    if (success)
                                    {
                                        response.SetSuccess();
                                    }
                                    else
                                    {
                                        _dbContext.Database.ExecuteSqlRaw("DELETE FROM SystemUser WHERE SystemUserUUID={0}", entity.SystemUserUuid);
                                        response.SetFailed("保存用户角色数据失败");
                                    }
                                }
                                else
                                { //数据库中存在该人员--修改信息
                                    var entity = _dbContext.SystemUser.FirstOrDefault(x => x.Streets == resdepuser.userlist[j].userid);
                                    entity.RealName       = resdepuser.userlist[j].name;
                                    entity.LoginName      = resdepuser.userlist[j].name;
                                    entity.DepartmentUuid = depuuid;//部门uuid
                                    _dbContext.SaveChanges();
                                }
                            }

                            ////获取子部门id列表
                            //string urlzidep = "https://oapi.dingtalk.com/department/list_ids?access_token=" + result.access_token + "&id=" + resultdep.department[i].id;
                            //    var responselzidep = Haikan3.Utils.DingDingHelper.HttpGet(urlzidep);
                        }
                    }

                    //var response = ResponseModelFactory.CreateInstance;
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    response.SetFailed(ex.Message);
                    return(Ok(response));
                }
            }
        }
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(User, id, AccountManagementOperations.Update);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(User, (user.Roles, currentRoles), Policies.AssignAllowedRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //if (user == null)
            //    return BadRequest($"{nameof(user)} cannot be null");

            if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
            {
                return(BadRequest(AppRes.AccountController_UpdateUser_IdMismatch));
            }

            if (appUser == null)
            {
                return(NotFound(id));
            }

            bool isPasswordChanged = !string.IsNullOrWhiteSpace(user.NewPassword);
            bool isUserNameChanged = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase);

            if (User.GetUserId() == id)
            {
                if (string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (isPasswordChanged)
                    {
                        AddError(AppRes.AccountController_UpdateUser_PasswordChanged, "Password");
                    }

                    if (isUserNameChanged)
                    {
                        AddError(AppRes.AccountController_UpdateUser_UserChanged, "Username");
                    }
                }
                else if (isPasswordChanged || isUserNameChanged)
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        AddError(AppRes.AccountController_UpdateUser_PasswordCheck);
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Mapper.Map(user, appUser);

            var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

            if (result.Succeeded)
            {
                if (isPasswordChanged)
                {
                    if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                    {
                        result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                    }
                    else
                    {
                        result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                    }
                }

                if (result.Succeeded)
                {
                    return(NoContent());
                }
            }

            AddError(result.Errors);

            return(BadRequest(ModelState));
        }
Example #11
0
        public IActionResult Edit(UserEditViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;

            if (ConfigurationManager.AppSettings.IsTrialVersion)
            {
                response.SetIsTrial();
                return(Ok(response));
            }
            using (_dbContext)
            {
                var entity = _dbContext.SystemUser.FirstOrDefault(x => x.SystemUserUuid == model.SystemUserUuid);
                if (entity == null)
                {
                    response.SetFailed("用户不存在");
                    return(Ok(response));
                }
                if (_dbContext.SystemUser.Count(x => x.LoginName == model.LoginName && x.SystemUserUuid != model.SystemUserUuid) > 0)
                {
                    response.SetFailed("登录名已存在");
                    return(Ok(response));
                }
                if ((!string.IsNullOrEmpty(model.UserIdCard)) && _dbContext.SystemUser.Count(x => x.UserIdCard == model.UserIdCard && x.SystemUserUuid != model.SystemUserUuid) > 0)
                {
                    response.SetFailed("身份证号已存在");
                    return(Ok(response));
                }
                //if (model.SystemRoleUuid.Count <= 0)
                //{
                //    response.SetFailed("请选择角色");
                //    return Ok(response);
                //}
                if (string.IsNullOrEmpty(model.SystemRoleUuid))
                {
                    response.SetFailed("请选择角色");
                    return(Ok(response));
                }
                entity.LoginName  = model.LoginName;
                entity.RealName   = model.RealName;
                entity.UserIdCard = model.UserIdCard;
                entity.PassWord   = Haikan3.Utils.DesEncrypt.Encrypt(model.PassWord.Trim(), MdDesEncrypt.SecretKey);
                entity.UserType   = model.UserType;
                //entity.ShopUuid = model.ShopUuid;
                //entity.VillageId = model.VillageId;
                //string temp = "";
                //for (int i = 0; i < model.SystemRoleUuid.Count; i++)
                //{
                //    temp += model.SystemRoleUuid[i] +",";
                //}
                //entity.SystemRoleUuid = temp.TrimEnd(',');
                entity.SystemRoleUuid = model.SystemRoleUuid;
                entity.IsDeleted      = model.IsDeleted;
                //entity.OldCard = model.OldCard;
                entity.Phone = model.Phone;
                _dbContext.Database.ExecuteSqlRaw("DELETE FROM SystemUserRoleMapping WHERE SystemUserUUID={0}", entity.SystemUserUuid);
                var success = true;
                //循环加权限
                //for (int i = 0; i < model.SystemRoleUuid.Count; i++)
                //{
                //    if (!string.IsNullOrEmpty(model.SystemRoleUuid[i]))
                //    {
                //        var roles = new SystemUserRoleMapping();
                //        roles.SystemUserUuid = entity.SystemUserUuid;
                //        roles.SystemRoleUuid = Guid.Parse(model.SystemRoleUuid[i]);
                //        roles.AddTime = DateTime.Now.ToString("yyyy-MM-dd");
                //        roles.AddPeople = AuthContextService.CurrentUser.DisplayName;

                //        _dbContext.SystemUserRoleMapping.Add(roles);

                //    }
                //}
                //非循环加权
                var roles = new SystemUserRoleMapping();
                roles.SystemUserUuid = entity.SystemUserUuid;
                roles.SystemRoleUuid = Guid.Parse(model.SystemRoleUuid);
                roles.AddTime        = DateTime.Now.ToString("yyyy-MM-dd");
                roles.AddPeople      = AuthContextService.CurrentUser.DisplayName;
                _dbContext.SystemUserRoleMapping.Add(roles);
                success = _dbContext.SaveChanges() > 0;
                if (success)
                {
                    ToLog.AddLog("编辑", "成功:编辑:系统用户管理列表数据", _dbContext);
                    response.SetSuccess();
                }
                else
                {
                    _dbContext.Database.ExecuteSqlRaw("DELETE FROM SystemUser WHERE SystemUserUUID={0}", entity.SystemUserUuid);
                    response.SetFailed("保存用户角色数据失败");
                }
                response = ResponseModelFactory.CreateInstance;
                return(Ok(response));
            }
        }
Example #12
0
        public async Task <IActionResult> Edit(UserEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == model.Id);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user.");
            }

            //Remove exist role
            var isAdminExists = await _userManager.IsInRoleAsync(user, "Admin");

            if (isAdminExists)
            {
                var roleResult = await _userManager.RemoveFromRoleAsync(user, "Admin");

                if (!roleResult.Succeeded)
                {
                    throw new ApplicationException($"Unable to remove user role.");
                }
            }

            if (model.IsAdmin)
            {
                var newRoleResult = await _userManager.AddToRoleAsync(user, "Admin");

                if (!newRoleResult.Succeeded)
                {
                    throw new ApplicationException($"Unable to add new user role.");
                }
            }

            var firstName = user.FirstName;
            var lastName  = user.LastName;

            if (model.FirstName != firstName || model.LastName != lastName)
            {
                user.FirstName = model.FirstName;
                user.LastName  = model.LastName;
                var setFirstNameResult = await _userManager.UpdateAsync(user);

                if (!setFirstNameResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting firstname and lastname for user with ID '{user.Id}'.");
                }
            }

            var email = user.Email;

            if (model.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, model.Email);

                if (!setEmailResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }
            }

            var phoneNumber = user.PhoneNumber;

            if (model.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, model.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
                }
            }

            if (model.ChangeImage)
            {
                _fileService.Delete(user.ImageUrl);
                user.ImageUrl = await _fileService.Save(model.Image, "images/users");

                await _userManager.UpdateAsync(user);
            }

            StatusMessage = "Your profile has been updated";

            return(RedirectToAction(nameof(Index)));
        }
Example #13
0
        public async Task <ActionResult> EditAsync(UserEditViewModel userViewModel)
        {
            await _usersService.EditAsync(userViewModel);

            return(NoContent());
        }
Example #14
0
 public ActionResult Edit(UserEditViewModel userViewModel)
 {
     return(View(userViewModel));
 }
Example #15
0
 public AddFriendCommand(UserEditViewModel ViewModel)
 {
     _ViewModel = ViewModel;
 }
Example #16
0
        public ActionResult Edit(UserEditViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using BD_EvaluacionEntities Db = new BD_EvaluacionEntities();
                    var oUser = Db.Usuarios.Find(model.Codigo_Usuario);
                    oUser.Codigo_Usuario = model.Codigo_Usuario.ToUpper();
                    oUser.Nombre_Usuario = model.Nombre_Usuario.ToUpper();
                    oUser.Tipo_Usuario   = model.Tipo_Usuario;
                    oUser.Codigo_Cargo   = model.Codigo_Cargo;
                    if (model.PASS != null && model.PASS.Trim() != "")
                    {
                        oUser.PASS = Crypto.Hash(model.PASS);
                    }
                    if (model.IdState > 0)
                    {
                        oUser.IdState = model.IdState;
                    }
                    Db.Entry(oUser).State = System.Data.Entity.EntityState.Modified;

                    //DateTime dt = new DateTime();

                    var Existe = true;
                    var Dat    = (from usr in Db.Datos_Usuarios where usr.Codigo_Usuario == model.Codigo_Usuario select usr);
                    if (Dat.Count() == 0 || Dat == null)
                    {
                        Existe = false;
                    }
                    else
                    {
                        Dat = null;
                    }
                    #region Graba datos
                    Datos_Usuarios dUser = new Datos_Usuarios
                    {
                        Codigo_Usuario   = model.Codigo_Usuario.ToUpper(),
                        Nombre_Completo  = model.Nombre_Completo.ToUpper(),
                        Fecha_Nacimiento = model.Fecha_Nacimiento,
                        Rut                    = model.Rut,
                        Fondo                  = model.Fondo,
                        Fecha_Ingreso          = model.Fecha_Ingreso,
                        Fecha_Termino_Contrato = model.Fecha_Termino_Contrato,
                        Calidad_Contrato       = model.Calidad_Contrato ?? string.Empty,
                        Tipo_Contrato          = model.Tipo_Contrato ?? string.Empty,
                        Codigo_Contrato        = model.Codigo_Contrato ?? string.Empty
                    };
                    if (Existe)
                    {
                        Db.Entry(dUser).State = System.Data.Entity.EntityState.Modified;
                    }
                    else
                    {
                        Db.Datos_Usuarios.Add(dUser);
                    }
                    mensaje = "Ok";
                    Db.SaveChanges();
                    #endregion
                }
                else
                {
                    string errors = string.Empty;
                    foreach (var item in ModelState.Values)
                    {
                        if (item.Errors.Count > 0)
                        {
                            mensaje += string.Format("{0} \n", item.Errors[0].ErrorMessage);
                        }
                    }
                    mensaje += " Contacte al Administrador";
                }
                return(RedirectToAction("Edit", "User", new { id = model.Codigo_Usuario, mensaje }));
            }
            catch (Exception ex)
            {
                mensaje = ex.Message;
                return(RedirectToAction("Edit", "User", new { id = model.Codigo_Usuario, mensaje }));
            }
        }
Example #17
0
        public ActionResult Edit(string Id, string mensaje)
        {
            Usuarios oUser = (Usuarios)Session["User"];

            ViewBag.TipoUsuario = new SelectList(Tools.LeerTipoUsuario(Convert.ToInt32(oUser.Tipo_Usuario)), "Tipo_Usuario", "Nombre", "");
            ViewBag.Cargos      = new SelectList(Tools.LeerCargos(Convert.ToInt32(oUser.Tipo_Usuario)), "Codigo_Cargo", "Nombre_Cargo", "");
            ViewBag.UserState   = new SelectList(Utils.Tools.LeerEstados(), "IdState", "StateDescription", "");

            ViewBag.Status = false;

            if (mensaje != null && mensaje != "")
            {
                if (mensaje == "Ok")
                {
                    ViewBag.Message = "Usuario modificado exitosamente";
                    ViewBag.Status  = true;
                }
                else if (mensaje != "Ok")
                {
                    ViewBag.Message = "Usuario no pudo ser modificado " + Environment.NewLine + mensaje;
                    ViewBag.Status  = false;
                }
            }
            try
            {
                var eUser = new UserEditViewModel();
                var Du    = new UsuarioViewModel();
                using BD_EvaluacionEntities Db = new BD_EvaluacionEntities();
                string dv;
                Du = (from du in Db.Datos_Usuarios
                      where du.Codigo_Usuario == Id
                      select new UsuarioViewModel
                {
                    Rut = du.Rut
                }
                      ).FirstOrDefault(); // select du).FirstOrDefault().Rut;
                if (Du != null)
                {
                    dv = Tools.CalcularDV(Convert.ToInt32(Du.Rut));
                }
                else
                {
                    dv = "";
                }
                #region Llena datos para mostrar
                DateTime dt = new DateTime();
                eUser = (from usr in Db.Usuarios
                         join dUs in Db.Datos_Usuarios on usr.Codigo_Usuario equals dUs.Codigo_Usuario into leftJ
                         from lJo in leftJ.DefaultIfEmpty()
                         where usr.Codigo_Usuario == Id
                         select new UserEditViewModel
                {
                    Codigo_Usuario = usr.Codigo_Usuario,
                    Nombre_Usuario = usr.Nombre_Usuario,
                    Tipo_Usuario = usr.Tipo_Usuario,
                    Codigo_Cargo = usr.Codigo_Cargo,
                    IdState = usr.IdState.Equals(null) ? 0 : usr.IdState,
                    Nombre_Completo = lJo.Nombre_Completo ?? string.Empty,
                    Fecha_Nacimiento = lJo.Fecha_Nacimiento ?? dt,
                    Rut = lJo.Rut.Equals(null) ? 0 : lJo.Rut,
                    Dv = dv ?? string.Empty,
                    Fondo = lJo.Fondo ?? string.Empty,
                    Fecha_Ingreso = lJo.Fecha_Ingreso ?? dt,
                    Fecha_Termino_Contrato = lJo.Fecha_Termino_Contrato ?? dt,
                    Calidad_Contrato = lJo.Calidad_Contrato ?? string.Empty,
                    Tipo_Contrato = lJo.Tipo_Contrato ?? string.Empty,
                    Codigo_Contrato = lJo.Codigo_Contrato ?? string.Empty
                }).FirstOrDefault();
                return(View(eUser));

                #endregion
            }
            catch (Exception e)
            {
                return(View(new { e.Message }));
                //return RedirectToAction("~/Error/UnAuthorizedOperation?Error = " + e.Message);
            }
        }
Example #18
0
        public async Task <IActionResult> User([FromForm] UserEditViewModel user)
        {
            var newUser = user.Id == 0;

            if (newUser && string.IsNullOrWhiteSpace(user.Password))
            {
                ModelState.AddModelError(nameof(user.Password), "Password field is requried when creating a new user.");
            }

            if (!ModelState.IsValid)
            {
                return(View(user));
            }


            var            dbUser = _mapper.Map <User>(user);
            IdentityResult result = null;


            if (user.Id == 0)
            {
                dbUser.EmailConfirmed = true;
                dbUser.Enabled        = true;
                result = await _userManager.CreateAsync(dbUser);
            }

            else
            {
                dbUser = _dbContext.Users.FirstOrDefault(u => u.Id == user.Id);
                if (dbUser == null)
                {
                    return(RedirectToAction("Index"));
                }
                _mapper.Map(user, dbUser);


                result = await _userManager.UpdateAsync(dbUser);
            }

            if (result.Succeeded && !string.IsNullOrWhiteSpace(user.Password))
            {
                result = await _userManager.AddPasswordAsync(dbUser, user.Password);
            }

            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError(err.Code, err.Description);
                }

                return(View(user));
            }

            foreach (var role in user.Roles)
            {
                if (role.Selected)
                {
                    if (!await _userManager.IsInRoleAsync(dbUser, role.Name))
                    {
                        await _userManager.AddToRoleAsync(dbUser, role.Name);
                    }
                }
                else // not selected
                {
                    if (await _userManager.IsInRoleAsync(dbUser, role.Name))
                    {
                        await _userManager.RemoveFromRoleAsync(dbUser, role.Name);
                    }
                }
            }

            _dbContext.SaveChanges();

            if (newUser)
            {
                return(RedirectToAction("User", new { id = dbUser.Id }));
            }
            else
            {
                return(View(user));
            }
        }
        public ActionResult Edit(string id, UserEditViewModel viewModel)
        {
            try
            {
                var dbUser  = userService.Get(id);
                var appUser = GameHandler.Users.SingleOrDefault(u => u.Id == id);
                //var appUser = _gameHandler.Users.SingleOrDefault(u => u.Id == id);

                // Update user name
                dbUser.Name  = viewModel.Name;
                appUser.Name = viewModel.Name;

                // Update the character

                var character = characterService.GetByName(viewModel.CharacterName);
                dbUser.Character  = character;
                appUser.Character = character;

                // Reset user cards
                dbUser.SkillCards           = new List <SkillCard>();
                dbUser.ShopCards            = new List <ShopCard>();
                dbUser.ClassEquipmentCards  = new List <ClassEquipmentCard>();
                dbUser.FamiliarCards        = new List <FamiliarCard>();
                appUser.SkillCards          = new List <SkillCard>();
                appUser.ShopCards           = new List <ShopCard>();
                appUser.ClassEquipmentCards = new List <ClassEquipmentCard>();
                appUser.FamiliarCards       = new List <FamiliarCard>();

                // Set newly selected SkillCards based on user selection in the UI
                var allSkillCards      = skillCardService.Get();
                var selectedSkillCards = viewModel.SkillCards.Where(x => x.Selected);

                foreach (var card in allSkillCards)
                {
                    if (selectedSkillCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        dbUser.SkillCards.Add(card);
                        appUser.SkillCards.Add(card);
                    }
                }

                // Set newly selected ClassEquipmentCards based on user selection in the UI
                var allClassEquipmentCards      = classEquipmentCardService.Get();
                var selectedClassEquipmentCards = viewModel.ClassEquipmentCards.Where(x => x.Selected);

                foreach (var card in allClassEquipmentCards)
                {
                    if (selectedClassEquipmentCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        dbUser.ClassEquipmentCards.Add(card);
                        appUser.ClassEquipmentCards.Add(card);
                    }
                }

                // Set newly selected ShopCards based on user selection in the UI
                var allShopCards      = shopCardService.Get();
                var selectedShopCards = viewModel.ShopCards.Where(x => x.Selected);

                foreach (var card in allShopCards)
                {
                    if (selectedShopCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        dbUser.ShopCards.Add(card);
                        appUser.ShopCards.Add(card);
                    }
                }

                // Set newly selected FamiliarCards based on user selection in the UI
                var allFamiliarCards      = familiarCardService.Get();
                var selectedFamiliarCards = viewModel.FamiliarCards.Where(x => x.Selected);

                foreach (var card in allFamiliarCards)
                {
                    if (selectedFamiliarCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        dbUser.FamiliarCards.Add(card);
                        appUser.FamiliarCards.Add(card);
                    }
                }

                userService.Update(id, dbUser);
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception)
            {
                return(View());
            }
        }
Example #20
0
        public async Task <ActionResult> DisableUserByIdAsync(UserEditViewModel userEditViewModel)
        {
            await _usersService.DisableUserByIdAsync(userEditViewModel);

            return(NoContent());
        }
Example #21
0
        public async Task <IActionResult> Edit(UserEditViewModel model, IFormFile newProfileAvatar = null)
        {
            string sId        = User.FindFirst("Id").Value;
            User   editEntity = await db.Users.FirstOrDefaultAsync(el => el.Id == model.user.Id);

            if (editEntity != null)
            {
                if (editEntity.Id.ToString() == sId)
                {
                    ModelState.ClearValidationState("newPassword");
                    ModelState.ClearValidationState("newPasswordRepeat");
                    ModelState.ClearValidationState("Name");
                    if (!(model.Name.Length <= 20 && model.Name.Length > 3))
                    {
                        ModelState.AddModelError("Name", "Длина имени должна быть в диапазоне 3-20 символов");
                        return(View(model));
                    }
                    editEntity.UserName         = model.Name;
                    editEntity.NeedToNotificate = model.NeedToNotify;
                    if (!string.IsNullOrEmpty(model.currentPassword))
                    {
                        if (BCrypt.Net.BCrypt.Verify(model.currentPassword, editEntity.PasswordHash))
                        {
                            if (model.newPassword == model.newPasswordRepeat)
                            {
                                if (model.newPassword.Length <= 20 && model.newPassword.Length >= 8)
                                {
                                    editEntity.PasswordHash = BCrypt.Net.BCrypt.HashPassword(model.newPassword);
                                }
                                else
                                {
                                    ModelState.AddModelError("newPassword", "Длина нового пароля должна быть в диапазоне 8-20 символов");
                                    ModelState.AddModelError("newPasswordRepeat", "Длина нового пароля должна быть в диапазоне 8-20 символов");
                                    return(View(model));
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("newPassword", "Пароли должны совпадать");
                                ModelState.AddModelError("newPasswordRepeat", "Пароли должны совпадать");
                                return(View(model));
                            }
                        }
                        else
                        {
                            ModelState.ClearValidationState("currentPassword");
                            ModelState.AddModelError("currentPassword", "Неверный пароль");
                            return(View(model));
                        }
                    }
                    db.Users.Update(editEntity);
                    await db.SaveChangesAsync();

                    var claims = new List <Claim>
                    {
                        new Claim(ClaimsIdentity.DefaultNameClaimType, model.Name)
                    };
                    if (editEntity.RoleName == Models.User.AdminRole)
                    {
                        claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, "admin"));
                    }
                    claims.Add(new Claim("Id", editEntity.Id.ToString()));
                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                    ClaimsIdentity idCI = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(idCI));

                    if (newProfileAvatar != null)
                    {
                        string path = "/static/images/UsersAvatars/" + editEntity.Id.ToString() + ".jpg";
                        using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create))
                        {
                            await newProfileAvatar.CopyToAsync(fileStream);
                        }
                    }
                }
                else
                {
                    return(StatusCode(404));
                }
            }
            return(RedirectToAction("Index"));
        }
Example #22
0
 public void Remove(UserEditViewModel User)
 {
     UserRepo.Remove(User.toModel());
     unitOfWork.commit();
 }
        public async Task <IActionResult> Edit(int?id, string name)
        {
            UserEditViewModel model = new UserEditViewModel();

            await TryUpdateModelAsync(model, "", i => i.FIO, i => i.CareerStart, i => i.VacationStart, i => i.Avatar, i => i.AvatarPath, i => i.ApplicationUserId);

            // Валидация.
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using var db = AppContextFactory.DB;
            using var t  = db.Database.BeginTransaction();

            try
            {
                // Редактируем пользователя.
                var user = db.UserInfos.FirstOrDefault(i => i.Id == id) ?? new UserInfo();

                // Аватара Фрейи (да был такой НИП в WOTLK, вернуться бы в 10 класс...).
                // Новый аватар.
                if (model.Avatar != null)
                {
                    // Удаление старого файла, если он у нас есть.
                    if (!string.IsNullOrEmpty(model.AvatarPath))
                    {
                        AvatarHelper.DeleteFile(_env, model.AvatarPath);
                    }

                    // Сохранение нового файла.
                    string filePath = await AvatarHelper.SaveFile(model.Avatar, _env);

                    // Прикрепляем / обновляем файл к профилю пользователя.
                    user.AvatarPath = filePath;
                }

                // Обновляем данные пользователя.
                user.CareerStart   = model.CareerStart;
                user.Name          = model.FIO;
                user.VacationStart = model.VacationStart;
                user.UserId        = model.ApplicationUserId;

                if (user.Id == 0)
                {
                    db.Entry(user).State = EntityState.Added;
                }

                await db.SaveChangesAsync();

                await t.CommitAsync();
            }
            catch (Exception ex)
            {
                await t.RollbackAsync();

                ModelState.AddModelError("Error", "В процессе сохранения произошла ошибка! Ошибка: " + ex.Message);
            }

            return(RedirectToAction("Index"));
        }
Example #24
0
		public ActionResult Edit(string id)
		{
			#region validation

			if (string.IsNullOrEmpty(id))
			{
				return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid user ID");
			}
			var user = UserManager.FindById(id);
			if (user == null)
			{
				return new HttpStatusCodeResult(HttpStatusCode.NotFound, "User not found");
			}

			#endregion

			var model = new UserEditViewModel
			{
				Email = user.Email,
				FirstName = user.FirstName,
				LastName = user.LastName
			};
			return View(model);
		}
Example #25
0
        //[CustomAuthorize("Admin", "Customer", "Receptionist", "Client Service Agent")]
        public ActionResult EditUser(UserEditViewModel viewModel)
        {
            int roleId = 0;

            if (Session["RoleId"] != null && Session["RoleId"].ToString() != "")
            {
                roleId = Int32.Parse(Session["RoleId"].ToString());
            }
            SussexDBEntities db   = new SussexDBEntities();
            User             user = null;

            if (viewModel.UserId != 0)
            {
                user = db.Users.Where(w => w.UserId == viewModel.UserId).FirstOrDefault();
            }
            // new user
            if (user == null)
            {
                user                 = new User();
                user.UserType        = viewModel.UserType;
                user.UserJoinedDate  = DateTime.Now;
                user.UserIsActivated = true;
                user.UserEmail       = viewModel.Email;
            }

            if (user.RoleId == roleId)
            {
                user.RoleId = roleId;
            }
            else
            {
                user.RoleId = RoleTypes.CUSTOMER_ID;
            }
            if (roleId == 0)
            {
                user.RoleId = RoleTypes.CUSTOMER_ID;
            }
            user.UserFirstName = viewModel.FirstName;
            user.UserLastName  = viewModel.LastName;
            user.UserContactNo = viewModel.ContactNo;
            if (user.UserId == 0)
            {
                user.UserPassword = Crypto.Hash(viewModel.Password);
                db.Users.Add(user);
            }
            db.SaveChanges();
            PaymentHelper.StartMonthlySubscription(user.UserId);

            UserDetail userDetail = null;

            userDetail = db.UserDetails.Where(w => w.UserDetailId == viewModel.UserDetailId).FirstOrDefault();

            if (userDetail == null)
            {
                userDetail = new UserDetail();
            }
            userDetail.UserDetailBio        = viewModel.Bio;
            userDetail.UserDetailProfession = viewModel.Profession;
            userDetail.UserDetailAge        = viewModel.Age;
            userDetail.UserDetailGender     = viewModel.Gender;
            userDetail.UserId = user.UserId;

            if (userDetail.UserDetailId == 0)
            {
                db.UserDetails.Add(userDetail);
            }
            db.SaveChanges();
            if (roleId == RoleTypes.CUSTOMER_ID)
            {
                return(Redirect("/User/MyProfile"));
            }
            return(Redirect("/"));
        }
Example #26
0
		public async Task<ActionResult> Edit(UserEditViewModel model)
		{
			if (!ModelState.IsValid)
			{
				return View(model);
			}
			var user = await UserManager.FindByIdAsync(model.Id);
			if (user == null)
			{
				// Don't reveal that the user does not exist
				AddErrors(new IdentityResult("User not found"));
				return View(model);
			}
			// make sure email is not taken
			var otherUser = await UserManager.FindByEmailAsync(model.Email);
			if (otherUser != null && otherUser.Id != model.Id)
			{
				AddErrors(new IdentityResult("Email is already taken"));
				return View(model);
			}

			user.Email = model.Email;
			user.UserName = model.Email;
			user.FirstName = model.FirstName;
			user.LastName = model.LastName;

			var result = await UserManager.UpdateAsync(user);
			if (result.Succeeded)
			{
				return RedirectToAction("List");
			}
			AddErrors(result);
			return View(model);
		}
Example #27
0
 public EditUserCommand(UserEditViewModel ViewModel)
 {
     _ViewModel = ViewModel;
 }
Example #28
0
        public async Task <IActionResult> Edit(string UserId, UserEditViewModel userEditVM)
        {
            if (!ModelState.IsValid)
            {
                return(View(userEditVM));
            }

            var user = await _context.Users.FindAsync(UserId);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{UserId}'.");
            }

            var ChangeLog = new UsersChangeLog
            {
                HRID                 = user.HRID,
                StaffId              = user.StaffId,
                FirstName            = user.FirstName,
                MiddleName           = user.MiddleName,
                LastName             = user.LastName,
                Address              = user.Address,
                City                 = user.City,
                State                = user.State,
                ZipCode              = user.ZipCode,
                Country              = user.Country,
                Email                = user.Email,
                EmailConfirmed       = user.EmailConfirmed,
                PhoneNumber          = user.PhoneNumber,
                PhoneNumberConfirmed = user.PhoneNumberConfirmed,
                UserName             = user.UserName,
                HomeEmail            = user.HomeEmail,
                HomeEmailConfirmed   = user.HomeEmailConfirmed,
                CreatedAt            = user.CreatedAt,
                DeletedAt            = user.DeletedAt,
                UpdatedAt            = DateTime.Now
            };
            await _context.UsersChangeLog.AddAsync(ChangeLog);

            await _context.SaveChangesAsync();

            user.StaffId   = userEditVM.StaffId;
            user.Address   = userEditVM.Address;
            user.City      = userEditVM.City;
            user.State     = userEditVM.State;
            user.ZipCode   = userEditVM.ZipCode;
            user.Country   = userEditVM.Country;
            user.HomeEmail = userEditVM.HomeEmail;
            user.CreatedAt = ChangeLog.CreatedAt;
            user.UpdatedAt = ChangeLog.UpdatedAt;
            _context.Users.Update(user);
            await _context.SaveChangesAsync();

            var username = userEditVM.Username;

            if (userEditVM.Username != username)
            {
                var setUsernameResult = await _userManager.SetUserNameAsync(user, userEditVM.Username);

                if (!setUsernameResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting username for user with ID '{user.Id}'.");
                }
            }

            var email = user.Email;

            if (userEditVM.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, userEditVM.Email);

                if (!setEmailResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }
            }

            var phoneNumber = user.PhoneNumber;

            if (userEditVM.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, userEditVM.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
                }
            }

            StatusMessage = "Profile has been updated";
            return(RedirectToAction(nameof(Edit), new { @UserId = UserId }));
        }
Example #29
0
        public IActionResult Getuserinfo(string strlist)
        {
            var response = ResponseModelFactory.CreateResultInstance;

            using (_dbContext)
            {
                var code = strlist;
                //TODO:钉钉相关的配置信息都要放到配置文件中
                string suiteKey    = "dinga7xg5vjb2lwwvicu";
                string suiteSecret = "pUiI0xvN0ZEbsFavSbuaLqctwHL2p9cIRlQ4HU5GS7y-TmYngcTjJGuI309ZLR_h";
                string timestamp   = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000).ToString();
                string suiteTicket = "TestSuiteTicket";
                string signature1  = timestamp + "\n" + suiteTicket;
                string signature2  = HmacSHA256(signature1, suiteSecret);
                string signature   = System.Web.HttpUtility.UrlEncode(signature2, System.Text.Encoding.UTF8);
                string auth_corpid = strlist;
                string url         = "https://oapi.dingtalk.com/gettoken?appkey=" + suiteKey + "&appsecret=" + suiteSecret;

                try
                {
                    var response11 = Haikan3.Utils.DingDingHelper.HttpGet(url);
                    var result     = Newtonsoft.Json.JsonConvert.DeserializeObject <HaikanCRM.Api.ViewModels.DIngDing.PersistentCodeResult>(response11);
                    if (result != null && result.errcode == "0")
                    {
                        string url11      = "https://oapi.dingtalk.com/user/getuserinfo?access_token=" + result.access_token + "&code=" + code;
                        var    response12 = Haikan3.Utils.DingDingHelper.HttpGet(url11);
                        var    result12   = Newtonsoft.Json.JsonConvert.DeserializeObject <HaikanCRM.Api.ViewModels.DIngDing.PersistentCodeResult12>(response12);
                        if (result12 != null && result12.errcode == 0)
                        {
                            //获取人员信息
                            //var results = Haikan3.Utils.DingDingHelper.GetUserDetail(result.access_token, result12.userid);
                            var roiduuid = _dbContext.SystemRole.FirstOrDefault(x => x.RoleName == "客户经理");
                            var userdata = _dbContext.SystemUser.Where(x => x.Streets == result12.userid).ToList().Count;
                            if (userdata == 0)
                            {
                                UserEditViewModel model = new UserEditViewModel();
                                string            pas   = "******";
                                var entity = new HaikanCRM.Api.Entities.SystemUser();
                                entity.SystemUserUuid = Guid.NewGuid();
                                entity.Streets        = result12.userid;
                                entity.AddTime        = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                entity.RealName       = result12.name;
                                entity.LoginName      = result12.name;
                                //entity.PassWord = Haikan3.Utils.DesEncrypt.Encrypt(pas.Trim(), MdDesEncrypt.SecretKey);
                                entity.PassWord       = Security.GenerateMD5(pas.Trim());
                                entity.SystemRoleUuid = roiduuid.SystemRoleUuid.ToString();
                                entity.IsDeleted      = 0;
                                entity.ZaiGang        = "在岗";
                                entity.UserType       = 2;
                                _dbContext.SystemUser.Add(entity);
                                _dbContext.SaveChanges();
                                _dbContext.Database.ExecuteSqlRaw("DELETE FROM SystemUserRoleMapping WHERE SystemUserUUID={0}", entity.SystemUserUuid);
                                var success = true;
                                ////循环加权限
                                //for (int i = 0; i < model.SystemRoleUuid.Count; i++)
                                //{
                                if (entity.SystemRoleUuid != null)
                                {
                                    var roles = new SystemUserRoleMapping();
                                    roles.SystemUserUuid = entity.SystemUserUuid;
                                    roles.SystemRoleUuid = Guid.Parse(entity.SystemRoleUuid);
                                    roles.AddTime        = DateTime.Now.ToString("yyyy-MM-dd");
                                    roles.AddPeople      = AuthContextService.CurrentUser.DisplayName;

                                    _dbContext.SystemUserRoleMapping.Add(roles);
                                }
                                //}
                                success = _dbContext.SaveChanges() > 0;
                                if (success)
                                {
                                    response.SetSuccess();
                                }
                                else
                                {
                                    _dbContext.Database.ExecuteSqlRaw("DELETE FROM SystemUser WHERE SystemUserUUID={0}", entity.SystemUserUuid);
                                    response.SetFailed("保存用户角色数据失败");
                                }
                            }
                            var user           = _dbContext.SystemUser.FirstOrDefault(x => x.IsDeleted == 0 && x.Streets == result12.userid);
                            var role           = _dbContext.SystemRole.FirstOrDefault(x => x.SystemRoleUuid == Guid.Parse(user.SystemRoleUuid));
                            var claimsIdentity = new ClaimsIdentity(new Claim[]
                            {
                                new Claim(ClaimTypes.Name, result12.userid),
                                new Claim("guid", user.SystemUserUuid.ToString()),
                                new Claim("avatar", ""),
                                new Claim("displayName", user.RealName),
                                new Claim("loginName", user.LoginName),
                                new Claim("emailAddress", ""),
                                //new Claim("guid",user.SystemUserUuid.ToString()),
                                //new Claim("userType",usertype.ToString()),
                                new Claim("userType", user.UserType.Value.ToString()),
                                new Claim("roleid", user.SystemRoleUuid.TrimEnd(',')),
                                new Claim("roleName", role.RoleName.TrimEnd(',')),
                                new Claim("ZYZ", ""),
                                new Claim("YH", ""),
                                new Claim("DDY", ""),
                                new Claim("SJ", "")
                            });
                            var token = JwtBearerAuthenticationExtension.GetJwtAccessToken(_appSettings, claimsIdentity);

                            response.SetData(new { user, token });

                            return(Ok(response));
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return(Ok(response));
        }
Example #30
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AuthPolicies.ManageUserByUserIdPolicy);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), AuthPolicies.AssignRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Xung đột user id trong tham số và mô hình dữ liệu"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                if (Utilities.GetUserId(this.User) == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    {
                        return(BadRequest("Mật khẩu hiện tại được yêu cầu khi thay đổi mật khẩu của riêng bạn"));
                    }

                    if (appUser.UserName != user.UserName)
                    {
                        return(BadRequest("Mật khẩu hiện tại được yêu cầu khi thay đổi tên người dùng của bạn"));
                    }
                }


                bool isValid = true;

                if (Utilities.GetUserId(this.User) == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new string[] { "Tên tài khoản/Mật khẩu không hợp lệ." });
                    }
                }

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Item1)
                    {
                        if (!string.IsNullOrWhiteSpace(user.NewPassword))
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
Example #31
0
 public async Task <IActionResult> UpdateCurrentUser([FromBody] UserEditViewModel user)
 {
     return(await UpdateUser(HelperMethods.GetUserId(User), user));
 }
Example #32
0
 public FollowCommand(UserEditViewModel ViewModel)
 {
     _ViewModel = ViewModel;
 }
        public async Task <IActionResult> Edit(UserEditViewModel details)
        {
            User user = await userManager.FindByIdAsync(details.Id);

            IdentityResult result;

            if (user != null)
            {
                if (!string.IsNullOrEmpty(details.Password))
                {
                    result = await passwordValidator.ValidateAsync(userManager, user, details.Password);

                    if (result.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, details.Password);
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }

                if (user.Email != details.Email && !string.IsNullOrEmpty(details.Email))
                {
                    user.Email = details.Email;
                    result     = await userValidator.ValidateAsync(userManager, user);

                    if (!result.Succeeded)
                    {
                        AddErrorsFromResult(result);
                    }
                }

                if (user.Name != details.Name)
                {
                    user.Name = details.Name;
                }
                if (user.LastName != details.LastName)
                {
                    user.LastName = details.LastName;
                }
                if (user.DNI != details.DNI)
                {
                    user.DNI = details.DNI;
                }
                if (user.Address != details.Address)
                {
                    user.Address = details.Address;
                }
                if (user.City != details.City)
                {
                    user.City = details.City;
                }
                if (user.Province != details.Province)
                {
                    user.Province = details.Province;
                }
                if (user.ZipCode != details.ZipCode)
                {
                    user.ZipCode = details.ZipCode;
                }

                result = await userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrorsFromResult(result);
                }
            }
            else
            {
                ModelState.AddModelError("", "Usuario no encontrado");
            }
            return(Redirect(details.ReturnUrl ?? "/"));
        }
        public async Task <IdentityResult> ChangePasswordAsync(UserEditViewModel userEditVM)
        {
            GolfioUser golfioUser = await _userManager.FindByIdAsync(userEditVM.GolfioUser.Id);

            return(await _userManager.ChangePasswordAsync(golfioUser, userEditVM.OldPassword, userEditVM.NewPassword));
        }
Example #35
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AuthPolicies.ManageUserByUserIdPolicy);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), AuthPolicies.AssignRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                if (Utilities.GetUserId(this.User).ToString() == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    {
                        return(BadRequest("Current password is required when changing your own password"));
                    }

                    if (appUser.UserName != user.UserName)
                    {
                        return(BadRequest("Current password is required when changing your own username"));
                    }
                }


                bool isValid = true;

                if (Utilities.GetUserId(this.User).ToString() == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new string[] { "The username/password couple is invalid." });
                    }
                }

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Item1)
                    {
                        if (!string.IsNullOrWhiteSpace(user.NewPassword))
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }


                        var value = user;
                        //update profierimage
                        //save logo to physical file
                        if (value.profier != null && !string.IsNullOrEmpty(value.profier.Name) && !string.IsNullOrEmpty(value.profier.Value))
                        {
                            //Convert Base64 Encoded string to Byte Array.
                            var    base64String = value.profier.Value;
                            var    fileName     = value.profier.Name;
                            byte[] imageBytes   = Convert.FromBase64String(base64String);

                            //Save the Byte Array as Image File.
                            string filePath = fileName.WebRootPathProfier(Guid.NewGuid().ToString(), _env);
                            imageBytes.WriteAllBytes(filePath);

                            //store filename to DB
                            appUser.ProfilerImage = filePath.GetFileName();

                            result = await _accountManager.UpdateUserAsync(appUser, user.Roles);
                        }

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
Example #36
0
 public async Task <IActionResult> UpdateCurrentUser([FromBody] UserEditViewModel user)
 {
     return(await UpdateUser(Utilities.GetUserId(this.User), user));
 }
        public ActionResult Create(UserEditViewModel viewModel)
        {
            try
            {
                var user = new User();
                user.Name                   = viewModel.Name;
                user.Character              = characterService.GetByName(viewModel.CharacterName);
                user.SkillCards             = new List <SkillCard>();
                user.ShopCards              = new List <ShopCard>();
                user.ClassEquipmentCards    = new List <ClassEquipmentCard>();
                user.FamiliarCards          = new List <FamiliarCard>();
                user.OverlordCards          = new List <OverlordCard>();
                user.RemainingOverlordCards = new List <OverlordCard>();
                user.HandOverlordCards      = new List <OverlordCard>();
                user.DiscardedOverlordCards = new List <OverlordCard>();
                // user.Lieutenants = new List<Lieutenant>();
                // user.Monsters = new List<Monster>();
                user.OverlordRelics = new List <OverlordRelicCard>();

                // Set newly selected SkillCards based on user selection in the UI
                var allSkillCards      = skillCardService.Get();
                var selectedSkillCards = viewModel.SkillCards.Where(x => x.Selected);

                foreach (var card in allSkillCards)
                {
                    if (selectedSkillCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        user.SkillCards.Add(card);
                    }
                }

                // Set newly selected ClassEquipmentCards based on user selection in the UI
                var allClassEquipmentCards      = classEquipmentCardService.Get();
                var selectedClassEquipmentCards = viewModel.ClassEquipmentCards.Where(x => x.Selected);

                foreach (var card in allClassEquipmentCards)
                {
                    if (selectedClassEquipmentCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        user.ClassEquipmentCards.Add(card);
                    }
                }

                // Set newly selected ShopCards based on user selection in the UI
                var allShopCards      = shopCardService.Get();
                var selectedShopCards = viewModel.ShopCards.Where(x => x.Selected);

                foreach (var card in allShopCards)
                {
                    if (selectedShopCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        user.ShopCards.Add(card);
                    }
                }

                // Set newly selected FamiliarCards based on user selection in the UI
                var allFamiliarCards      = familiarCardService.Get();
                var selectedFamiliarCards = viewModel.FamiliarCards.Where(x => x.Selected);

                foreach (var card in allFamiliarCards)
                {
                    if (selectedFamiliarCards.Where(x => x.DisplayName == card.Name).Any())
                    {
                        user.FamiliarCards.Add(card);
                    }
                }

                userService.Create(user);
                GameHandler.Users.Add(user);
                //_gameHandler.Users.Add(user);
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception)
            {
                return(View());
            }
        }
Example #38
0
        public ActionResult Edit(UserEditViewModel userprofile)
       {
                string email = User.Identity.Name;

                ApplicationUser user = db.Users.FirstOrDefault(u => u.Email.Equals(email));

                user.FirstName = userprofile.FirstName;
                user.LastName = userprofile.LastName;
                user.ProfilePicture = userprofile.ProfilePicture;
                user.Location = userprofile.Location;
                user.FavoritePizzaria = userprofile.FavoritePizzaria;
                user.PizzaEatingStyle = userprofile.PizzaEatingStyle;

                db.Entry(user).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("ViewProfile");
       }
Example #39
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AccountManagementOperations.Update);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, (user.Roles, currentRoles), Authorization.Policies.AssignAllowedRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }

                bool isPasswordChanged = !string.IsNullOrWhiteSpace(user.NewPassword);
                bool isUserNameChanged = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase);

                if (Utilities.GetUserId(this.User) == id)
                {
                    if (string.IsNullOrWhiteSpace(user.CurrentPassword))
                    {
                        if (isPasswordChanged)
                        {
                            AddError("Current password is required when changing your own password", "Password");
                        }

                        if (isUserNameChanged)
                        {
                            AddError("Current password is required when changing your own username", "Username");
                        }
                    }
                    else if (isPasswordChanged || isUserNameChanged)
                    {
                        if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                        {
                            AddError("The username/password couple is invalid.");
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    _mapper.Map <UserEditViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Succeeded)
                    {
                        if (isPasswordChanged)
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Succeeded)
                        {
                            return(NoContent());
                        }
                    }

                    AddError(result.Errors);
                }
            }

            return(BadRequest(ModelState));
        }
        public ActionResult Update(UserEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = this.users.Update(model.Id, model.UserName, model.FirstName, model.LastName, model.PhoneNumber, model.Email);
                TempData["Success"] = "User updated successfully.";
                return Redirect($"~/admin/users/edit/{user.Id}");
            }

            return View("Edit", model);
        }
Example #41
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AuthPolicies.ManageUserByUserIdPolicy);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), AuthPolicies.AssignRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be empty"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                if (Utilities.GetUserId(this.User) == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    {
                        return(BadRequest("Current password is required when changing your own password"));
                    }

                    if (appUser.UserName != user.UserName)
                    {
                        return(BadRequest("Current password is required when changing your own username"));
                    }
                }


                bool isValid = true;

                if (Utilities.GetUserId(this.User) == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new string[] { "The username/password couple is invalid." });
                    }
                }

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Item1)
                    {
                        if (!string.IsNullOrWhiteSpace(user.NewPassword))
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
Example #42
0
 public RemoveFriendCommand(UserEditViewModel ViewModel)
 {
     _ViewModel = ViewModel;
 }
        //[HttpPut("users/{id}")]
        public async Task <IActionResult> UpdateUser(string id, string currentUserId, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            //string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            //var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AccountManagementOperations.Update);
            //var assignRolePolicy = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), Authorization.Policies.AssignAllowedRolesPolicy);


            //if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            //    return new ChallengeResult();


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                //if (Utilities.GetUserId(this.User) == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                //{
                //    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                //        return BadRequest("Current password is required when changing your own password");

                //    if (appUser.UserName != user.UserName)
                //        return BadRequest("Current password is required when changing your own username");
                //}

                bool isValid = true;

                var systemUser = await _userManager.FindByIdAsync(id);

                if ((systemUser.UserName.ToUpper().Trim() != user.UserName.ToUpper().Trim()) && id == currentUserId)
                {
                    // Validate the username/password parameters and ensure the account is not locked out.
                    var value = await _signInManager.CheckPasswordSignInAsync(systemUser, user.CurrentPassword, true);

                    if (value.Succeeded)
                    {
                        isValid = true;
                    }
                    else
                    {
                        return(BadRequest("Invalid password"));
                    }
                }

                //if (Utilities.GetUserId(this.User) == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                //{
                //    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                //    {
                //        isValid = false;
                //        AddErrors(new string[] { "Entered current password is invalid." });
                //    }
                //}

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    //if (result.Item1)
                    //{
                    //    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    //    {
                    //        if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                    //            result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                    //        else
                    //            result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                    //    }

                    //    if (result.Item1)
                    //        return NoContent();
                    //}

                    if (result.Item1)
                    {
                        return(NoContent());
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
Example #44
0
       public ActionResult Edit()
        {
            string username = User.Identity.Name;

            ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));
            UserEditViewModel model = new UserEditViewModel();
            model.FirstName = user.FirstName;
            model.LastName = user.LastName;
            model.ProfilePicture = user.ProfilePicture;
            model.Location = user.Location;
            model.FavoritePizzaria = user.FavoritePizzaria;
            model.PizzaEatingStyle = user.PizzaEatingStyle;

            return View(model);
        }