Example #1
0
        public async Task <ActionResult <User> > PutUser(int id, UserEdit model)
        {
            if (id != model.Id)
            {
                ModelState.AddModelError("User.Id", "Id != User.Id");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    var data = await _repository.GetAsync(id);

                    if (data != null)
                    {
                        data.Email = model.Email;
                        data.Name  = model.Name;
                        if (!string.IsNullOrEmpty(model.Password))
                        {
                            var pass = _crypt.Hash(model.Password);
                            data.Password     = pass.Hashed;
                            data.PasswordSalt = pass.Salt;
                        }
                        if (await _repository.EditAsync(data))
                        {
                            return(Ok(data));
                        }
                        else
                        {
                            return(StatusCode(304, data));
                        }
                    }
                    return(NotFound(new { Status = "Not Found", Id = id }));
                }
            }
            return(BadRequest(ModelState));
        }
        public ActionResult Update(int id, string username, string firstName, string lastName, string description, string email, string password)
        {
            if (Session["ID"] == null || (int)Session["ID"] != id)
            {
                return(View("Error"));
            }

            var user = new User();

            user.ID          = id;
            user.Username    = username;
            user.FirstName   = firstName;
            user.LastName    = lastName;
            user.Description = description;
            user.Email       = email;
            user.Password    = password;

            var client = new RestClient(ConfigurationManager.AppSettings.Get("APIURL"));

            var request = new RestRequest($"user/update", Method.POST);

            request.AddJsonBody(user);

            var content      = client.Execute(request).Content;
            var responseUser = JsonConvert.DeserializeObject <User>(content);

            if (responseUser.UsernameError != "" || responseUser.EmailError != "" || responseUser.PasswordError != "")
            {
                var model = new UserEdit();
                model.User = responseUser;

                return(View("Edit", model));
            }

            return(RedirectToAction($"Show/{id}"));
        }
        public ActionResult Edit(int?id)
        {
            // Make sure the user is logged in and that they have permission
            if (!IsUserLoggedIn)
            {
                return(RedirectToLogin());
            }
            if (!UserHasPermission(PermissionName.User))
            {
                return(RedirectToPermissionDenied());
            }

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            int userId = ( int )id;

            TCABS_DataLibrary.Models.UserModel userModel = UserProcessor.SelectUserForUserId(userId);

            UserEdit user = new UserEdit(userModel);

            return(View(user));
        }
        //Get
        public ActionResult EditUsers(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            //find the user in DB
            User users = db.Users.Find(id);

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

            //bind the DB user with view model
            UserEdit editUser = new UserEdit();

            editUser.Username   = users.Username;
            editUser.isAdmin    = users.isAdmin;
            editUser.isApproved = users.Approved;
            editUser.Id         = users.Id;

            return(View(editUser));
        }
Example #5
0
        public async Task <ActionResult> edit(UserEdit viewModel)
        {
            ViewBag.returnUrl = "/Account/Index";
            if (ModelState.IsValid)
            {
                ApplicationUser model = await UserManager.FindByIdAsync(viewModel.id);

                model.UserName    = viewModel.userName;
                model.trueName    = viewModel.trueName;
                model.Email       = viewModel.email;
                model.PhoneNumber = viewModel.phoneNumber;
                var result = await UserManager.UpdateAsync(model);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AddErrors(result);
                }
            }
            return(View(viewModel));
        }
Example #6
0
        public ActionResult Edit(int id, UserEdit model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (model.UserId != id)
            {
                ModelState.AddModelError("", "Id Doesn't Match");
                return(View(model));
            }

            var service = CreateUserService();

            if (service.UpdateUser(model))
            {
                TempData["SaveResult"] = "User info was updated.";
                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", "User info could not be updated.");
            return(View(model));
        }
Example #7
0
 public void EditAsAdmin(UserEdit userEdit)
 {
     if (userEdit.Id == 0)
     {
         Database.User.Add(new User()
         {
             EmailAddress = userEdit.EmailAddress, Name = userEdit.Name, Role = Database.Role.QueryToTable.FirstOrDefault(x => x.Name == userEdit.Role), Salt = userEdit.Salt
         });
         Database.Save();
     }
     else
     {
         var userDb = Database.User.QueryToTable.FirstOrDefault(x => x.id == userEdit.Id);
         userDb.Name         = userEdit.Name;
         userDb.EmailAddress = userEdit.EmailAddress;
         if (!string.IsNullOrEmpty(userEdit.Salt))
         {
             userDb.Salt = userEdit.Salt.GetHashCode().ToString();
         }
         userDb.Role = Database.Role.QueryToTable.FirstOrDefault(x => x.Name == userEdit.Role);
         Database.User.Update(userDb);
         Database.Save();
     }
 }
        public ActionResult Edit(int id = 0)
        {
            UserEdit user = null;

            if (webSecurity.CurrentUser.IsInRole("Administrator") && id > 0)
            {
                user = new UserEdit(Request <User> .GetAuthItemById(id, "A", "B"));
            }
            else
            {
                user = new UserEdit(Request <User> .GetAuthItemByName(User.Identity.Name, "A", "B"));
            }
            if (user == null)
            {
                return(HttpNotFound());
            }
            if (webSecurity.CurrentUser.IsInRole("Administrator"))
            {
                ViewBag.AllRoles  = roles.GetAllRoles().ToList();
                ViewBag.UserRoles = roles.GetRolesForUser(user.username).ToList();
            }

            return(View(user));
        }
        private void SetChangeModel(Account user, UserEdit model)
        {
            model.AllAccountGroup = DB.AccountGroup.Where(x => x.TypeGroup == user.TypeUser)
                                    .Select(x => new SelectListItem {
                Text = x.Name, Value = x.Id.ToString()
            })
                                    .ToList();

            // должности
            var allAppointment = new List <SelectListItem>();

            if (!user.AppointmentId.HasValue)
            {
                allAppointment.Add(new SelectListItem()
                {
                    Text = "", Value = "", Selected = true
                });
            }
            allAppointment.AddRange(DB.AccountAppointment.OrderBy(x => x.Name)
                                    .Select(x => new SelectListItem {
                Text = x.Name, Value = x.Id.ToString(), Selected = x.Id == user.AppointmentId
            })
                                    .ToList());
            model.AllAppointment = allAppointment;

            var regionIds = model.AccountRegionIds ?? new List <ulong>();

            var regions = DB.Regions()
                          .OrderBy(x => x.Name)
                          .Select(x => new SelectListItem {
                Value = x.Id.ToString(), Text = x.Name, Selected = regionIds.Contains(x.Id)
            })
                          .ToList();

            model.AllAccountRegion = regions;
        }
Example #10
0
        public ActionResult Edit(string id, UserEdit model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (model.Id != id)
            {
                ModelState.AddModelError("", "Id does not match User profile");
                return(View(model));
            }

            var service = CreateUserService();

            if (service.UpdateUser(model))
            {
                TempData["SaveResult"] = "Your profile was updated.";
                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", "Your profile could not be updated.");
            return(View(model));
        }
        public ActionResult Edit(UserEdit user)
        {
            var userModel = RepoUser.GetById(User.Identity.Name);

            if (ModelState.IsValid)
            {
                if (!user.Name.Trim().Equals(""))
                    userModel.Name = user.Name;

                if (!user.Email.Trim().Equals(""))
                    userModel.Email = user.Email;

               return new SeeOtherResult { Uri = Url.Action("Show", "Users") };
            }

            Response.StatusCode = HttpStatusCodes.BadRequest;
            user.Name = userModel.Name;
            user.Email = userModel.Email;
            user.UserView = new UserView {NickName = userModel.Id, CurrentRole = userModel.CurrentRole, ContainsImage = userModel.ContainsImage};
            return View(user);
        }
Example #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            UserEdit userEdit = new UserEdit();

            userEdit.Show();
        }
Example #13
0
        private void InfoCommandFunc()
        {
            UserEdit edit = new UserEdit();

            edit.ShowDialog();
        }
Example #14
0
 public override void Link()
 {
     VirtualRoot.BuildCmdPath <ShowDialogWindowCommand>(action: message => {
         UIThread.Execute(() => {
             DialogWindow.ShowDialog(new DialogWindowViewModel(message: message.Message, title: message.Title, onYes: message.OnYes, icon: message.Icon));
         });
     });
     VirtualRoot.BuildCmdPath <ShowQQGroupQrCodeCommand>(action: message => {
         UIThread.Execute(() => {
             QQGroupQrCode.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowCalcCommand>(action: message => {
         UIThread.Execute(() => {
             Calc.ShowWindow(message.CoinVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowLocalIpsCommand>(action: message => {
         UIThread.Execute(() => {
             LocalIpConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowEthNoDevFeeCommand>(action: message => {
         UIThread.Execute(() => {
             EthNoDevFeeEdit.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowCalcConfigCommand>(action: message => {
         UIThread.Execute(() => {
             CalcConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerClientsWindowCommand>(action: message => {
         UIThread.Execute(() => {
             MinerClientsWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowNTMinerUpdaterConfigCommand>(action: message => {
         UIThread.Execute(() => {
             NTMinerUpdaterConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowAboutPageCommand>(action: message => {
         UIThread.Execute(() => {
             AboutPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowKernelOutputPageCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputPage.ShowWindow(message.SelectedKernelOutputVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowKernelInputPageCommand>(action: message => {
         UIThread.Execute(() => {
             KernelInputPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowTagBrandCommand>(action: message => {
         if (NTMinerRoot.IsBrandSpecified)
         {
             return;
         }
         BrandTag.ShowWindow();
     });
     VirtualRoot.BuildCmdPath <ShowCoinPageCommand>(action: message => {
         UIThread.Execute(() => {
             CoinPage.ShowWindow(message.CurrentCoin, message.TabType);
         });
     });
     VirtualRoot.BuildCmdPath <ShowGroupPageCommand>(action: message => {
         UIThread.Execute(() => {
             GroupPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowSysDicPageCommand>(action: message => {
         UIThread.Execute(() => {
             SysDicPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowVirtualMemoryCommand>(action: message => {
         UIThread.Execute(() => {
             VirtualMemory.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowRestartWindowsCommand>(action: message => {
         UIThread.Execute(() => {
             RestartWindows.ShowDialog();
         });
     });
     VirtualRoot.BuildCmdPath <ShowNotificationSampleCommand>(action: message => {
         UIThread.Execute(() => {
             NotificationSample.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowPropertyCommand>(action: message => {
         UIThread.Execute(() => {
             Property.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowChartsWindowCommand>(action: message => {
         UIThread.Execute(() => {
             ChartsWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowOverClockDataPageCommand>(action: message => {
         UIThread.Execute(() => {
             OverClockDataPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowNTMinerWalletPageCommand>(action: message => {
         UIThread.Execute(() => {
             NTMinerWalletPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowMessagePathIdsCommand>(action: message => {
         UIThread.Execute(() => {
             MessagePathIds.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowUserPageCommand>(action: message => {
         UIThread.Execute(() => {
             UserPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowRemoteDesktopLoginDialogCommand>(action: message => {
         RemoteDesktopLogin.ShowWindow(message.Vm);
     });
     VirtualRoot.BuildCmdPath <ShowKernelsWindowCommand>(action: message => {
         UIThread.Execute(() => {
             KernelsWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowKernelDownloaderCommand>(action: message => {
         UIThread.Execute(() => {
             KernelDownloading.ShowWindow(message.KernelId, message.DownloadComplete);
         });
     });
     VirtualRoot.BuildCmdPath <EnvironmentVariableEditCommand>(action: message => {
         UIThread.Execute(() => {
             EnvironmentVariableEdit.ShowWindow(message.CoinKernelVm, message.EnvironmentVariable);
         });
     });
     VirtualRoot.BuildCmdPath <InputSegmentEditCommand>(action: message => {
         UIThread.Execute(() => {
             InputSegmentEdit.ShowWindow(message.CoinKernelVm, message.Segment);
         });
     });
     VirtualRoot.BuildCmdPath <CoinKernelEditCommand>(action: message => {
         UIThread.Execute(() => {
             CoinKernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <CoinEditCommand>(action: message => {
         UIThread.Execute(() => {
             CoinEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ColumnsShowEditCommand>(action: message => {
         UIThread.Execute(() => {
             ColumnsShowEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowContainerWindowCommand>(action: message => {
         UIThread.Execute(() => {
             ContainerWindow window = ContainerWindow.GetWindow(message.Vm);
             window?.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowSpeedChartsCommand>(action: message => {
         UIThread.Execute(() => {
             SpeedCharts.ShowWindow(message.GpuSpeedVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowFileWriterPageCommand>(action: message => {
         UIThread.Execute(() => {
             FileWriterPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <FileWriterEditCommand>(action: message => {
         UIThread.Execute(() => {
             FileWriterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowFragmentWriterPageCommand>(action: message => {
         UIThread.Execute(() => {
             FragmentWriterPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <FragmentWriterEditCommand>(action: message => {
         UIThread.Execute(() => {
             FragmentWriterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <GroupEditCommand>(action: message => {
         UIThread.Execute(() => {
             GroupEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelInputEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelInputEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelOutputFilterEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputFilterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelOutputTranslaterEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputTranslaterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelOutputEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowPackagesWindowCommand>(action: message => {
         UIThread.Execute(() => {
             PackagesWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <KernelEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowLogColorCommand>(action: message => {
         UIThread.Execute(() => {
             LogColor.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerClientSettingCommand>(action: message => {
         UIThread.Execute(() => {
             MinerClientSetting.ShowWindow(message.Vm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerNamesSeterCommand>(action: message => {
         UIThread.Execute(() => {
             MinerNamesSeter.ShowWindow(message.Vm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowGpuProfilesPageCommand>(action: message => {
         UIThread.Execute(() => {
             GpuProfilesPage.ShowWindow(message.MinerClientsWindowVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerClientAddCommand>(action: message => {
         UIThread.Execute(() => {
             MinerClientAdd.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <MinerGroupEditCommand>(action: message => {
         UIThread.Execute(() => {
             MinerGroupEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <NTMinerWalletEditCommand>(action: message => {
         UIThread.Execute(() => {
             NTMinerWalletEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <MineWorkEditCommand>(action: message => {
         UIThread.Execute(() => {
             MineWorkEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <OverClockDataEditCommand>(action: message => {
         UIThread.Execute(() => {
             OverClockDataEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <PackageEditCommand>(action: message => {
         UIThread.Execute(() => {
             PackageEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <PoolKernelEditCommand>(action: message => {
         UIThread.Execute(() => {
             PoolKernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <PoolEditCommand>(action: message => {
         UIThread.Execute(() => {
             PoolEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowControlCenterHostConfigCommand>(action: message => {
         UIThread.Execute(() => {
             ControlCenterHostConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <SysDicItemEditCommand>(action: message => {
         UIThread.Execute(() => {
             SysDicItemEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <SysDicEditCommand>(action: message => {
         UIThread.Execute(() => {
             SysDicEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <UserEditCommand>(action: message => {
         UIThread.Execute(() => {
             UserEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <WalletEditCommand>(action: message => {
         UIThread.Execute(() => {
             WalletEdit.ShowWindow(message.FormType, message.Source);
         });
     });
 }
 public Task <UserEdit> Create(UserEdit userEdit)
 {
     userEdit.Id = Guid.NewGuid().ToString();
     _userEdits.Add(userEdit.Clone());
     return(Task.FromResult(userEdit.Clone()));
 }
Example #16
0
 public UsersController(QuestContext context, AccountController register, User user, UserEdit userEdit)
 {
     _context  = context;
     _register = register;
     _user     = user;
     _userEdit = userEdit;
 }
Example #17
0
 public UserViewModel()
 {
     this.Save = new DelegateCommand(() => {
         if (!VirtualRoot.IsMinerStudio)
         {
             return;
         }
         if (string.IsNullOrEmpty(this.LoginName))
         {
             return;
         }
         IUser user = NTMinerRoot.Current.UserSet.GetUser(this.LoginName);
         if (user != null)
         {
             VirtualRoot.Execute(new UpdateUserCommand(this));
         }
         else
         {
             VirtualRoot.Execute(new AddUserCommand(this));
         }
         CloseWindow?.Invoke();
     });
     this.Edit = new DelegateCommand <FormType?>((formType) => {
         UserEdit.ShowWindow(formType ?? FormType.Edit, this);
     });
     this.Remove = new DelegateCommand(() => {
         if (!VirtualRoot.IsMinerStudio)
         {
             return;
         }
         if (string.IsNullOrEmpty(this.LoginName))
         {
             return;
         }
         if (VirtualRoot.IsMinerStudio && this.LoginName == SingleUser.LoginName)
         {
             throw new ValidationException("不能删除自己");
         }
         DialogWindow.ShowDialog(message: $"您确定删除{this.LoginName}吗?", title: "确认", onYes: () => {
             VirtualRoot.Execute(new RemoveUserCommand(this.LoginName));
         }, icon: IconConst.IconConfirm);
     });
     this.Enable = new DelegateCommand(() => {
         if (!VirtualRoot.IsMinerStudio)
         {
             return;
         }
         if (this.IsEnabled)
         {
             return;
         }
         DialogWindow.ShowDialog(message: $"您确定启用{this.LoginName}吗?", title: "确认", onYes: () => {
             this.IsEnabled = true;
             VirtualRoot.Execute(new UpdateUserCommand(this));
         }, icon: IconConst.IconConfirm);
     });
     this.Disable = new DelegateCommand(() => {
         if (!VirtualRoot.IsMinerStudio)
         {
             return;
         }
         if (!this.IsEnabled)
         {
             return;
         }
         DialogWindow.ShowDialog(message: $"您确定禁用{this.LoginName}吗?", title: "确认", onYes: () => {
             this.IsEnabled = false;
             VirtualRoot.Execute(new UpdateUserCommand(this));
         }, icon: IconConst.IconConfirm);
     });
 }
Example #18
0
        public UserEdit Update(UserEdit entity)
        {
            var user = _umsDbContext.Users.Add(entity);

            return(user.Entity);
        }
Example #19
0
        private async void Save()
        {
            //  Validate the field of form
            #region Current Email

            var response = MethodsHelper.IsValidField(
                "S",
                0,
                0,
                "email",
                this.CurrentEmail,
                false,
                false,
                string.Empty);
            if (!response.IsSuccess)
            {
                await dialogService.ShowMessage(
                    "Error",
                    response.Message,
                    "Accept");

                return;
            }

            var isValidEmail = MethodsHelper.IsValidEmail(this.CurrentEmail);
            if (!isValidEmail)
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter an valid current email",
                    "Accept");

                return;
            }

            #endregion Current Email

            // Verify if it is valid the email current
            if (!this.CurrentEmail.Equals(this.mainViewModel.UserData.Email))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "This email not are registered in the sistem...!!!",
                    "Accept");

                return;
            }

            #region New Email

            response = MethodsHelper.IsValidField(
                "S",
                0,
                0,
                "new email",
                this.NewEmail,
                false,
                false,
                string.Empty);
            if (!response.IsSuccess)
            {
                await dialogService.ShowMessage(
                    "Error",
                    response.Message,
                    "Accept");

                return;
            }

            isValidEmail = MethodsHelper.IsValidEmail(this.NewEmail);
            if (!isValidEmail)
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter an valid new email",
                    "Accept");

                return;
            }

            #endregion New Email

            #region Confirm Email

            response = MethodsHelper.IsValidField(
                "S",
                0,
                0,
                "confirm email",
                this.ConfirmEmail,
                false,
                false,
                string.Empty);
            if (!response.IsSuccess)
            {
                await dialogService.ShowMessage(
                    "Error",
                    response.Message,
                    "Accept");

                return;
            }

            isValidEmail = MethodsHelper.IsValidEmail(this.ConfirmEmail);
            if (!isValidEmail)
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter an valid confirm email",
                    "Accept");

                return;
            }

            #endregion Confirm Email

            #region Email Confirm and new Email

            response = MethodsHelper.IsValidField(
                "S",
                0,
                0,
                "email confirm",
                this.ConfirmEmail,
                false,
                true,
                this.NewEmail);
            if (!response.IsSuccess)
            {
                await dialogService.ShowMessage(
                    "Error",
                    response.Message,
                    "Accept");

                return;
            }

            #endregion Email Confirm and new Email

            //  Validate that the emails are different
            if (this.CurrentEmail.Equals(this.NewEmail))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "The new email can not be the same as the current email .. !!!",
                    "Accept");

                return;
            }

            //  Set status controls
            SetStatusControl(false, true, "Green", 1);

            response = await apiService.CheckConnection();

            if (!response.IsSuccess)
            {
                //  Set status controls
                SetStatusControl(true, false, "Green", 0);

                await dialogService.ShowMessage(
                    "Error",
                    response.Message,
                    "Accept");

                return;
            }

            //  Use the user registration API
            var userEdit = new UserEdit
            {
                AppName    = MethodsHelper.GetAppName(),
                Email      = this.mainViewModel.UserData.Email,
                FirstName  = this.mainViewModel.UserData.FirstName,
                LastName   = this.mainViewModel.UserData.LastName,
                NewEmail   = this.newEmail,
                Password   = this.mainViewModel.UserData.Password,
                UserId     = this.mainViewModel.UserData.UserId,
                UserTypeId = 5,
            };

            response = await apiService.Put <UserEdit>(
                MethodsHelper.GetUrlAPI(),
                "/api",
                "/Users/PutUserEdit",
                "id",
                this.mainViewModel.Token.TokenType,
                this.mainViewModel.Token.AccessToken,
                userEdit);

            if (!response.IsSuccess)
            {
                //  Set status controls
                SetStatusControl(true, false, "Green", 0);

                await dialogService.ShowMessage(
                    "Error",
                    response.Message,
                    "Accept");

                return;
            }

            //  Set status controls
            SetStatusControl(true, false, "Green", 0);

            //  Set Initialize the fields
            LoadValuesControls(0);

            //  Go back login
            await dialogService.ShowMessage(
                "Information",
                "Successfully modified email, you must log in again...!!! ",
                "Accept");

            //  Navigate to LoginPage
            navigationService.SetMainPage("LoginPage");
        }
        public ActionResult Edit(UserEdit model)
        {
            var user = DB.Account.Single(x => x.Id == model.Id);

            if (!ModelState.IsValid)
            {
                SetChangeModel(user, model);
                ViewBag.IsControlPanelUser = user.TypeUser == (sbyte)TypeUsers.ControlPanelUser;
                return(View(model));
            }

            var activated = false;

            if (Request.Form["activate"] != null)
            {
                if (user.EnabledEnum == UserStatus.Request)
                {
                    activated = true;
                }
                user.EnabledEnum = UserStatus.New;
            }
            else if (Request.Form["block"] != null)
            {
                user.EnabledEnum = UserStatus.Blocked;
            }

            var groups = DB.AccountGroup.Where(x => model.AccountGroupIds.Contains(x.Id));

            user.AccountGroup.Clear();
            foreach (var group in groups)
            {
                user.AccountGroup.Add(group);
            }

            user.AccountRegion.Clear();
            foreach (var regionCode in model.AccountRegionIds)
            {
                user.AccountRegion.Add(new AccountRegion()
                {
                    AccountId = user.Id, RegionId = regionCode
                });
            }

            var password = "";

            // если подтверждение регистрации пользователя
            if (activated)
            {
                password             = GetRandomPassword();
                user.Password        = Md5HashHelper.GetHash(password);
                user.PasswordUpdated = DateTime.Now;
            }

            user.AppointmentId        = model.AppointmentId;
            user.LastUpdatePermisison = DateTime.Now;
            DB.SaveChanges();

            // отправка сообщения пользователю с паролем
            if (activated)
            {
                Mails.SendAccountVerificationMessage(user, password);
            }

            SuccessMessage("Изменения успешно сохранены");
            // если админ - на список админов
            if (user.TypeUser == (sbyte)TypeUsers.ControlPanelUser)
            {
                return(RedirectToAction("AdminList"));
            }

            return(RedirectToAction("Index"));
        }
Example #21
0
        public static DefaultUser InsertUserDetailed(DbContextOptions <DataContext> options, OrganisationEntity organisation, UserEdit sourceUser)
        {
            var branch = new BranchEntity {
                Id = Guid.NewGuid(), OrganisationId = organisation.Id, Name = "Branch 1"
            };
            var user = new UserEntity
            {
                Id        = sourceUser.Id.Value,
                FirstName = sourceUser.FirstName,
                LastName  = sourceUser.LastName,
                Aliases   = sourceUser.Aliases,
                BranchId  = branch.Id,
                Scope     = sourceUser.Scope,
                Config    = sourceUser.Config,
            };

            using (var context = new DataContext(options))
            {
                context.Branch.Add(branch);
                context.Users.Add(user);
                context.SaveChanges();
            }

            return(new DefaultUser()
            {
                User = user,
                Branch = branch,
                Organisation = organisation
            });
        }
Example #22
0
        public IActionResult Update(int id, [Required][FromHeader(Name = "Authorization")] string authToken, [FromBody] UserEdit item)
        {
            if (item == null)
            {
                return(BadRequest());
            }
            if (string.IsNullOrWhiteSpace(item.CurrentPassword))
            {
                return(BadRequest("Please provide Username and Current Password"));
            }

            // Verify the Authorization Token
            if (!_authenticationService.VerifyAuthTokenAndID(id, authToken))
            {
                return(BadRequest("Invalid AuthToken"));
            }

            // Get the current user
            var repoItem = _userRepository.Find(id);

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

            // Make sure the current password is correctly set as a third layer of security
            if (_authenticationService.VerifyPassword(item.CurrentPassword, repoItem.Password_Hash))
            {
                // If the new username doesn't equal the current username...
                if (!string.IsNullOrWhiteSpace(item.NewUsername))
                {
                    if (!_authenticationService.ValidateUsername(item.NewUsername))
                    {
                        return(BadRequest("The new username is invalid, has already been taken or does not meet the minimum requirements"));
                    }

                    // Search that new username to determine if it is available
                    User user = _userRepository.GetAllQuery()
                                .Where(x => x.Username.ToLower().Equals(item.NewUsername.ToLower()))
                                .FirstOrDefault();

                    // If it isn't, notify the user it is unavailable
                    if (user != null)
                    {
                        return(BadRequest("This user already exists"));
                    }

                    // Otherwise, set the new username
                    repoItem.Username = item.NewUsername;
                }

                // If we have a new password, go through the steps to generate a new password and auth token
                if (!string.IsNullOrWhiteSpace(item.NewPassword))
                {
                    if (!_authenticationService.ValidatePassword(item.NewPassword))
                    {
                        return(BadRequest("The new password contains invalid characters or does not meet the minimum requirements"));
                    }

                    repoItem.Password_Hash = _authenticationService.HashPassword(item.NewPassword);
                    repoItem.AuthToken     = _authenticationService.GenerateAuthToken(repoItem.ID, repoItem.Username);
                }

                // Determine if we need to change the email
                if (!string.IsNullOrWhiteSpace(item.NewEmail))
                {
                    if (_authenticationService.ValidateEmail(item.NewEmail))
                    {
                        repoItem.Email = item.NewEmail;
                    }
                    else
                    {
                        return(BadRequest("The email contains invalid characters or does not meet the minimum requirements"));
                    }
                }

                // Update the user
                _userRepository.UpdateAndCommit(repoItem);

                // Return the new authenticated user
                UserAuthenticated authenticatedUser = new UserAuthenticated();
                authenticatedUser.ID        = repoItem.ID;
                authenticatedUser.Username  = repoItem.Username;
                authenticatedUser.AuthToken = repoItem.AuthToken;
                return(new ObjectResult(authenticatedUser));
            }

            return(BadRequest("Current Password is incorrect"));
        }
Example #23
0
 public async Task <Result> InsertUser(ScopeOptions scope, UserEdit user)
 {
     return(await InsertUser(scope, user, GenerateRandomPassword(_userManager.Options.Password), false));
 }
Example #24
0
 public static string GenerateActivateLink(AppOptions appOptions, string token, UserEdit user)
 {
     return($"{appOptions.BaseUrl}/activate?username={System.Net.WebUtility.UrlEncode(user.UserName)}&token={System.Net.WebUtility.UrlEncode(token)}");
 }
Example #25
0
        public async Task <IActionResult> EditUser(UserEdit form, string returnUrl, string action)
        {
            if (action == "Edit")
            {
                if (ModelState.IsValid)
                {
                    var user = await _userManager.FindByIdAsync(form.Id);

                    var userByEmail = await _userManager.FindByEmailAsync(form.Email);

                    if (userByEmail != null && userByEmail.Id != form.Id)
                    {
                        ModelState.AddModelError("", "User update failed: user with the same email already exist!");
                        return(View());
                    }

                    if (ModelState.IsValid)
                    {
                        if (user != null)
                        {
                            user.UserName       = form.Email;
                            user.Email          = form.Email;
                            user.EmailConfirmed = form.EmailConfirmed;
                            await _userManager.UpdateAsync(user);

                            foreach (var role in form.CheckBoxRoles)
                            {
                                if (role.IsChecked)
                                {
                                    await _userManager.AddToRoleAsync(user, role.Name);
                                }
                                else
                                {
                                    await _userManager.RemoveFromRoleAsync(user, role.Name);
                                }
                            }

                            if (string.IsNullOrWhiteSpace(returnUrl))
                            {
                                return(RedirectToAction("Index", "User"));
                            }
                            else
                            {
                                return(Redirect(returnUrl));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "User update failed: user not found!");
                        }
                    }
                }
            }
            else
            {
                return(RedirectToAction("index", "user"));
            }

            UserEdit userEdit = await GetUserEdit(form.Id);

            return(View(userEdit));
        }
        public async Task <IActionResult> Edit(UserEdit userEdit)
        {
            AppUser appUser = await _userManager.FindByNameAsync(User.Identity.Name);

            var oldEmail          = appUser.Email;
            var oldName           = appUser.UserName;
            var fullNameFromModel = userEdit.FirstName.ToLower() + "-" + userEdit.LastName.ToLower();

            if (ModelState.IsValid)
            {
                //email edit
                var isEmailAlreadyExists = _context.Users.Any(x => x.Email == userEdit.Email);
                if (oldEmail != userEdit.Email)
                {
                    if (isEmailAlreadyExists)
                    {
                        ModelState.AddModelError("Email", "User with this email already exists");
                        return(View(userEdit));
                    }
                    appUser.Email = userEdit.Email;
                }
                else
                {
                    appUser.Email = oldEmail;
                }

                //name edit
                var isNameAlreadyExists = _context.Users.Any(x => x.UserName == fullNameFromModel);
                if (oldName != fullNameFromModel)
                {
                    if (isNameAlreadyExists)
                    {
                        ModelState.AddModelError("LastName", "User with this name already exists");
                        return(View(userEdit));
                    }
                    appUser.UserName = fullNameFromModel;
                }
                else
                {
                    appUser.UserName = oldName;
                }

                //telephone number edit
                if (userEdit.PhoneNumber != null)
                {
                    appUser.PhoneNumber = userEdit.PhoneNumber;
                }


                //password edit
                if (userEdit.Password != null)
                {
                    appUser.PasswordHash = _passwordHasher.HashPassword(appUser, userEdit.Password);
                }


                if (oldEmail != appUser.Email)
                {
                    appUser.EmailConfirmed = false;
                }

                IdentityResult result = await _userManager.UpdateAsync(appUser);

                if (result.Succeeded)
                {
                    if (oldEmail != appUser.Email)
                    {
                        var token = await _userManager.GenerateEmailConfirmationTokenAsync(appUser);

                        var confirmationLink = Url.Action("ConfirmEmail", "Account",
                                                          new { userId = appUser.Id, token = token }, Request.Scheme);

                        _logger.Log(LogLevel.Warning, confirmationLink);

                        await _emailSender.SendEmailAsync(appUser.Email, "Email Confirmation",
                                                          "Your confirmation link: " + confirmationLink);

                        TempData["Success"] = "We send you an Email with reset password link.";
                    }


                    TempData["Success"] = "Your details have been changed!";
                    return(Redirect("/account/edit"));
                }
                TempData["Error"] = "An error occures. Please try again.";
            }

            return(View());
        }
 public async Task <IActionResult> UpdateCurrentUser([FromBody] UserEdit user)
 {
     return(await UpdateUser(IdentityHelper.GetUserId(User), user));
 }
Example #28
0
 public override void Link()
 {
     VirtualRoot.Window <ShowDialogWindowCommand>(LogEnum.DevConsole,
                                                  action: message => {
         UIThread.Execute(() => {
             DialogWindow.ShowDialog(message: message.Message, title: message.Title, onYes: message.OnYes, icon: message.Icon);
         });
     });
     VirtualRoot.Window <ShowQQGroupQrCodeCommand>(LogEnum.DevConsole,
                                                   action: message => {
         UIThread.Execute(() => {
             QQGroupQrCode.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowCalcCommand>(LogEnum.DevConsole,
                                          action: message => {
         UIThread.Execute(() => {
             Calc.ShowWindow(message.CoinVm);
         });
     });
     VirtualRoot.Window <ShowFileDownloaderCommand>(LogEnum.DevConsole,
                                                    action: message => {
         UIThread.Execute(() => {
             FileDownloader.ShowWindow(message.DownloadFileUrl, message.FileTitle, message.DownloadComplete);
         });
     });
     VirtualRoot.Window <ShowAboutPageCommand>(LogEnum.DevConsole,
                                               action: message => {
         UIThread.Execute(() => {
             AboutPage.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowKernelOutputPageCommand>(LogEnum.DevConsole,
                                                      action: message => {
         UIThread.Execute(() => {
             KernelOutputPage.ShowWindow(message.SelectedKernelOutputVm);
         });
     });
     VirtualRoot.Window <ShowKernelInputPageCommand>(LogEnum.DevConsole,
                                                     action: message => {
         UIThread.Execute(() => {
             KernelInputPage.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowGroupPageCommand>(LogEnum.DevConsole,
                                               action: message => {
         UIThread.Execute(() => {
             GroupPage.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowSysDicPageCommand>(LogEnum.DevConsole,
                                                action: message => {
         UIThread.Execute(() => {
             SysDicPage.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowVirtualMemoryCommand>(LogEnum.DevConsole,
                                                   action: message => {
         UIThread.Execute(() => {
             VirtualMemory.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowRestartWindowsCommand>(LogEnum.DevConsole,
                                                    action: message => {
         UIThread.Execute(() => {
             RestartWindows.ShowDialog();
         });
     });
     VirtualRoot.Window <ShowNotificationSampleCommand>(LogEnum.DevConsole,
                                                        action: message => {
         UIThread.Execute(() => {
             NotificationSample.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowOuterPropertyCommand>(LogEnum.DevConsole,
                                                   action: message => {
         UIThread.Execute(() => {
             OuterProperty.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowInnerPropertyCommand>(LogEnum.DevConsole,
                                                   action: message => {
         UIThread.Execute(() => {
             InnerProperty.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowUserPageCommand>(LogEnum.DevConsole,
                                              action: message => {
         UIThread.Execute(() => {
             UserPage.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowKernelDownloaderCommand>(LogEnum.DevConsole,
                                                      action: message => {
         UIThread.Execute(() => {
             KernelDownloading.ShowWindow(message.KernelId, message.DownloadComplete);
         });
     });
     VirtualRoot.Window <EnvironmentVariableEditCommand>(LogEnum.DevConsole,
                                                         action: message => {
         UIThread.Execute(() => {
             EnvironmentVariableEdit.ShowWindow(message.CoinKernelVm, message.EnvironmentVariable);
         });
     });
     VirtualRoot.Window <InputSegmentEditCommand>(LogEnum.DevConsole,
                                                  action: message => {
         UIThread.Execute(() => {
             InputSegmentEdit.ShowWindow(message.CoinKernelVm, message.Segment);
         });
     });
     VirtualRoot.Window <CoinKernelEditCommand>(LogEnum.DevConsole,
                                                action: message => {
         UIThread.Execute(() => {
             CoinKernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <CoinEditCommand>(LogEnum.DevConsole,
                                          action: message => {
         UIThread.Execute(() => {
             CoinEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <ShowContainerWindowCommand>(LogEnum.DevConsole,
                                                     action: message => {
         UIThread.Execute(() => {
             ContainerWindow window = ContainerWindow.GetWindow(message.Vm);
             window?.ShowWindow();
         });
     });
     VirtualRoot.Window <GroupEditCommand>(LogEnum.DevConsole,
                                           action: message => {
         UIThread.Execute(() => {
             GroupEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <KernelInputEditCommand>(LogEnum.DevConsole,
                                                 action: message => {
         UIThread.Execute(() => {
             KernelInputEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <KernelOutputFilterEditCommand>(LogEnum.DevConsole,
                                                        action: message => {
         UIThread.Execute(() => {
             KernelOutputFilterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <KernelOutputTranslaterEditCommand>(LogEnum.DevConsole,
                                                            action: message => {
         UIThread.Execute(() => {
             KernelOutputTranslaterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <KernelOutputEditCommand>(LogEnum.DevConsole,
                                                  action: message => {
         UIThread.Execute(() => {
             KernelOutputEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <ShowPackagesWindowCommand>(LogEnum.DevConsole,
                                                    action: message => {
         UIThread.Execute(() => {
             PackagesWindow.ShowWindow();
         });
     });
     VirtualRoot.Window <KernelEditCommand>(LogEnum.DevConsole,
                                            action: message => {
         UIThread.Execute(() => {
             KernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <ShowLogColorCommand>(LogEnum.DevConsole,
                                              action: message => {
         UIThread.Execute(() => {
             LogColor.ShowWindow();
         });
     });
     VirtualRoot.Window <ShowGpuProfilesPageCommand>(LogEnum.DevConsole,
                                                     action: message => {
         UIThread.Execute(() => {
             GpuProfilesPage.ShowWindow(message.MinerClientsWindowVm);
         });
     });
     VirtualRoot.Window <PackageEditCommand>(LogEnum.DevConsole,
                                             action: message => {
         UIThread.Execute(() => {
             PackageEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <PoolKernelEditCommand>(LogEnum.DevConsole,
                                                action: message => {
         UIThread.Execute(() => {
             PoolKernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <PoolEditCommand>(LogEnum.DevConsole,
                                          action: message => {
         UIThread.Execute(() => {
             PoolEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <SysDicItemEditCommand>(LogEnum.DevConsole,
                                                action: message => {
         UIThread.Execute(() => {
             SysDicItemEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <SysDicEditCommand>(LogEnum.DevConsole,
                                            action: message => {
         UIThread.Execute(() => {
             SysDicEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <UserEditCommand>(LogEnum.DevConsole,
                                          action: message => {
         UIThread.Execute(() => {
             UserEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.Window <WalletEditCommand>(LogEnum.DevConsole,
                                            action: message => {
         UIThread.Execute(() => {
             WalletEdit.ShowWindow(message.FormType, message.Source);
         });
     });
 }
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEdit user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

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

            Task <AuthorizationResult> manageUsersPolicy =
                _authorizationService.AuthorizeAsync(User, id, AuthPolicies.ManageUserByUserIdPolicy);
            Task <AuthorizationResult> assignRolePolicy = _authorizationService.AuthorizeAsync(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 (IdentityHelper.GetUserId(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 (IdentityHelper.GetUserId(User) == id && (appUser.UserName != user.UserName ||
                                                             !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new[] { "The username/password couple is invalid." });
                    }
                }

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

                    Tuple <bool, string[]> 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 #30
0
        public IActionResult Edit(string id, UserEdit model)
        {
            try
            {
                //obtenemos los datos de usuario y cogemos los datos del form a result
                var result = usrManager.GetByUserId(id);
                result.UserName = model.User.UserName;
                result.Email    = model.User.Email;
                // si no se ha introducido una nueva contrseña no hace nada
                if (model.User.Password != null)
                {
                    //creamos un nuevo hasher para encriptar la password
                    var hasher = new PasswordHasher <ApplicationUser>();
                    //desde el hasher mediante la password introducida creamos la password hasheada
                    string hashedNewPassword = hasher.HashPassword(result, model.User.Password);
                    result.PasswordHash = hashedNewPassword;
                }



                //incializamos necesario
                var rolUser  = _userManager.GetRolesAsync(result).Id;
                var rolUsers = _userManager.GetRolesAsync(result);

                if (model.Option != null)
                {
                    switch (_userManager.GetRolesAsync(result).Result.FirstOrDefault())
                    {
                    case "Admin":
                        //lo eliminamos del rol
                        _userManager.RemoveFromRoleAsync(result, "Admin").Wait();
                        //añadimos al usuario al rol
                        _userManager.AddToRoleAsync(result, model.Option).Wait();

                        break;

                    case "Professional":
                        //lo eliminamos del rol
                        _userManager.RemoveFromRoleAsync(result, "Professional").Wait();
                        //añadimos al usuario al rol
                        _userManager.AddToRoleAsync(result, model.Option).Wait();
                        break;

                    case "Business":
                        //lo eliminamos del rol
                        _userManager.RemoveFromRoleAsync(result, "Business").Wait();
                        //añadimos al usuario al rol
                        _userManager.AddToRoleAsync(result, model.Option).Wait();
                        break;

                    case "Registered":
                        //lo eliminamos del rol
                        _userManager.RemoveFromRoleAsync(result, "Registered").Wait();
                        //añadimos al usuario al rol
                        _userManager.AddToRoleAsync(result, model.Option).Wait();
                        break;

                    case "":
                        break;
                    }
                }

                //guardamos los datos
                usrManager.Context.SaveChanges();
                TempData["editado"] = "El usuario se ha editado correctamente";
                _log.LogInformation("Usuario editado correctamente: Id " + id.ToString());
                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                _log.LogError(ex.Message, ex);
                return(View(model));
            }
        }
Example #31
0
        public void EditUser(User targetUser, UserEdit userEdit, bool removeAvatar, bool removePhoto, HttpPostedFileBase avatarFile, HttpPostedFileBase photoFile, string ip, User user)
        {
            if (!String.IsNullOrWhiteSpace(userEdit.NewEmail))
            {
                ChangeEmail(targetUser, userEdit.NewEmail, user, ip, userEdit.IsApproved);
            }
            if (!String.IsNullOrWhiteSpace(userEdit.NewPassword))
            {
                SetPassword(targetUser, userEdit.NewPassword, ip, user);
            }
            if (targetUser.IsApproved != userEdit.IsApproved)
            {
                UpdateIsApproved(targetUser, userEdit.IsApproved, user, ip);
            }

            var profile = _profileRepository.GetProfile(targetUser.UserID);

            profile.IsSubscribed     = userEdit.IsSubscribed;
            profile.ShowDetails      = userEdit.ShowDetails;
            profile.IsPlainText      = userEdit.IsPlainText;
            profile.HideVanity       = userEdit.HideVanity;
            profile.TimeZone         = userEdit.TimeZone;
            profile.IsDaylightSaving = userEdit.IsDaylightSaving;
            profile.Signature        = _textParsingService.ForumCodeToHtml(userEdit.Signature);
            profile.Location         = userEdit.Location;
            profile.Dob            = userEdit.Dob;
            profile.Web            = userEdit.Web;
            profile.Aim            = userEdit.Aim;
            profile.Icq            = userEdit.Icq;
            profile.YahooMessenger = userEdit.YahooMessenger;
            profile.Facebook       = userEdit.Facebook;
            profile.Twitter        = userEdit.Twitter;
            if (removeAvatar)
            {
                profile.AvatarID = null;
            }
            if (removePhoto)
            {
                profile.ImageID = null;
            }
            _profileRepository.Update(profile);

            var newRoles = userEdit.Roles ?? new string[0];

            _roleRepository.ReplaceUserRoles(targetUser.UserID, newRoles);
            foreach (var role in targetUser.Roles)
            {
                if (!newRoles.Contains(role))
                {
                    _securityLogService.CreateLogEntry(user, targetUser, ip, role, SecurityLogType.UserRemovedFromRole);
                }
            }
            foreach (var role in newRoles)
            {
                if (!targetUser.Roles.Contains(role))
                {
                    _securityLogService.CreateLogEntry(user, targetUser, ip, role, SecurityLogType.UserAddedToRole);
                }
            }

            if (avatarFile != null && avatarFile.ContentLength > 0)
            {
                var avatarID = _userAvatarRepository.SaveNewAvatar(targetUser.UserID, avatarFile.GetBytes(), DateTime.UtcNow);
                profile.AvatarID = avatarID;
                _profileRepository.Update(profile);
            }

            if (photoFile != null && photoFile.ContentLength > 0)
            {
                var imageID = _userImageRepository.SaveNewImage(targetUser.UserID, 0, true, photoFile.GetBytes(), DateTime.UtcNow);
                profile.ImageID = imageID;
                _profileRepository.Update(profile);
            }
        }