public ActionResult Edit(UserEditModel model)
        {
            if (ModelState.IsValid)
            {
                this.UsersServices.Update(model.Id, model.Email);
                TempData["Success"] = "User email updated successfully.";
                return this.RedirectToAction("Index");
            }

            return this.View("Edit", model);
        }
Beispiel #2
0
        public ActionResult GetUserInfo(int userId)
        {
            var resp = _userManager.GetWfsUserInfoById(new GetWfsUserInfoByIdRequest() { UserId = userId });

            var m = new UserEditModel()
            {
                UserInfo = resp.Value
            };

            var uiresult = new UIResponse<UserEditModel>();
            uiresult.Subject = m;
            uiresult.HtmlResult = RenderPartialViewToString("UserInfo", m);
            uiresult.Status = resp.Status;
            return Json(uiresult, JsonRequestBehavior.AllowGet);
        }
Beispiel #3
0
        public ActionResult UpdateUserBalance(UserEditModel model)
        {
            var resp = _userManager.SaveUserAccountCredits(new SaveWFSUserRequest()
            {
                UserInfo = model.UserInfo
            });

            if (resp.Status == Status.Success)
            {
                var uiresponse = resp.ToUIResult<UserEditModel, WFSUser>(x => model, x => RenderPartialViewToString("UserInfo", x));
                return Json(uiresponse);
            }
            else
            {
                var uiResp = resp.ToUIResult<UserEditModel, WFSUser>(x => model, x =>
                {
                    x.Merge(resp);
                    return RenderPartialViewToString("UserInfo", model);
                });
                return Json(uiResp);
            }
        }
        public async Task <IActionResult> Edit(UserEditModel userEditModel)
        {
            await _userService.UserEdit(userEditModel);

            return(RedirectToAction("Index", "Project"));
        }
Beispiel #5
0
 public UserEditModel Add()
 {
     return(UserEditModel.Create(_db));
     //return View("Edit", UserEditModel.Create(_db));
 }
Beispiel #6
0
        public AppUser EditUser(long userId, UserEditModel userData)
        {
            int count = 0;

            var user = Repository.GetUser(userId);

            if (user.Name != userData.Name)
            {
                user.Name = userData.Name;
                count++;
            }

            if (user.IsPublicUser != userData.IsPublic)
            {
                user.IsPublicUser = userData.IsPublic;
                count++;
            }

            if (!string.IsNullOrEmpty(userData.Email) && user.Email != userData.Email)
            {
                user.Email = userData.Email;
            }

            if (!string.IsNullOrEmpty(userData.PhotoUrl))
            {
                user.PhotoUrl = userData.PhotoUrl;
                count++;
            }

            if (!string.IsNullOrEmpty(userData.OldPassword) && ComputeHash(userData.OldPassword) == user.PasswordHash && !string.IsNullOrEmpty(userData.NewPassword) &&
                userData.NewPassword == userData.NewPasswordConfirm)
            {
                user.Password     = userData.NewPassword;
                user.PasswordHash = ComputeHash(userData.NewPassword);
                count++;
            }
            if (!string.IsNullOrEmpty(userData.OldPassword))
            {
                if (ComputeHash(userData.OldPassword) != user.PasswordHash)
                {
                    throw new MovieUniverseException(ExceptionType.InvalidPassword);
                }
                if (string.IsNullOrEmpty(userData.NewPassword) || userData.NewPassword != userData.NewPasswordConfirm)
                {
                    throw new MovieUniverseException(ExceptionType.InvalidNewPassword);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(userData.NewPassword) || !string.IsNullOrEmpty(userData.NewPasswordConfirm))
                {
                    throw new MovieUniverseException(ExceptionType.InvalidPassword);
                }
            }
            if (count > 0)
            {
                Repository.Save();
            }

            return(user);
        }
Beispiel #7
0
        public JsonResult Add(UserEditModel model)
        {
            if (string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Password is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            var mongo = new MongoHelper();

            var filter = Builders <BsonDocument> .Filter.Eq("Username", model.Username);

            var count = mongo.Count(Constant.UserCollectionName, filter);

            if (count > 0)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username is already existed.",
                }));
            }

            var now = DateTime.Now;

            var salt = DateTime.Now.ToString("yyyyMMddHHmmss");

            var doc = new BsonDocument
            {
                ["ID"]         = ObjectId.GenerateNewId(),
                ["Username"]   = model.Username,
                ["Password"]   = MD5Helper.Encrypt(model.Password + salt),
                ["Name"]       = model.Name,
                ["Gender"]     = 0,
                ["Phone"]      = "",
                ["Email"]      = "",
                ["QQ"]         = "",
                ["CreateTime"] = now,
                ["UpdateTime"] = now,
                ["Salt"]       = salt,
                ["Status"]     = 0,
            };

            mongo.InsertOne(Constant.UserCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
        public ActionResult Edit(UserEditModel model)
        {
            if (!User.Id().Equals(model.Username, StringComparison.OrdinalIgnoreCase) && !User.IsInRole(Definitions.Roles.Administrator))
            {
                return RedirectToAction("Unauthorized", "Home");
            }

            if (ModelState.IsValid)
            {
                bool valid = true;

                if (!User.IsInRole(Definitions.Roles.Administrator) && (model.OldPassword == null && model.NewPassword != null))
                {
                    ModelState.AddModelError("OldPassword", Resources.Account_Edit_OldPasswordEmpty);
                    valid = false;
                }

                if (model.OldPassword != null && MembershipService.ValidateUser(model.Username, model.OldPassword) != ValidationResult.Success)
                {
                    ModelState.AddModelError("OldPassword", Resources.Account_Edit_OldPasswordIncorrect);
                    valid = false;
                }

                if (User.IsInRole(Definitions.Roles.Administrator) && model.Username.Equals(User.Id(), StringComparison.OrdinalIgnoreCase) && !(model.Roles != null && model.Roles.Contains(Definitions.Roles.Administrator)))
                {
                    ModelState.AddModelError("Roles", Resources.Account_Edit_CannotRemoveYourselfFromAdminRole);
                    valid = false;
                }

                if (valid)
                {
                    MembershipService.UpdateUser(model.Username, model.Name, model.Surname, model.Email, model.NewPassword);
                    RoleProvider.RemoveUserFromRoles(model.Username, RoleProvider.GetAllRoles());
                    if (model.Roles != null)
                    {
                        RoleProvider.AddUserToRoles(model.Username, model.Roles);
                    }
                    ViewBag.UpdateSuccess = true;
                }
            }

            PopulateRoles();
            return View(model);
        }
Beispiel #9
0
        private async void btnOK_Click(object sender, RoutedEventArgs e)
        {
            #region 新增
            if (Om == OperationMode.AddMode)
            {
                string strErrorMsg = string.Empty;
                try
                {
                    UserEditModel newUserEditModel = new UserEditModel();
                    //SysUser newSysUser = new SysUser();
                    newUserEditModel.UserCode = txtUserCode.Text.Trim();
                    newUserEditModel.Name = txtName.Text.Trim();
                    newUserEditModel.LoginName = txtLoginName.Text.Trim();
                    newUserEditModel.Password = "******";
                    newUserEditModel.Sex = (UserSex)(cmbSex.SelectedIndex + 1);
                    //newSysUser.Picture
                    //newUserEditModel.Picture = this.GetBytesByImagePath(this.image.Tag.ToString());
                    newUserEditModel.Password = txtPassWord.Password.Trim();
                    newUserEditModel.Mobile = txtMobile.Text.Trim();
                    newUserEditModel.OfficialPhone = txtOfficialPhone.Text.Trim();
                    newUserEditModel.Email = txtEmail.Text.Trim();
                    newUserEditModel.Position = txtPosition.Text.Trim();
                    newUserEditModel.Remark = txtRemark.Text.Trim();
                    newUserEditModel.NeedChangePassword = chkNeedChangePassword.IsChecked.HasValue ? chkNeedChangePassword.IsChecked.Value : false;
                    newUserEditModel.IsLeader = chkIsLeader.IsChecked.HasValue ? chkIsLeader.IsChecked.Value : false;
                    newUserEditModel.IsOnline = false;
                    newUserEditModel.Stopped = false;


                    newUserEditModel = await userAsyncProxy.CallAsync(c => c.Add(newUserEditModel));
                    //MessageDialogResult result = await DialogManager.ShowMessageAsync(this, UIResources.MsgInfo, "新增用户成功!", MessageDialogStyle.Affirmative, null);
                    this.ShowAutoCloseDialogOwter(UIResources.MsgInfo, "新增用户成功!");
                    this.DialogResult = true;
                }
                catch (TimeoutException timeProblem)
                {
                    strErrorMsg = timeProblem.Message + UIResources.TimeOut + timeProblem.Message;
                }
                catch (FaultException<LCFault> af)
                {
                    strErrorMsg = af.Detail.Message;
                }
                catch (FaultException unknownFault)
                {
                    strErrorMsg = UIResources.UnKnowFault + unknownFault.Message;
                }
                catch (CommunicationException commProblem)
                {
                    strErrorMsg = UIResources.ConProblem + commProblem.Message + commProblem.StackTrace;
                }
                if (strErrorMsg != string.Empty)
                {
                    await DialogManager.ShowMessageAsync(this, UIResources.MsgError, "新增用户失败!原因:" + strErrorMsg, MessageDialogStyle.Affirmative, null);
                    //AisinoMessageBox.Show("新增用户失败!原因:" + strMsg, UIResources.MsgError, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                }
            }

            #endregion

            #region 修改
            else
            {
                string strErrorMsg = string.Empty;
                try
                {
                    SelectSysUser.Name = txtName.Text.Trim();
                    SelectSysUser.LoginName = txtLoginName.Text.Trim();
                    SelectSysUser.Sex = (UserSex)(cmbSex.SelectedIndex + 1);
                    //SelectSysUser.User.Picture
                    //SelectSysUser.Picture=this.GetBytesByImagePic(this.image, SelectSysUser.Picture);
                    SelectSysUser.Mobile = txtRemark.Text.Trim();
                    SelectSysUser.OfficialPhone = txtOfficialPhone.Text.Trim();
                    SelectSysUser.Email = txtEmail.Text.Trim();
                    SelectSysUser.Position = txtPosition.Text.Trim();
                    SelectSysUser.Remark = txtRemark.Text.Trim();
                    SelectSysUser.NeedChangePassword = chkNeedChangePassword.IsChecked.HasValue ? chkNeedChangePassword.IsChecked.Value : false;
                    SelectSysUser.IsLeader = chkIsLeader.IsChecked.HasValue ? chkIsLeader.IsChecked.Value : false;
                    SelectSysUser.Stopped = false;
                    SelectSysUser.Password = txtPassWord.Password.Trim();

                    SelectSysUser = await userAsyncProxy.CallAsync(c => c.Update(SelectSysUser));
                    //MessageDialogResult result = await DialogManager.ShowMessageAsync(this, UIResources.MsgInfo, "修改用户成功!", MessageDialogStyle.Affirmative, null);
                    this.ShowAutoCloseDialogOwter(UIResources.MsgInfo, "修改用户成功!");
                    this.DialogResult = true;
                }
                catch (TimeoutException timeProblem)
                {
                    strErrorMsg = timeProblem.Message + UIResources.TimeOut + timeProblem.Message;
                }
                catch (FaultException<LCFault> af)
                {
                    strErrorMsg = af.Detail.Message;
                }
                catch (FaultException unknownFault)
                {
                    strErrorMsg = UIResources.UnKnowFault + unknownFault.Message;
                }
                catch (CommunicationException commProblem)
                {
                    strErrorMsg = UIResources.ConProblem + commProblem.Message + commProblem.StackTrace;
                }
                if (strErrorMsg != string.Empty)
                {
                    await DialogManager.ShowMessageAsync(this, UIResources.MsgError, "修改用户失败!原因:" + strErrorMsg, MessageDialogStyle.Affirmative, null);
                    //AisinoMessageBox.Show("修改用户失败!原因:" + strMsg, UIResources.MsgError, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                }
            }
            #endregion
        }
        public async Task <object> Put([FromBody] UserEditModel user)
        {
            var output = new ResponseDetail();

            try
            {
                if (ModelState.IsValid && user != null)
                {
                    var userDetail = !string.IsNullOrEmpty(user.Id) ? await _userManager.FindByIdAsync(user.Id) : null;

                    if (userDetail != null)
                    {
                        userDetail.Id                   = user.Id;
                        userDetail.Email                = user.Email;
                        userDetail.EmailConfirmed       = true;
                        userDetail.PasswordHash         = user.Password;
                        userDetail.SecurityStamp        = user.SecurityStamp;
                        userDetail.PhoneNumberConfirmed = user.PhoneNumberConfirmed;
                        userDetail.TwoFactorEnabled     = user.TwoFactorEnabled;
                        userDetail.LockoutEnabled       = user.LockoutEnabled;
                        userDetail.AccessFailedCount    = user.AccessFailedCount;
                        userDetail.TwoFactorEnabled     = user.TwoFactorEnabled;
                        userDetail.UserName             = user.Email;
                        userDetail.FirstName            = user.FirstName;
                        userDetail.MiddelName           = user.MiddelName;
                        userDetail.LastName             = user.LastName;
                        userDetail.Contact              = user.Contact;
                        userDetail.DesignationID        = user.DesignationID;
                        userDetail.RoleID               = user.RoleID;
                        userDetail.Address              = user.Address;
                        userDetail.Status               = user.Status;
                        userDetail.Delete               = user.Delete;
                        userDetail.CreatedDate          = user.CreatedDate;
                        userDetail.ModifiedDate         = DateTime.Now;
                        userDetail.DesignationName      = user.DesignationName;
                        userDetail.ConcurrencyStamp     = user.ConcurrencyStamp;
                        userDetail.NormalizedEmail      = user.NormalizedEmail;
                        userDetail.NormalizedUserName   = user.NormalizedUserName;
                        userDetail.LockoutEnd           = user.LockoutEnd;

                        var chkUser = await _userManager.UpdateAsync(userDetail);

                        if (chkUser.Succeeded)
                        {
                            output.Message = "User updated successfully!";
                            output.Success = true;
                            return(output);
                        }
                        output.Success = false;
                        output.Message = chkUser.Errors.ToString();
                        return(output);
                    }
                    output.Success = false;
                    output.Message = "Error Occured";
                    return(output);
                }
                output.Success = false;
                return(output);
            }
            catch (Exception ex)
            {
                output.Success = false;
                output.Message = ex.Message;
                return(output);
            }
        }
Beispiel #11
0
        public JsonResult Edit(UserEditModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (string.IsNullOrEmpty(model.RoleID))
            {
                model.RoleID = "";
            }

            var mongo = new MongoHelper();

            // 判断是否是系统内置用户
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.UserCollectionName, filter);

            if (doc == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The user is not existed."
                }));
            }

            var userName = doc["Username"].ToString();

            if (userName == "admin")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Modifying system built-in users is not allowed."
                }));
            }

            // 判断用户名是否重复
            var filter1 = Builders <BsonDocument> .Filter.Ne("ID", objectId);

            var filter2 = Builders <BsonDocument> .Filter.Eq("Username", model.Username);

            filter = Builders <BsonDocument> .Filter.And(filter1, filter2);

            var count = mongo.Count(Constant.UserCollectionName, filter);

            if (count > 0)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username is already existed.",
                }));
            }

            filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var update1 = Builders <BsonDocument> .Update.Set("Username", model.Username);

            var update2 = Builders <BsonDocument> .Update.Set("Name", model.Name);

            var update3 = Builders <BsonDocument> .Update.Set("RoleID", model.RoleID);

            var update4 = Builders <BsonDocument> .Update.Set("DeptID", model.DeptID);

            var update5 = Builders <BsonDocument> .Update.Set("UpdateTime", DateTime.Now);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2, update3, update4, update5);

            mongo.UpdateOne(Constant.UserCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
        public ActionResult Edit([Bind(Include = "id,name,realName,certificateType,certificateNo,mobile,email,password,password2,state,gender,postId,officePhone,picture,deptId,deptChild,roleId")] UserEditModel model)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToRoute(new { controller = "Login", action = "LogOut" }));
            }
            int user = PageValidate.FilterParam(User.Identity.Name);

            if (!RoleCheck.CheckHasAuthority(user, db, "用户管理") && user != model.id)
            {
                return(RedirectToRoute(new { controller = "Error", action = "Index", err = "没有权限!" }));
            }
            setSelect();
            if (ModelState.IsValid)
            {
                if (model.deptChild != null && model.deptId != null)
                {
                    List <SelectOption> options = DropDownList.getDepartment((int)model.deptId);
                    ViewBag.DeptChild = DropDownList.SetDropDownList(options);
                }
                User_Info info = db.User_Info.Find(model.id);
                info.ToDecrypt();
                if (info == null)
                {
                    ViewBag.msg = "该用户可能已被删除,无法更改。";
                    goto next;
                }
                model.toUserInfoDB(info);
                if (db.User_Info.Where(x => x.user_name == info.user_name && x.user_id != info.user_id).Count() > 0)
                {
                    ViewBag.msg = "该用户名已注册。";
                    goto next;
                }
                if (!string.IsNullOrEmpty(model.password))
                {
                    if (model.password != model.password2)
                    {
                        ViewBag.msg = "两次输入密码不一致,请重新输入。";
                        goto next;
                    }
                    var salt = Guid.NewGuid().ToString("N").Substring(0, 10).ToUpper();
                    info.user_password = PasswordUnit.getPassword(model.password.ToUpper(), salt);
                    info.user_salt     = salt;
                }
                info.ToEncrypt();
                if (db.User_Info.Where(x => (x.user_certificate_type == info.user_certificate_type && x.user_certificate_no == info.user_certificate_no) && x.user_id != info.user_id).Count() > 0)
                {
                    ViewBag.msg = "该证件号已注册。";
                    goto next;
                }
                if (db.User_Info.Where(x => x.user_email == info.user_email && x.user_id != info.user_id).Count() > 0)
                {
                    ViewBag.msg = "该邮箱已注册。";
                    goto next;
                }
                if (db.User_Info.Where(x => x.user_mobile == info.user_mobile && x.user_id != info.user_id).Count() > 0)
                {
                    ViewBag.msg = "该手机号已注册。";
                    goto next;
                }
                db.Entry <User_Info>(info).State = EntityState.Modified;
                bool        edit   = true;
                User_Extend extend = db.User_Extend.Find(info.user_id);
                if (extend == null)
                {
                    edit           = false;
                    extend         = new User_Extend();
                    extend.user_id = info.user_id;
                }
                if (!string.IsNullOrEmpty(model.picture) && model.picture != extend.user_picture)
                {
                    string photoDir = ConfigurationManager.AppSettings["photoPath"];
                    if (!Directory.Exists(photoDir))
                    {
                        Directory.CreateDirectory(photoDir);
                    }
                    string photoTempDir   = ConfigurationManager.AppSettings["tempPhotoPath"];
                    string file_name      = string.Format("{0}{1}", photoDir, model.picture).Replace("_temp", "");
                    string temp_file_name = string.Format("{0}{1}", photoTempDir, model.picture);
                    if (System.IO.File.Exists(temp_file_name))
                    {
                        FileInfo fi = new FileInfo(temp_file_name);
                        fi.CopyTo(file_name, true);
                        model.picture = Path.GetFileName(file_name);
                    }
                    else
                    {
                        ViewBag.msg = "图片保存失败。";
                    }
                }
                model.toUserExtendDB(extend);
                extend.user_edit_time = DateTime.Now;
                extend.user_edit_user = PageValidate.FilterParam(User.Identity.Name);
                if (edit)
                {
                    db.Entry <User_Extend>(extend).State = EntityState.Modified;
                }
                else
                {
                    db.User_Extend.Add(extend);
                }
                edit = true;
                if (model.roleId != null)
                {
                    User_vs_Role uvr = db.User_vs_Role.Find(info.user_id);
                    if (uvr == null)
                    {
                        edit = false;
                        uvr  = new User_vs_Role();
                    }
                    uvr.uvr_user_id = info.user_id;
                    uvr.uvr_role_id = (int)model.roleId;
                    if (edit)
                    {
                        db.Entry <User_vs_Role>(uvr).State = EntityState.Modified;
                    }
                    else
                    {
                        db.User_vs_Role.Add(uvr);
                    }
                }
                try
                {
                    db.SaveChanges();
                    ViewBag.msg = " 更新成功。";
                    SysLog.WriteLog(user, string.Format("修改用户[{0}]信息", model.realName), IpHelper.GetIP(), info.user_id.ToString(), 2, "", db);
                }
                catch (DbEntityValidationException ex)
                {
                    StringBuilder errors = new StringBuilder();
                    IEnumerable <DbEntityValidationResult> validationResult = ex.EntityValidationErrors;
                    foreach (DbEntityValidationResult result in validationResult)
                    {
                        ICollection <DbValidationError> validationError = result.ValidationErrors;
                        foreach (DbValidationError err in validationError)
                        {
                            errors.Append(err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                        }
                    }
                    ErrorUnit.WriteErrorLog(errors.ToString(), this.GetType().Name);
                    ViewBag.msg = " 更新失败。";
                }
            }
next:
            return(View(model));
        }
        public ActionResult Create([Bind(Include = "name,realName,certificateType,certificateNo,mobile,email,password,password2,state,gender,postId,officePhone,picture,deptId,deptChild,roleId")] UserEditModel model)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToRoute(new { controller = "Login", action = "LogOut" }));
            }
            int user = PageValidate.FilterParam(User.Identity.Name);

            if (!RoleCheck.CheckHasAuthority(user, db, "用户管理"))
            {
                return(RedirectToRoute(new { controller = "Error", action = "Index", err = "没有权限。" }));
            }
            setSelect();
            if (ModelState.IsValid)
            {
                User_Info info = new User_Info();
                model.toUserInfoDB(info);
                if (db.User_Info.Where(x => x.user_name == info.user_name).Count() > 0)
                {
                    ViewBag.msg = "该用户名已注册。";
                    goto next;
                }
                var salt = Guid.NewGuid().ToString("N").Substring(0, 10).ToUpper();
                info.user_password = PasswordUnit.getPassword(model.password.ToUpper(), salt);
                info.user_salt     = salt;
                info.ToEncrypt();
                if (db.User_Info.Where(x => x.user_certificate_type == info.user_certificate_type && x.user_certificate_no == info.user_certificate_no).Count() > 0)
                {
                    ViewBag.msg = "该证件号已注册。";
                    goto next;
                }
                if (db.User_Info.Where(x => x.user_email == info.user_email).Count() > 0)
                {
                    ViewBag.msg = "该邮箱已注册。";
                    goto next;
                }
                if (db.User_Info.Where(x => x.user_mobile == info.user_mobile).Count() > 0)
                {
                    ViewBag.msg = "该手机号已注册。";
                    goto next;
                }
                if (model.password != model.password2)
                {
                    ViewBag.msg = "两次输入密码不一致,请重新输入。";
                    goto next;
                }

                db.User_Info.Add(info);
                try
                {
                    db.SaveChanges();
                }catch (Exception ex)
                {
                    ViewBag.msg = "信息录入失败,请重新录入。";
                    ErrorUnit.WriteErrorLog(ex.ToString(), this.GetType().Name);
                    goto next;
                }

                User_Extend extend = new User_Extend();
                model.toUserExtendDB(extend);
                extend.user_id       = info.user_id;
                extend.user_add_user = PageValidate.FilterParam(User.Identity.Name);
                extend.user_add_time = DateTime.Now;
                db.User_Extend.Add(extend);
                string photoDir = ConfigurationManager.AppSettings["photoPath"];
                if (!Directory.Exists(photoDir))
                {
                    Directory.CreateDirectory(photoDir);
                }
                string photoTempDir   = ConfigurationManager.AppSettings["tempPhotoPath"];
                string file_name      = string.Format("{0}{1}", photoDir, extend.user_picture).Replace("_temp", "");
                string temp_file_name = string.Format("{0}{1}", photoTempDir, extend.user_picture);
                if (System.IO.File.Exists(temp_file_name))
                {
                    FileInfo fi = new FileInfo(temp_file_name);
                    fi.CopyTo(file_name, true);
                }
                else
                {
                    ViewBag.msg = "图片保存失败。";
                }
                if (model.roleId != null)
                {
                    User_vs_Role uvr = new User_vs_Role();
                    uvr.uvr_user_id = info.user_id;
                    uvr.uvr_role_id = (int)model.roleId;
                    db.User_vs_Role.Add(uvr);
                }
                db.SaveChanges();
                SysLog.WriteLog(user, string.Format("添加用户[{0}]", model.realName), IpHelper.GetIP(), info.user_id.ToString(), 2, "", db);
                ViewBag.msg = " 用户创建成功。";
            }
            else
            {
                StringBuilder sbmsg = new StringBuilder();
                foreach (var value in ModelState.Values)
                {
                    if (value.Errors.Count() > 0)
                    {
                        foreach (var err in value.Errors)
                        {
                            sbmsg.Append(err.ErrorMessage);
                        }
                        ViewBag.msg = sbmsg.ToString();;
                    }
                }
            }
next:

            return(View(model));
        }
        public async Task UpdateAsync([FromBody] UserEditModel model)
        {
            if (string.IsNullOrEmpty(model.Id))
            {
                throw new ArgumentNullException(nameof(model.Id), "Id must be required.");
            }

            var entity = await _userManager.FindByIdAsync(model.Id);

            if (entity == null)
            {
                throw new Exception("User not found.");
            }

            entity = _userFactory.ToEntity(model, entity);

            var result = await _userManager.UpdateAsync(entity);

            if (!result.Succeeded)
            {
                throw new Exception(result.Errors.First().Description);
            }

            if (!string.IsNullOrEmpty(model.Password))
            {
                result = await _userManager.FocusResetPassowrdAsync(entity, model.Password);

                if (!result.Succeeded)
                {
                    throw new Exception(result.Errors.First().Description);
                }
            }

            var userExistsRoleNames = await _userManager.GetRolesAsync(entity);

            if (model.RoleIds?.Any() == true)
            {
                var newRoles = new List <Role>();
                foreach (var item in model.RoleIds)
                {
                    var role = await _roleManager.FindByIdAsync(item);

                    if (role != null)
                    {
                        newRoles.Add(role);

                        //if (!(await _userManager.IsInRoleAsync(entity, role.Name)))
                        //{
                        //	await _userManager.AddToRoleAsync(entity, role.Name);
                        //}
                    }
                }

                var needRemove = userExistsRoleNames.Except(newRoles.Select(t => t.Name));
                var needAdd    = newRoles.Select(t => t.Name).Except(userExistsRoleNames);

                if (needRemove.Any())
                {
                    await _userManager.RemoveFromRolesAsync(entity, needRemove);
                }

                if (needAdd.Any())
                {
                    await _userManager.AddToRolesAsync(entity, needAdd);
                }
            }
            else
            {
                if (userExistsRoleNames.Any())
                {
                    await _userManager.RemoveFromRolesAsync(entity, userExistsRoleNames);
                }
            }
        }
Beispiel #15
0
        public ActionResult Edit(UserEditModel userEditModel)
        {
            try
            {
                if (userEditModel.UsersRoles != null && userEditModel.UsersRoles.Count() > 0)
                {
                    if (!userEditModel.UsersRoles.Any(ur => ur.GetSystemRoleId == (long)Roles.MedicalVendorUser))
                    {
                        userEditModel.PhysicianProfile = null;
                    }
                }
                var userValidator = IoC.Resolve <UserEditModelValidator>();
                var result        = userValidator.Validate(userEditModel);
                if (result.IsValid)//ModelState.IsValid
                {
                    if (!string.IsNullOrEmpty(userEditModel.Password) && _passwordChangelogService.IsPasswordRepeated(userEditModel.Id, userEditModel.Password))
                    {
                        SetTestsAndPodsForPhysicianProfile(userEditModel);
                        var nonRepeatCount = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.PreviousPasswordNonRepetitionCount);
                        userEditModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("New password can not be same as last " + nonRepeatCount + " password(s). Please enter a different password.");
                        return(View(userEditModel));
                    }

                    if (!string.IsNullOrEmpty(userEditModel.TechnicianProfile.Pin) && _pinChangelogService.IsPinRepeated(userEditModel.TechnicianProfile.TechnicianId, userEditModel.TechnicianProfile.Pin.Encrypt()))
                    {
                        SetTestsAndPodsForPhysicianProfile(userEditModel);
                        var nonRepeatPinCount = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.PreviousPinNonRepetitionCount);
                        userEditModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("New Pin can not be same as last " + nonRepeatPinCount + " pin(s). Please enter a different Pin.");
                        return(View(userEditModel));
                    }

                    try
                    {
                        if (userEditModel.PhysicianProfile != null)
                        {
                            if (Request.Files.Count > 0)
                            {
                                var signatureFile = UploadFile(Request.Files[0], userEditModel.FullName.ToString());
                                if (signatureFile != null)
                                {
                                    signatureFile.Id = userEditModel.PhysicianProfile.SignatureFile.Id;
                                    userEditModel.PhysicianProfile.SignatureFile = signatureFile;
                                }
                                else if (userEditModel.PhysicianProfile.SignatureFile != null && userEditModel.PhysicianProfile.SignatureFile.Id > 0)
                                {
                                    userEditModel.PhysicianProfile.SignatureFile =
                                        _fileRepository.GetById(userEditModel.PhysicianProfile.SignatureFile.Id);
                                }
                                else
                                {
                                    userEditModel.PhysicianProfile.SignatureFile = null;
                                }
                            }
                        }

                        var currentRoles = _organizationRoleUserRepository.GetOrganizationRoleUserCollectionforaUser(userEditModel.Id).Where(x => x.RoleId == (long)Roles.CallCenterRep || x.RoleId == (long)Roles.Technician ||
                                                                                                                                             x.RoleId == (long)Roles.NursePractitioner || x.RoleId == (long)Roles.Coder || x.RoleId == (long)Roles.MedicalVendorUser).Select(x => x.RoleId);
                        var newRoles = userEditModel.UsersRoles.Where(x => x.RoleId == (long)Roles.CallCenterRep || x.RoleId == (long)Roles.Technician ||
                                                                      x.RoleId == (long)Roles.NursePractitioner || x.RoleId == (long)Roles.Coder || x.RoleId == (long)Roles.MedicalVendorUser).Select(x => x.RoleId);

                        List <string> removedRoleAlias = new List <string>();
                        var           removedRoles     = currentRoles.Select(x => x).Except(newRoles).ToList();
                        removedRoleAlias = _roleRepository.GetByRoleIds(removedRoles).Select(x => x.Alias).ToList();


                        userEditModel = _userService.Save(userEditModel);

                        ExportToMedicare(userEditModel, removedRoleAlias);

                        userEditModel.Password        = null;
                        userEditModel.ConfirmPassword = null;


                        if (userEditModel.PhysicianProfile != null && userEditModel.PhysicianProfile.SignatureFile != null)
                        {
                            var signatureMediaFileLocation = _mediaRepository.GetPhysicianSignatureMediaFileLocation();
                            userEditModel.PhysicianProfile.SignatureFile.Path = signatureMediaFileLocation.Url +
                                                                                userEditModel.PhysicianProfile.SignatureFile.Path;
                        }

                        SetTestsAndPodsForPhysicianProfile(userEditModel);
                        userEditModel.FeedbackMessage = FeedbackMessageModel.CreateSuccessMessage(string.Format("The user {0} was saved successfully.", userEditModel.FullName));
                        return(View(userEditModel));
                    }

                    catch (InvalidAddressException)
                    {
                        SetTestsAndPodsForPhysicianProfile(userEditModel);
                        userEditModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("Unable to save this address. Please check the city, state and zip are valid.");
                        return(View(userEditModel));
                    }

                    catch (Exception exception)
                    {
                        SetTestsAndPodsForPhysicianProfile(userEditModel);
                        userEditModel.FeedbackMessage =
                            FeedbackMessageModel.CreateFailureMessage("System Error:" + exception.Message);
                        return(View(userEditModel));
                    }
                }
                SetTestsAndPodsForPhysicianProfile(userEditModel);
                return(View(userEditModel));
            }
            catch
            {
                SetTestsAndPodsForPhysicianProfile(userEditModel);
                return(View(userEditModel));
            }
        }
Beispiel #16
0
        public ActionResult Create(UserEditModel userEditModel)
        {
            if (userEditModel.UsersRoles != null && userEditModel.UsersRoles.Count() > 0)
            {
                if (!userEditModel.UsersRoles.Any(ur => ur.GetSystemRoleId == (long)Roles.MedicalVendorUser))
                {
                    userEditModel.PhysicianProfile = null;
                }
            }
            var userValidator = IoC.Resolve <UserEditModelValidator>();
            var result        = userValidator.Validate(userEditModel);

            if (result.IsValid)//ModelState.IsValid
            {
                try
                {
                    if (userEditModel.PhysicianProfile != null)
                    {
                        if (Request.Files.Count > 0)
                        {
                            var signatureFile = UploadFile(Request.Files[0], userEditModel.FullName.ToString());
                            userEditModel.PhysicianProfile.SignatureFile = signatureFile;
                        }
                    }

                    userEditModel = _userService.Save(userEditModel);

                    ExportToMedicare(userEditModel, new List <string>());

                    SendNotificationMail(userEditModel);

                    ModelState.Clear();
                    return(RedirectToAction("Create", "User", new { message = string.Format("The user {0} was saved successfully. You can add more users from here.", userEditModel.FullName) }));
                    //var newModel = new UserEditModel();
                    //SetTestsAndPodsForPhysicianProfile(newModel);

                    //newModel.FeedbackMessage =
                    //    FeedbackMessageModel.CreateSuccessMessage(
                    //        string.Format("The user {0} was saved successfully. You can add more users from here.",
                    //                      userEditModel.FullName));
                    //return View(newModel);
                }

                catch (InvalidAddressException)
                {
                    SetTestsAndPodsForPhysicianProfile(userEditModel);
                    userEditModel.FeedbackMessage =
                        FeedbackMessageModel.CreateFailureMessage(
                            "Unable to save this address. Please check the city, state and zip are valid.");
                    return(View(userEditModel));
                }

                catch (Exception exception)
                {
                    SetTestsAndPodsForPhysicianProfile(userEditModel);
                    userEditModel.FeedbackMessage =
                        FeedbackMessageModel.CreateFailureMessage("System Error:" + exception.Message);
                    return(View(userEditModel));
                }
            }
            SetTestsAndPodsForPhysicianProfile(userEditModel);
            return(View(userEditModel));
        }
Beispiel #17
0
 public UserEditModel Add()
 {
     return(UserEditModel.Create(_db));
 }
        public ActionResult Edit(UserEditModel model)
        {
            if (!this.ModelState.IsValid)
            {
                this.ViewBag.Error = ModelValidationErrors.InvalidModel;
                return this.View(model);
            }

            var user = this.users.GetById(model.Id);
            if (user == null)
            {
                this.TempData["Error"] = ModelValidationErrors.EditDeletedEntity;
                return this.RedirectToAction("Index");
            }

            user.FirstName = model.FirstName;
            user.LastName = model.LastName;
            user.PhoneNumber = model.PhoneNumber;
            this.users.Update();

            this.TempData["Success"] = "User was successful edited!";
            return this.RedirectToAction("Index");
        }
Beispiel #19
0
 public IActionResult Edit(Guid id)
 {
     return(View(UserEditModel.GetById(_db, id)));
 }
Beispiel #20
0
        public ActionResult EditProfile(UserEditModel userEditModel)
        {
            string message      = "";
            bool   Status       = false;
            bool   EmailChanged = false;

            using (DBEntities de = new DBEntities())
            {
                var user = de.Users.Where(a => a.EmailID == HttpContext.User.Identity.Name).FirstOrDefault();
                if (user != null)
                {
                    if (userEditModel.FirstName != null)
                    {
                        if (!userEditModel.FirstName.Any(x => Char.IsWhiteSpace(x)))
                        {
                            user.FirstName = userEditModel.FirstName;
                            Status         = true;
                        }
                    }

                    if (userEditModel.LastName != null)
                    {
                        if (!userEditModel.LastName.Any(x => Char.IsWhiteSpace(x)))
                        {
                            user.LastName = userEditModel.LastName;
                            Status        = true;
                        }
                    }

                    if (userEditModel.EmailID != null)
                    {
                        if (!userEditModel.EmailID.Any(x => Char.IsWhiteSpace(x)))
                        {
                            if (IsEmail(userEditModel.EmailID))
                            {
                                FormsAuthentication.SignOut();
                                user.EmailID = userEditModel.EmailID;
                                Status       = true;
                                EmailChanged = true;
                                de.Configuration.ValidateOnSaveEnabled = false;
                                de.SaveChanges();
                                return(RedirectToAction("Index", "Home"));
                            }
                        }
                    }

                    if (userEditModel.Address != null)
                    {
                        user.Address = userEditModel.Address;
                        Status       = true;
                    }

                    if (EmailChanged == false)
                    {
                        de.Configuration.ValidateOnSaveEnabled = false;
                        de.SaveChanges();
                    }

                    if (Status == true)
                    {
                        message = "Profile updated successfully!";
                    }
                    else
                    {
                        message = "Please input at least one value!";
                    }
                }
            }

            ViewBag.Message = message;
            return(View(userEditModel));
        }
        public void Delete(UserEditModel entity)
        {
            var service = DependencyInjection.Container.Resolve <IUserService>();

            service.Delete(entity.Target);
        }
 private async Task PopulateEditUserPageAsync(UserEditModel model)
 {
     model.Roles = await _roleService.GetReferencesAsync();
 }
        public ActionResult Edit(string id)
        {
            if (!id.Equals(User.Id(), StringComparison.OrdinalIgnoreCase) && !User.IsInRole(Definitions.Roles.Administrator))
            {
                return RedirectToAction("Unauthorized", "Home");
            }

            if (MembershipService.IsReadOnly())
            {
                return RedirectToAction("Detail", "Account", new { id = id });
            }

            if (!String.IsNullOrEmpty(id))
            {
                var user = MembershipService.GetUser(id);
                if (user != null)
                {
                    var model = new UserEditModel
                    {
                        Username = user.Name,
                        Name = user.GivenName,
                        Surname = user.Surname,
                        Email = user.Email,
                        Roles = RoleProvider.GetRolesForUser(user.Name),
                    };
                    PopulateRoles();
                    return View(model);
                }
            }
            return View();
        }
Beispiel #24
0
 public IActionResult Add()
 {
     return(View("Edit", UserEditModel.Create(_db)));
 }
Beispiel #25
0
        public async Task <IActionResult> Update(UserEditModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (model.Roles.Contains("Customer") && model.Roles.Count() > 1) // if user is customer and also some roles, invalid
                    {
                        ModelState.AddModelError("", "Not allowed to assign other roles to customer");
                    }
                    else
                    {
                        AppUser user = await userManager.FindByNameAsync(model.UserName);

                        if (user == null)
                        {
                            return(NotFound());
                        }
                        // if existed
                        IEnumerable <string> roles = await userManager.GetRolesAsync(user);

                        bool notChanged = model.Roles.OrderBy(r => r).SequenceEqual(roles.OrderBy(r => r));    // compare to determine if role has changed
                        if (!notChanged)                                                                       // if role is change
                        {
                            if (model.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase)) // if current user try to remove role admin from his/her account or lock his/her account
                            {
                                if (!model.Roles.Contains("Admin"))
                                {
                                    ModelState.AddModelError("", "You are not allowed to remove 'Admin' role from your account");
                                }
                                if (!model.IsLocked)
                                {
                                    ModelState.AddModelError("", "You are not allowed to lock your account");
                                }
                            }
                            else if (roles.Contains("Customer") && !model.Roles.Contains("Customer")) //if user is a customer and updating remove customer role from user
                            {
                                ModelState.AddModelError("", "Customer is not allowed to change role");
                            }

                            if (roles.Contains("Guide"))            //if user is a guide
                            {
                                if (!model.Roles.Contains("Guide")) // if updating remove guide role from user
                                {
                                    IEnumerable <string> tours = await tourDAL.FindToursByUserIdAsync(user.Id);

                                    if (tours != null) // if guide is used in any tours then it can't be remove
                                    {
                                        ModelState.AddModelError("", $"Can't remove 'Guide' role. This guide is used in tours: {string.Join(", ", tours)}");
                                    }
                                }
                                if (model.IsLocked) // if want to lock this guide
                                {
                                    IEnumerable <string> tours = await tourDAL.FindFutureToursByUserIdAsync(user.Id);

                                    if (tours != null)
                                    {
                                        ModelState.AddModelError("", $"Can't lock this user. Remove this guide from the following tours before lock: {string.Join(", ", tours)}");
                                    }
                                }
                            }
                            if (!ModelState.IsValid)
                            {
                                model.RoleItems = new List <SelectListItem>();
                                foreach (IdentityRole role in roleManager.Roles)
                                {
                                    model.RoleItems.Add(new SelectListItem(role.Name, role.Name));
                                }
                                return(View("Edit", model));
                            }
                        }
                        bool isSameEmail = user.Email.Equals(model.Email, StringComparison.OrdinalIgnoreCase);
                        user.FirstName   = model.FirstName;
                        user.LastName    = model.LastName;
                        user.Address     = model.Address;
                        user.Email       = model.Email;
                        user.BirthDate   = model.BirthDate;
                        user.Gender      = model.Gender;
                        user.PhoneNumber = model.Tel;
                        bool changedStatus = false;
                        if (model.IsLocked)
                        {
                            if (user.LockoutEnd == null)
                            {
                                changedStatus = true;
                            }
                            user.LockoutEnd = DateTimeOffset.MaxValue;
                        }
                        else
                        {
                            if (user.LockoutEnd != null)
                            {
                                changedStatus = true;
                            }
                            user.LockoutEnd = null;
                        }
                        string avatar;
                        if (model.Photo != null && !string.IsNullOrWhiteSpace(model.Photo.FileName)) // if photo is change then copy
                        {
                            string filePath = user.UserName + "." + model.Photo.FileName.Substring(model.Photo.FileName.LastIndexOf(".") + 1);
                            avatar = await blobService.UploadFile("avatars", filePath, model.Photo);
                        }
                        else // if not, preserve old one
                        {
                            avatar = user.Avatar;
                        }
                        if (avatar != null)
                        {
                            user.Avatar = avatar;
                            IdentityResult result = null;
                            if (isSameEmail)
                            {
                                IEnumerable <UserLoginInfo> loginInfos = await userManager.GetLoginsAsync(user);

                                foreach (UserLoginInfo info in loginInfos)
                                {
                                    result = await userManager.RemoveLoginAsync(user, info.LoginProvider, info.ProviderKey);
                                }
                            }
                            if (result == null || result.Succeeded) // if don't need to remove external login or remove external login successfully
                            {
                                result = await userManager.UpdateAsync(user);

                                if (result.Succeeded)
                                {
                                    if (changedStatus || !notChanged)
                                    {
                                        if (!notChanged)
                                        {
                                            result = await userManager.AddToRolesAsync(user, model.Roles.Except(roles));

                                            if (!result.Succeeded)
                                            {
                                                AddErrorFromResult(result);
                                            }
                                            result = await userManager.RemoveFromRolesAsync(user, roles.Except(model.Roles));

                                            if (!result.Succeeded)
                                            {
                                                AddErrorFromResult(result);
                                            }
                                        }
                                        await userManager.UpdateSecurityStampAsync(user);
                                    }
                                    if (ModelState.IsValid) // if everything is ok
                                    {
                                        return(RedirectToAction(nameof(Details), new { userName = model.UserName }));
                                    }
                                }
                                else // if update failed
                                {
                                    AddErrorFromResult(result);
                                }
                            }
                            else // if remove external login failed
                            {
                                AddErrorFromResult(result);
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Can't upload avatar");
                        }
                    }
                }
                model.RoleItems = new List <SelectListItem>();
                foreach (IdentityRole role in roleManager.Roles)
                {
                    model.RoleItems.Add(new SelectListItem(role.Name, role.Name));
                }
                return(View("Edit", model));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                throw;
            }
        }
Beispiel #26
0
        public JsonResult Edit(UserEditModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            var mongo = new MongoHelper();

            // 判断用户名是否重复
            var filter1 = Builders <BsonDocument> .Filter.Ne("ID", objectId);

            var filter2 = Builders <BsonDocument> .Filter.Eq("Username", model.Username);

            var filter = Builders <BsonDocument> .Filter.And(filter1, filter2);

            var count = mongo.Count(Constant.UserCollectionName, filter);

            if (count > 0)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username is already existed.",
                }));
            }

            filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var update1 = Builders <BsonDocument> .Update.Set("Username", model.Username);

            var update2 = Builders <BsonDocument> .Update.Set("Name", model.Name);

            var update3 = Builders <BsonDocument> .Update.Set("UpdateTime", DateTime.Now);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2, update3);

            mongo.UpdateOne(Constant.UserCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
        public ActionResult Edit(string id)
        {
            var userId = User.Identity.GetUserId();

            return(View(UserEditModel.UserEdit(id, UserRolesModel.IsAdmin(userId))));
        }
        public ActionResult EditProfile(UserEditModel userEditModel)
        {
            string message      = "";
            bool   Status       = false;
            bool   EmailChanged = false;

            using (DatabaseEntities de = new DatabaseEntities())
            {
                var user = de.Users.Where(a => a.EmailID == HttpContext.User.Identity.Name).FirstOrDefault();
                if (user != null)
                {
                    if (userEditModel.FirstName != null)
                    {
                        if (!userEditModel.FirstName.Any(x => Char.IsWhiteSpace(x)))
                        {
                            user.FirstName = userEditModel.FirstName;
                            Status         = true;
                        }
                    }

                    if (userEditModel.LastName != null)
                    {
                        if (!userEditModel.LastName.Any(x => Char.IsWhiteSpace(x)))
                        {
                            user.LastName = userEditModel.LastName;
                            Status        = true;
                        }
                    }

                    if (userEditModel.EmailID != null)
                    {
                        if (!userEditModel.EmailID.Any(x => Char.IsWhiteSpace(x)))
                        {
                            if (IsEmail(userEditModel.EmailID))
                            {
                                var videos = de.Videos.Where(a => a.VideoAuthor == user.EmailID);
                                FormsAuthentication.SignOut();
                                foreach (var video in videos)
                                {
                                    video.VideoAuthor = userEditModel.EmailID;
                                }
                                user.EmailID = userEditModel.EmailID;
                                Status       = true;
                                EmailChanged = true;
                                de.Configuration.ValidateOnSaveEnabled = false;
                                de.SaveChanges();
                                return(RedirectToAction("DisplayAllVideos", "Video"));
                            }
                        }
                    }

                    if (userEditModel.DateOfBirth != null)
                    {
                        user.DateOfBirth = userEditModel.DateOfBirth;
                        Status           = true;
                    }

                    if (EmailChanged == false)
                    {
                        de.Configuration.ValidateOnSaveEnabled = false;
                        de.SaveChanges();
                    }

                    if (Status == true)
                    {
                        message = "Profile updated successfully!";
                    }
                    else
                    {
                        message = "Please input at least one value!";
                    }
                }
            }

            ViewBag.Message = message;
            return(View(userEditModel));
        }
Beispiel #29
0
        public static OperationResult EditUser(UserEditModel model, int EditUserID)
        {
            List <SqlParameter> paras = new List <SqlParameter>()
            {
                new SqlParameter("@ID", SqlDbType.Int),
                new SqlParameter("@RoleID", SqlDbType.Int),
                new SqlParameter("@NickName", SqlDbType.NVarChar, 20),
                new SqlParameter("@StrucID", SqlDbType.Int),
                new SqlParameter("@ContactNumber1", SqlDbType.NVarChar, 50),
                new SqlParameter("@ContactNumber2", SqlDbType.NVarChar, 50),
                new SqlParameter("@ContactAddress", SqlDbType.NVarChar, 50),
                new SqlParameter("@Remark", SqlDbType.NVarChar, 50),
                new SqlParameter("@EditUserID", SqlDbType.Int),
                new SqlParameter("@VehicleViewMode", SqlDbType.Bit),
            };

            paras[0].Value = model.ID;
            paras[1].Value = model.RoleID;
            paras[2].Value = model.NickName.Trim();
            paras[3].Value = model.StrucID;

            #region 可NULL

            if (string.IsNullOrWhiteSpace(model.ContactNumber1))
            {
                paras[4].Value = DBNull.Value;
            }
            else
            {
                paras[4].Value = model.ContactNumber1.Trim();
            }

            if (string.IsNullOrWhiteSpace(model.ContactNumber2))
            {
                paras[5].Value = DBNull.Value;
            }
            else
            {
                paras[5].Value = model.ContactNumber2.Trim();
            }

            if (string.IsNullOrWhiteSpace(model.ContactAddress))
            {
                paras[6].Value = DBNull.Value;
            }
            else
            {
                paras[6].Value = model.ContactAddress.Trim();
            }

            if (string.IsNullOrWhiteSpace(model.Remark))
            {
                paras[7].Value = DBNull.Value;
            }
            else
            {
                paras[7].Value = model.Remark;
            }
            paras[8].Value = EditUserID;
            paras[9].Value = model.VehicleViewMode;
            #endregion


            #region  SQL
            string sql = @"UPDATE  dbo.Users SET     NickName = @NickName ,
        RoleID = @RoleID ,
        StrucID = @StrucID ,
        Remark = @Remark,
        ContactAddress = @ContactAddress ,
        ContactNumber1 = @ContactNumber1 ,
        ContactNumber2 = @ContactNumber2 ,
        EditDateTime = GETDATE(),
        EditUserID=@EditUserID,
        VehicleViewMode =@VehicleViewMode
WHERE   ID = @ID";
            #endregion

            int    result = MSSQLHelper.ExecuteNonQuery(CommandType.Text, sql, paras.ToArray());
            string msg    = string.Empty;
            switch (result)
            {
            case 1:
                msg = PromptInformation.OperationSuccess;
                break;

            case 0:
                msg = PromptInformation.NotExists;
                break;

            case -1:
                msg = PromptInformation.DBError;
                break;
            }
            return(new OperationResult()
            {
                Success = result > 0,
                Message = msg
            });
        }
Beispiel #30
0
        public ActionResult Edit(UserEditModel model)
        {
            if (ModelState.IsValid)
            {
                SiteUser user = Repository.Find(model.SiteUserId);
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.UpdatedBy = model.SiteUserId;
                user.UpdatedOn = DateTime.Now;
                Repository.Update(user);
                return RedirectToAction("Details", new { id = model.SiteUserId });
            }

            return View(model);
        }
Beispiel #31
0
        public UserEditModel Save(UserEditModel userToSave)
        {
            _userModelValidator.ValidateAndThrow(userToSave);

            var userAddress = _addressService.SaveAfterSanitizing(Mapper.Map <AddressEditModel, Address>(userToSave.Address));
            OrganizationRoleUser organizationRoleUser = Mapper.Map <OrganizationRoleUserModel, OrganizationRoleUser>(_sessionContext.UserSession.CurrentOrganizationRole);

            userToSave.DataRecorderMetaData = new DataRecorderMetaData(organizationRoleUser, DateTime.Now, DateTime.Now);

            var        user = Mapper.Map <UserEditModel, User>(userToSave);
            var        isPasswordUpdatedOrCreated = false;
            SecureHash secureHash = null;

            if (userToSave.Id > 0 && string.IsNullOrEmpty(userToSave.Password))
            {
                var existingUser = _userRepository.GetUser(userToSave.Id);
                user.UserLogin.Password               = existingUser.UserLogin.Password;
                user.UserLogin.Salt                   = existingUser.UserLogin.Salt;
                user.UserLogin.UserVerified           = existingUser.UserLogin.UserVerified;//For a scenario: User is created and then immediatly updated
                user.UserLogin.LastPasswordChangeDate = existingUser.UserLogin.LastPasswordChangeDate;
                user.UserLogin.LastLogged             = existingUser.UserLogin.LastLogged;
            }
            else if (!string.IsNullOrEmpty(userToSave.Password))
            {
                secureHash = _oneWayHashingService.CreateHash(userToSave.Password);
                user.UserLogin.Password               = secureHash.HashedText;
                user.UserLogin.Salt                   = secureHash.Salt;
                isPasswordUpdatedOrCreated            = true;
                user.UserLogin.LastPasswordChangeDate = DateTime.Now;
            }

            user.Address = userAddress;
            if (isPasswordUpdatedOrCreated)//&& user.Id > 0 && userToSave.UsersRoles.Count() == 1 && userToSave.UsersRoles.Single().RoleId == (long)Roles.Customer)
            {
                user.UserLogin.UserVerified = false;
            }

            user.UserLogin.IsTwoFactorAuthrequired = userToSave.OverRideTwoFactorAuthrequired ? userToSave.IsTwoFactorAuthrequired : (bool?)null;


            user = _userRepository.SaveUser(user);
            if (isPasswordUpdatedOrCreated && secureHash != null && !(user.Id > 0 && userToSave.UsersRoles.Count() == 1 && userToSave.UsersRoles.Single().RoleId == (long)Roles.Customer))
            {
                _passwordChangelogService.Update(user.Id, secureHash, _sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId);
            }

            userToSave.Id = user.Id;
            //map & save user roles
            _orgRoleUserRepository.DeactivateAllOrganizationRolesForUser(user.Id);
            foreach (var organizationRoleModel in userToSave.UsersRoles)
            {
                organizationRoleModel.UserId = user.Id;
                var orgRoleUser = _orgRoleUserRepository.SaveOrganizationRoleUser(Mapper.Map <OrganizationRoleUserModel, OrganizationRoleUser>(organizationRoleModel));
                var roleId      = GetParentRoleIdByRoleId(orgRoleUser.RoleId);
                switch (roleId)
                {
                case (long)Roles.Technician:
                    var technician = Mapper.Map <TechnicianModel, Technician>(userToSave.TechnicianProfile);
                    technician.TechnicianId = orgRoleUser.Id;
                    var repository = ((IRepository <Technician>)_technicianRepository);
                    repository.Save(technician);
                    if (!string.IsNullOrWhiteSpace(userToSave.TechnicianProfile.Pin))
                    {
                        _pinChangeLogService.Update(userToSave.TechnicianProfile.Pin.Encrypt(), orgRoleUser.Id, organizationRoleUser.Id);
                    }
                    break;

                case (long)Roles.MedicalVendorUser:
                    var physician = Mapper.Map <PhysicianModel, Physician>(userToSave.PhysicianProfile);
                    physician.PhysicianId             = orgRoleUser.Id;
                    physician.AuthorizedStateLicenses =
                        _physicianLicenseModelFactory.CreateMultiple(userToSave.PhysicianProfile.Licenses,
                                                                     orgRoleUser.Id);
                    _physicianRepository.SavePhysician(physician);
                    break;

                case (long)Roles.CorporateAccountCoordinator:
                    var accountCoordinator = Mapper.Map <AccountCoordinatorProfileModel, AccountCoordinatorProfile>(userToSave.AccountCoordinatorProfile);
                    accountCoordinator.AccountCoordinatorId = orgRoleUser.Id;
                    var accountCoordinatorRepository = ((IRepository <AccountCoordinatorProfile>)_accountCoordinatorProfileRepository);
                    accountCoordinatorRepository.Save(accountCoordinator);
                    break;

                case (long)Roles.CallCenterRep:
                    var callCenterRepProfile = new CallCenterRepProfile
                    {
                        CallCenterRepId = orgRoleUser.Id,
                        CanRefund       = false,
                        CanChangeNotes  = false,
                        DialerUrl       = organizationRoleModel.DialerUrl
                    };
                    _callCenterRepProfileRepository.Save(callCenterRepProfile);
                    break;
                }
            }

            if (userToSave.UsersRoles.Any(x => x.RoleId == (long)Roles.NursePractitioner))
            {
                var userNpiInfo = new UserNpiInfo
                {
                    UserId     = userToSave.Id,
                    Npi        = !string.IsNullOrEmpty(userToSave.Npi) ? userToSave.Npi : null,
                    Credential = !string.IsNullOrEmpty(userToSave.Credential) ? userToSave.Credential : null
                };
                _userNpiInfoRepository.Save(userNpiInfo);
            }

            var systemUserInfo = new SystemUserInfo
            {
                EmployeeId = userToSave.UsersRoles.Count() == 1 && userToSave.UsersRoles.Any(x => x.RoleId == (long)Roles.Customer) ? string.Empty : userToSave.EmployeeId,
                UserId     = userToSave.Id
            };

            _systemUserInfoRepository.Save(systemUserInfo);

            return(userToSave); //this does not return the same object. the saved user are out of sync at this point.!!
        }
Beispiel #32
0
 public UserEditModel Get(Guid id)
 {
     return(UserEditModel.GetById(_db, id));
     //return View(UserEditModel.GetById(_db, id));
 }
Beispiel #33
0
 public async Task <IActionResult> Edit([FromBody] UserEditModel model)
 {
     return(await MakeActionCallAsync(async() => await _service.EditAsync(model, GetPersonId(), GetLanguage())));
 }
Beispiel #34
0
        public ActionResult RestorePassword(RestoreModel model)
        {
            var user = userBusinessLogic.User_GetByLogin(model.Login);

            if (user != null)
            {
                if (model.Choice == "email")
                {
                    if (!string.IsNullOrEmpty(user.Email))
                    {
                        UserEditModel userModel = new UserEditModel();
                        userModel          = new UserEditModel(user);
                        userModel.Password = UserEditModel.GeneratePassword();
                        try
                        {
                            userModel.SendEmail();
                            long userId = userBusinessLogic.User_Save(userModel.GetUserSaveData());
                            ViewBag.Message = "Письмо успешно отправлено на почту " + userModel.ReplaceEmail(user.Email);
                        }
                        catch (Exception e)
                        {
                            ViewBag.Message = e.Message;
                        }
                    }
                    else
                    {
                        ViewBag.Message = string.Format("У пользователя [{0}] не указан e-mail. Обратитесь к администратору.", model.Login);
                    }
                }

                if (model.Choice == "sms")
                {
                    if (!string.IsNullOrEmpty(user.Phone))
                    {
                        UserEditModel userModel = new UserEditModel();
                        userModel          = new UserEditModel(user);
                        userModel.Password = UserEditModel.GeneratePassword();
                        try
                        {
                            string result = userModel.SendSms();
                            if (string.IsNullOrEmpty(result))
                            {
                                long userId = userBusinessLogic.User_Save(userModel.GetUserSaveData());
                                ViewBag.Message = "СМС отправлено на телефон " + userModel.ReplacePhone(userModel.Phone);
                            }
                            else
                            {
                                ViewBag.Message = result;
                            }
                        }
                        catch (Exception e)
                        {
                            ViewBag.Message = e.Message;
                        }
                    }
                    else
                    {
                        ViewBag.Message = string.Format("У пользователя [{0}] не указан телефон. Обратитесь к администратору.", model.Login);
                    }
                }
            }
            else
            {
                ViewBag.Message = string.Format("Пользователь [{0}] не найден", model.Login);
            }

            return(View());
        }
        public virtual ActionResult EidtUser(long userId)
        {
            var model = new UserEditModel();

            return(View(model));
        }
Beispiel #36
0
        public async Task <IActionResult> Save([FromBody] UserEditModel model)
        {
            // Refresh roles in the model if validation fails
            //var temp = UserEditModel.Create(_db);
            //model.Roles = temp.Roles;

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

            try
            {
                var userId = model.User.Id;

                if (string.IsNullOrWhiteSpace(model.User.UserName))
                {
                    return(BadRequest(GetErrorMessage(_localizer.General["Username is mandatory."])));
                }

                if (string.IsNullOrWhiteSpace(model.User.Email))
                {
                    return(BadRequest(GetErrorMessage(_localizer.General["Email address is mandatory."])));
                }

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

                if (model.User.Id == Guid.Empty && string.IsNullOrWhiteSpace(model.Password))
                {
                    return(BadRequest(GetErrorMessage(_localizer.Security["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(GetErrorMessage(string.Join("<br />", errors))));
                        }
                    }
                }

                //check username
                if (await _db.Users.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."])));
                }

                var result = await model.Save(_userManager);

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

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

                return(BadRequest(GetErrorMessage(_localizer.Security["The user could not be saved."] + "<br/><br/>" + string.Join("<br />", errorMessages))));
            }
            catch (Exception ex)
            {
                return(BadRequest(GetErrorMessage(ex.Message)));
            }
        }
Beispiel #37
0
 public ActionResult Edit(UserEditModel model)
 {
     return(View(model));
 }