// GET: Users/Create public ActionResult Create() { var model = new UserEditorModel(); var usersRole = RoleManager.Roles.First(r => r.Name == Roles.Users); model.permissions = new string[] { usersRole.Id }; return View(model); }
/// <summary> /// An action returning a page to a user can edit their profile /// </summary> /// <returns>If logged in: Returns a page where a user can edit their profile</returns> public ActionResult Edit() { MeetupModel model = new MeetupModel(); List <User> users = model.Users.ToList(); int?infoID = this.UserId(); if (infoID is null) { return(RedirectToAction("Index", "Home")); } User editUser = users.SingleOrDefault(userInfo => userInfo.Id == infoID); UserEditorModel editModel = new UserEditorModel(); //Get business list List <Business> selectedBusinesses = editUser.GetBusinesses().ToList(); List <Business> unselectedBusinesses = model.Businesses.ToList().Except(selectedBusinesses).ToList(); //Get interest list List <Interest> selectedInterests = editUser.GetInterests().ToList(); List <Interest> unselectedInterests = model.Interests.ToList().Except(selectedInterests).ToList(); editModel.UnselectedBusinesses = unselectedBusinesses; editModel.SelectedBusinesses = selectedBusinesses; editModel.UnselectedInterests = unselectedInterests; editModel.SelectedInterests = selectedInterests; editModel.Description = editUser.Description; editModel.FirstName = editUser.FirstName; editModel.LastName = editUser.LastName; editModel.Address = new AddressModel(); editModel.Address.City = editUser.Address.CityName; editModel.Address.Country = editUser.Address.Country; editModel.Address.CityZipCode = editUser.Address.ZipCode.ToString(); editModel.Address.StreetName = editUser.Address.StreetName; editModel.Address.StreetNumber = editUser.Address.StreetNumber; editModel.Organizations = new List <OrganizationModel>(); foreach (UsersOrganizations organization in editUser.UsersOrganizations) { editModel.Organizations.Add(new OrganizationModel() { Id = organization.Id, Name = organization.Organization.Name, EndDate = organization.EndDate, StartDate = organization.StartDate, State = "old" }); } return(View(editModel)); }
public UserEditorForm(UserEditorModel model) { InitializeComponent(); _presenter = new UserEditorPresenter(this, model); valUserName.SetIconAlignment(txtUserName, ErrorIconAlignment.MiddleRight); valFirstName.SetIconAlignment(txtFirstName, ErrorIconAlignment.MiddleRight); valLastName.SetIconAlignment(txtLastName, ErrorIconAlignment.MiddleRight); valPassword.SetIconAlignment(txtPassword, ErrorIconAlignment.MiddleRight); valReTypePassword.SetIconAlignment(txtReTypePassword, ErrorIconAlignment.MiddleRight); this.Load += UserEditorForm_Load; }
public ViewResult Edit(string login) { var user = _identityService.GetUser(login); var userView = Mapper.Map <User, UserEditModel>(user); var userRoles = user.Roles.Select(rol => rol.Name).ToArray(); var editorModel = new UserEditorModel { Login = user.Login, UserModel = userView, Roles = CreateSelectList(userRoles) }; return(View(editorModel)); }
public async Task<ActionResult> Create([Bind(Include = AllowedFields)] UserEditorModel editor, string[] permissions) { try { if (await CreateUser(editor, permissions, false, false)) { SetSuccessMessage(string.Format("User {0} was created successfully!", editor.FullName())); return RedirectToAction("Index"); } } catch(Exception e) { SetFailureMessage(e.Message); } editor.permissions = permissions; return View(editor); }
public async Task<ActionResult> Edit(string id, [Bind(Include = AllowedFields)] UserEditorModel editor, string[] permissions) { var user = await UserManager.FindByIdAsync(id); if (user == null) { return HttpNotFound(); } try { user.Email = editor.Email; user.EmailConfirmed = editor.EmailConfirmed; user.FirstName = editor.FirstName; user.LastName = editor.LastName; user.LockoutEnabled = editor.LockoutEnabled; user.LockoutEndDateUtc = editor.LockoutEndDateUtc; user.PhoneNumber = editor.PhoneNumber; user.PhoneNumberConfirmed = editor.PhoneNumberConfirmed; user.TwoFactorEnabled = editor.TwoFactorEnabled; ApplyUserRoles(user, permissions); var result = await UserManager.UpdateAsync(user); if (result == IdentityResult.Success) { ModelState.Clear(); SetSuccessMessage("User information for {0} was saved successfully!", user.FullName()); return RedirectToAction("Index"); } else { throw new Exception(string.Join("\r\n", result.Errors)); } } catch(Exception e) { SetFailureMessage(e.Message); } editor.permissions = permissions; return View(editor); }
public ActionResult Edit(UserEditorModel editorModel, string[] rolesSelected) { if (ModelState.IsValid) { var user = _identityService.GetUser(editorModel.Login); Mapper.Map(editorModel.UserModel, user); user.Roles.Clear(); foreach (var role in _roleService.GetAll().Where(rol => rolesSelected.Contains(rol.Name))) { user.Roles.Add(role); } _identityService.Update(user); return(RedirectToAction("Index")); } return(View(editorModel)); }
/// <summary> /// Returns the edit page. Used for when something is wrong in the view model /// </summary> /// <param name="viewModel">The model with the information to show on the editing page</param> /// <param name="editUser">the user to edit</param> /// <param name="model">the database access</param> /// <returns>The profile edit page</returns> private ActionResult ReturnEdit(UserEditorModel viewModel, User editUser, MeetupModel model) { //Get businesses lists viewModel.SelectedBusinesses = new List <Business>(); List <Business> allBusinessesList = model.Businesses.ToList(); List <UsersBusiness> businessesList = editUser.UsersBusinesses.ToList(); foreach (UsersBusiness usersBusiness in businessesList) { viewModel.SelectedBusinesses.Add(usersBusiness.Business); allBusinessesList.Remove(usersBusiness.Business); } viewModel.UnselectedBusinesses = allBusinessesList; //Get interests lists viewModel.SelectedInterests = new List <Interest>(); List <Interest> allInterestsList = model.Interests.ToList(); List <UsersInterest> interestsList = editUser.UsersInterests.ToList(); foreach (UsersInterest usersInterest in interestsList) { viewModel.SelectedInterests.Add(usersInterest.Interest); allInterestsList.Remove(usersInterest.Interest); } viewModel.UnselectedInterests = allInterestsList; if (viewModel.Organizations is null) { viewModel.Organizations = new List <OrganizationModel>(); } //Remove removed organizations from the view model viewModel.Organizations = viewModel.Organizations.Where(o => o.State != "removed" && o.State != "new-removed").ToList(); return(View("Edit", viewModel)); }
/// <summary> /// Processes the submit. /// </summary> /// <param name="model">The model.</param> /// <param name="entity">The entity.</param> /// <returns></returns> protected ActionResult ProcessSubmit(UserEditorModel model, User entity) { Mandate.ParameterNotNull(model, "model"); //bind it's data model.BindModel(this); //if there's model errors, return the view if (!ModelState.IsValid) { AddValidationErrorsNotification(); return(View("Edit", model)); } //persist the data using (var uow = Hive.Create <ISecurityStore>()) { // Map the user if (entity == null) { //map to new entity, set default date values model.LastPasswordChangeDate = DateTime.UtcNow; model.LastActivityDate = DateTime.UtcNow; model.LastLoginDate = DateTime.UtcNow; entity = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <UserEditorModel, User>(model); } else { //map to existing entity BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map(model, entity); } uow.Repositories.AddOrUpdate(entity); // Remove any removed user groups foreach (var relation in uow.Repositories.GetParentRelations(entity.Id, FixedRelationTypes.UserGroupRelationType) .Where(x => !model.UserGroups.Contains(x.SourceId))) { uow.Repositories.RemoveRelation(relation); } // Add any new user groups var existingRelations = uow.Repositories.GetParentRelations(entity.Id, FixedRelationTypes.UserGroupRelationType).Select(x => x.SourceId).ToArray(); foreach (var userGroupId in model.UserGroups.Where(x => !existingRelations.Contains(x))) { uow.Repositories.AddRelation(new Relation(FixedRelationTypes.UserGroupRelationType, userGroupId, entity.Id)); } uow.Complete(); //we may have changed the user data, so we need to ensure that the latest user data exists in the Identity object so we'll re-issue a forms auth ticket here if (HttpContext.User.Identity.Name.InvariantEquals(entity.Username)) { HttpContext.CreateUmbracoAuthTicket(entity); } Notifications.Add(new NotificationMessage( "User.Save.Message".Localize(this), "User.Save.Title".Localize(this), NotificationType.Success)); //add path for entity for SupportsPathGeneration (tree syncing) to work GeneratePathsForCurrentEntity(uow.Repositories.GetEntityPaths <TypedEntity>(entity.Id, FixedRelationTypes.DefaultRelationType)); return(RedirectToAction("Edit", new { id = entity.Id })); } }
public async Task <Response> CreateOrUpdate( [FromBody] UserEditorModel model, [FromServices] UserManager <UserEntity> userManager, [FromServices] INotificator notificator) { UserEntity user; if (model.Id.HasValue) { user = await userManager.Users .Where(x => x.Id == model.Id.Value) .SingleOrDefaultAsync() ?? throw new EntityNotFoundException($"Пользователь (id = {model.Id.Value}) не найден"); } else { user = new UserEntity(); } // часовой пояс if (!TimeZoneHelper.IsTimeZoneIdValid(model.TimeZoneId)) { throw new InvalidRequestDataException("Не корректный часовой пояс"); } user.TimeZoneId = model.TimeZoneId; // телефон if (!String.IsNullOrWhiteSpace(model.PhoneNumber)) { if (!model.PhoneNumber.CleanupPhone().IsMobilePhoneFormat()) { throw new InvalidRequestDataException("Не корректный номер телефона", nameof(model.PhoneNumber)); } user.PhoneNumber = model.PhoneNumber.ResolvePhoneTo7Format(); } // email if (!model.Id.HasValue) { if (String.IsNullOrWhiteSpace(model.Email)) { throw new InvalidRequestDataException("Email обязателен для нового пользователя", nameof(model.Email)); } user.Email = model.Email; user.UserName = model.Email; } // восстановление пользователя if (!user.IsDeleted && user.IsDeleted) { user.IsDeleted = model.IsDeleted; _logger.LogInformation($"Восстанавливаем пользователя (Id = {user.Id}) из удалённых"); } if (model.Id.HasValue) { // обновляем var result = await userManager.UpdateAsync(user); if (!result.Succeeded) { throw new InvalidRequestDataException(result.Errors); } _logger.LogInformation($"Успешно обновлен пользователь (Id = {model.Id})"); } else { // создаём var result = await userManager.CreateAsync(user); if (!result.Succeeded) { throw new InvalidRequestDataException(result.Errors); } // для завершении регистрации пользователь должен задать пароль var token = await userManager.GeneratePasswordResetTokenAsync(user); notificator.NotifyAndForgot(new RegistrationMetadata( user.Email, token)); _logger.LogInformation($"Успешно создан новый пользователь (Id = {user.Id}, email = {user.Email})"); } return(new Response()); }
public ActionResult Edit(UserEditorModel viewModel) { //Get user MeetupModel model = new MeetupModel(); int? userId = this.UserId(); if (userId == null) { return(RedirectToAction("Index", "HomeController")); } User editUser = model.Users.SingleOrDefault(userInfo => userInfo.Id == userId); //Get businesses list if (string.IsNullOrEmpty(viewModel.ChosenBusinesses)) { viewModel.ChosenBusinesses = ""; } string[] selectedBusnisses = viewModel.ChosenBusinesses.Split(','); model.UsersBusinesses.RemoveRange(editUser.UsersBusinesses.Where(b => !selectedBusnisses.Contains(b.Business.Name))); List <Business> businesses = model.Businesses.Where(b => selectedBusnisses.Contains(b.Name)).ToList(); businesses = businesses.Where(b => !editUser.UsersBusinesses.Any(ub => ub.BusinessId == b.Id)).ToList(); foreach (Business business in businesses) { editUser.UsersBusinesses.Add(new UsersBusiness(business, editUser)); } //Get interests list if (string.IsNullOrEmpty(viewModel.ChosenInterests)) { viewModel.ChosenInterests = ""; } string[] selectedInterests = viewModel.ChosenInterests.Split(','); model.UsersInterests.RemoveRange(editUser.UsersInterests.Where(i => !selectedInterests.Contains(i.Interest.Name))); List <Interest> interests = model.Interests.Where(i => selectedInterests.Contains(i.Name)).ToList(); interests = interests.Where(i => !editUser.UsersInterests.Any(ui => ui.InterestId == i.Id)).ToList(); foreach (Interest interest in interests) { editUser.UsersInterests.Add(new UsersInterest(interest, editUser)); } //Make sure model is valid if (!ModelState.IsValid) { return(ReturnEdit(viewModel, editUser, model)); } else { if (!(viewModel.Organizations is null)) { //Create organizations list for (int i = 0; i < viewModel.Organizations.Count; i++) { OrganizationModel organization = viewModel.Organizations[i]; if (organization.State == "removed") { //Remove removed organizations UsersOrganizations removeOrganization = editUser.UsersOrganizations.SingleOrDefault(o => o.Id == organization.Id); if (!(removeOrganization is null)) { model.UsersOrganizations.Remove(removeOrganization); } } else if (organization.State == "old" || organization.State == "new") { //Make sure organization is in a valid state if (string.IsNullOrWhiteSpace(organization.Name)) { ModelState.AddModelError("Organizations[" + i + "].Name", "Feltet Organisation navn skal udfyldes."); return(ReturnEdit(viewModel, editUser, model)); } if (organization.StartDate is null) { ModelState.AddModelError("Organizations[" + i + "].StartDate", "Feltet ansættelsesdato skal udfyldes."); return(ReturnEdit(viewModel, editUser, model)); } if (organization.StartDate > DateTime.Now) { ModelState.AddModelError("Organizations[" + i + "].StartDate", "Ansættelsesdato må ikke være i fremtiden."); return(ReturnEdit(viewModel, editUser, model)); } else if (!(organization.EndDate is null)) { if (organization.StartDate.Value >= organization.EndDate) { ModelState.AddModelError("Organizations[" + i + "].StartDate", "Ansættelsesdato må ikke være efter s**t datoen."); return(ReturnEdit(viewModel, editUser, model)); } else if (organization.EndDate > DateTime.Now) { ModelState.AddModelError("Organizations[" + i + "].EndDate", "S**t datoen kan ikke være i fremtiden."); return(ReturnEdit(viewModel, editUser, model)); } } //Get the organization the user is editing or create a new one latter UsersOrganizations editOrganization = null; Organization newOrganization = null; Organization oldOrganization = null; if (organization.State == "old") { editOrganization = editUser.UsersOrganizations.SingleOrDefault(o => o.Id == organization.Id); if (editOrganization is null) { continue; } oldOrganization = editOrganization.Organization; } else if (organization.State != "new") { continue; } //Check new organization name if (organization.State == "new" || organization.Name != oldOrganization.Name) { newOrganization = model.Organizations.SingleOrDefault(o => o.Name == organization.Name); if (newOrganization is null) { //Call api to check organization name try { if (Organization.NameExists(organization.Name)) { newOrganization = new Organization(organization.Name); } else { ModelState.AddModelError("Organizations[" + i + "].Name", "Organisationen \"" + organization.Name + "\" eksisterer ikke."); return(ReturnEdit(viewModel, editUser, model)); } } catch (WebException) { ModelState.AddModelError("Organizations[" + i + "].Name", "Fejlede i at bedømme organisation navnet. Prøv igen senere"); return(ReturnEdit(viewModel, editUser, model)); } } } //Create new organization object or fill old object if (editOrganization is null) { editOrganization = new UsersOrganizations(newOrganization, editUser, organization.StartDate.Value); model.UsersOrganizations.Add(editOrganization); } else { if (!(newOrganization is null)) { editOrganization.Organization = newOrganization; } editOrganization.StartDate = organization.StartDate.Value; } editOrganization.EndDate = organization.EndDate; } } } if (!(viewModel.Picture is null)) { //Update profile picture if (!viewModel.Picture.ContentType.Contains("image")) { ModelState.AddModelError("Picture", "Feltet \"Profil Billed\" accepterer kun billeder."); return(ReturnEdit(viewModel, editUser, model)); } editUser.PictureUri = "data:image/png;base64," + viewModel.Picture.PictureFileToString(); } //Update everything else editUser.Description = viewModel.Description; editUser.Address.CityName = viewModel.Address.City; editUser.Address.Country = viewModel.Address.Country; editUser.Address.StreetName = viewModel.Address.StreetName; editUser.Address.StreetNumber = viewModel.Address.StreetNumber; editUser.Address.ZipCode = Convert.ToInt32(viewModel.Address.CityZipCode); editUser.FirstName = viewModel.FirstName; editUser.LastName = viewModel.LastName; model.SaveChanges(); return(RedirectToAction("Profile", "Users", new { editUser.Id })); } }