public async Task <DepartmentCreationResult> RegisterDepartment([FromBody] DepartmentCreationInput model) { DepartmentCreationResult creationResult = new DepartmentCreationResult(); var user = new Microsoft.AspNet.Identity.EntityFramework6.IdentityUser { UserName = model.Username, Email = model.Email, SecurityStamp = Guid.NewGuid().ToString() }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserProfile up = new UserProfile(); up.UserId = user.Id; var names = model.FullName.Split(char.Parse(" ")); if (names.Length > 1) { up.FirstName = names[0]; up.LastName = names[1]; } else { up.FirstName = model.FullName; up.LastName = ""; } _userProfileService.SaveProfile(0, up); _usersService.AddUserToUserRole(user.Id); _usersService.InitUserExtInfo(user.Id); var savedUser = await _userManager.FindByIdAsync(user.Id); Department department = _departmentsService.CreateDepartment(model.DepartmentName, user.Id, model.DepartmentType); //_departmentsService.AddUserToDepartment(model.DepartmentName, user.Id); _departmentsService.AddUserToDepartment(department.DepartmentId, user.Id); _subscriptionsService.CreateFreePlanPayment(department.DepartmentId, user.Id); _emailMarketingProvider.SubscribeUserToAdminList(up.FirstName, up.LastName, model.Email); _departmentsService.InvalidateDepartmentMembers(); _emailService.SendWelcomeEmail(department.Name, $"{up.FirstName} {up.LastName}", model.Email, model.Username, model.Password, department.DepartmentId); creationResult.Successful = true; } else { creationResult.Successful = false; } return(creationResult); }
public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null) { if (Config.SystemBehaviorConfig.RedirectHomeToLogin) { return(RedirectToAction("LogOn", "Account")); } ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new Microsoft.AspNet.Identity.EntityFramework6.IdentityUser { UserName = model.Username, Email = model.Email, SecurityStamp = Guid.NewGuid().ToString() }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserProfile up = new UserProfile(); up.UserId = user.Id; up.FirstName = model.FirstName; up.LastName = model.LastName; _userProfileService.SaveProfile(0, up); _usersService.AddUserToUserRole(user.Id); _usersService.InitUserExtInfo(user.Id); var savedUser = await _userManager.FindByIdAsync(user.Id); Department department = _departmentsService.CreateDepartment(model.DepartmentName, user.Id, model.DepartmentType); _departmentsService.AddUserToDepartment(model.DepartmentName, user.Id); _subscriptionsService.CreateFreePlanPayment(department.DepartmentId, user.Id); _emailMarketingProvider.SubscribeUserToAdminList(model.FirstName, model.LastName, model.Email); _departmentsService.InvalidateDepartmentMembers(); _emailService.SendWelcomeEmail(department.Name, $"{model.FirstName} {model.LastName}", model.Email, model.Username, model.Password, department.DepartmentId); //await _signInManager.SignInAsync(savedUser, isPersistent: false); //return RedirectToLocal(returnUrl); var loginResult = await _signInManager.PasswordSignInAsync(model.Username, model.Password, true, lockoutOnFailure : false); if (result.Succeeded) { await HttpContext.Authentication.SignInAsync("ResgridCookieMiddlewareInstance", HttpContext.User, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(24), IsPersistent = false, AllowRefresh = false }); if (!String.IsNullOrWhiteSpace(returnUrl)) { return(RedirectToLocal(returnUrl)); } else { return(RedirectToAction("Dashboard", "Home", new { Area = "User" })); } } else { return(View(model)); } } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Register(RegisterViewModel model, CancellationToken cancellationToken, string returnUrl = null) { if (Config.SystemBehaviorConfig.RedirectHomeToLogin) { return(RedirectToAction("LogOn", "Account")); } ViewBag.DepartmentTypes = new SelectList(model.DepartmentTypes); model.SiteKey = WebConfig.RecaptchaPublicKey; ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new IdentityUser { UserName = model.Username, Email = model.Email, SecurityStamp = Guid.NewGuid().ToString() }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserProfile up = new UserProfile(); up.UserId = user.Id; up.FirstName = model.FirstName; up.LastName = model.LastName; await _userProfileService.SaveProfileAsync(0, up, cancellationToken); _usersService.AddUserToUserRole(user.Id); _usersService.InitUserExtInfo(user.Id); Department department = await _departmentsService.CreateDepartmentAsync(model.DepartmentName, user.Id, model.DepartmentType, null, cancellationToken); await _departmentsService.AddUserToDepartmentAsync(department.DepartmentId, user.Id, true, cancellationToken); await _subscriptionsService.CreateFreePlanPaymentAsync(department.DepartmentId, user.Id, cancellationToken); // Guard, in case testing has caching turned on for the shared redis cache there can be artifacts _departmentsService.InvalidateAllDepartmentsCache(department.DepartmentId); _departmentsService.InvalidateDepartmentMembers(); _emailMarketingProvider.SubscribeUserToAdminList(model.FirstName, model.LastName, model.Email); _emailService.SendWelcomeEmail(department.Name, $"{model.FirstName} {model.LastName}", model.Email, model.Username, model.Password, department.DepartmentId); var loginResult = await _signInManager.PasswordSignInAsync(model.Username, model.Password, true, lockoutOnFailure : false); if (loginResult.Succeeded) { await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, HttpContext.User, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(24), IsPersistent = false, AllowRefresh = false }); if (!String.IsNullOrWhiteSpace(returnUrl)) { return(RedirectToLocal(returnUrl)); } else { return(RedirectToAction("Dashboard", "Home", new { Area = "User" })); } } else { return(View(model)); } } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> EditUserProfile(EditProfileModel model, IFormCollection form, CancellationToken cancellationToken) { if (!await _authorizationService.CanUserEditProfileAsync(UserId, DepartmentId, model.UserId)) { Unauthorized(); } model.User = _usersService.GetUserById(model.UserId); //model.PushUris = await _pushUriService.GetPushUrisByUserId(model.UserId); model.Department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId); model.CanEnableVoice = await _limitsService.CanDepartmentUseVoiceAsync(DepartmentId); var groups = new List <DepartmentGroup>(); var defaultGroup = new DepartmentGroup(); defaultGroup.Name = "No Group"; groups.Add(defaultGroup); groups.AddRange(await _departmentGroupsService.GetAllGroupsForDepartmentAsync(model.Department.DepartmentId)); model.Groups = new SelectList(groups, "DepartmentGroupId", "Name"); ViewBag.Carriers = model.Carrier.ToSelectList(); ViewBag.Countries = new SelectList(Countries.CountryNames); ViewBag.TimeZones = new SelectList(TimeZones.Zones, "Key", "Value"); if (!String.IsNullOrEmpty(model.Profile.MobileNumber)) { if (model.Carrier == MobileCarriers.None) { ModelState.AddModelError("Carrier", "If you entered a mobile phone, you need to select your mobile carrier. If you carrier is not listed select one and contact us to have your carrier added."); } else { if (model.Carrier == MobileCarriers.VirginMobileUk && !model.Profile.MobileNumber.StartsWith("0")) { ModelState.AddModelError("Profile.MobileNumber", "Virgin Mobile Uk requires your phone number to start with 0."); } if (model.Carrier == MobileCarriers.O2 && !model.Profile.MobileNumber.StartsWith("44")) { ModelState.AddModelError("Profile.MobileNumber", "O2 requires your phone number to start with 44."); } if (model.Carrier == MobileCarriers.Orange && !model.Profile.MobileNumber.StartsWith("0")) { ModelState.AddModelError("Profile.MobileNumber", "Orange requires your phone number to start with 0."); } if (model.Carrier == MobileCarriers.TMobileUk && !model.Profile.MobileNumber.StartsWith("0")) { ModelState.AddModelError("Profile.MobileNumber", "T-Mobile Uk requires your phone number to start with 0."); } if (model.Carrier == MobileCarriers.Vodafone && !model.Profile.MobileNumber.StartsWith("0")) { ModelState.AddModelError("Profile.MobileNumber", "Vodafone requires your phone number to start with 0."); } } } if ((model.Profile.SendSms || model.Profile.SendMessageSms || model.Profile.SendMessageSms) && String.IsNullOrEmpty(model.Profile.MobileNumber)) { ModelState.AddModelError("Profile.MobileNumber", "You have selected you want SMS/Text notifications but have not supplied a mobile number."); } // They specified a street address for physical if (!String.IsNullOrWhiteSpace(model.PhysicalAddress1)) { if (String.IsNullOrEmpty(model.PhysicalCity)) { ModelState.AddModelError("City", string.Format("The Physical City field is required")); } if (String.IsNullOrEmpty(model.PhysicalCountry)) { ModelState.AddModelError("Country", string.Format("The Physical Country field is required")); } if (String.IsNullOrEmpty(model.PhysicalPostalCode)) { ModelState.AddModelError("PostalCode", string.Format("The Physical Postal Code field is required")); } if (String.IsNullOrEmpty(model.PhysicalState)) { ModelState.AddModelError("State", string.Format("The Physical State/Provence field is required")); } } if (!String.IsNullOrWhiteSpace(model.MailingAddress1) && !model.MailingAddressSameAsPhysical) { if (String.IsNullOrEmpty(model.MailingCity)) { ModelState.AddModelError("City", string.Format("The Mailing City field is required")); } if (String.IsNullOrEmpty(model.MailingCountry)) { ModelState.AddModelError("Country", string.Format("The Mailing Country field is required")); } if (String.IsNullOrEmpty(model.MailingPostalCode)) { ModelState.AddModelError("PostalCode", string.Format("The Mailing Postal Code field is required")); } if (String.IsNullOrEmpty(model.MailingState)) { ModelState.AddModelError("State", string.Format("The Mailing State/Provence field is required")); } } if (model.User.Email != model.Email) { var currentEmail = _usersService.GetUserByEmail(model.Email); if (currentEmail != null && currentEmail.Id != model.User.UserId.ToString()) { ModelState.AddModelError("Email", "Email Address Already in Use. Please use another one."); } } if (model.Profile.VoiceForCall) { if (model.Profile.VoiceCallHome && String.IsNullOrWhiteSpace(model.Profile.HomeNumber)) { ModelState.AddModelError("VoiceForCall", "You selected to Enable Telephone alerting for your home phone number but have not supplied a home phone number. Please supply one."); } if (model.Profile.VoiceCallMobile && String.IsNullOrWhiteSpace(model.Profile.MobileNumber)) { ModelState.AddModelError("VoiceForCall", "You selected to Enable Telephone alerting for your mobile phone number but have not supplied a mobile phone number. Please supply one."); } if (!model.Profile.VoiceCallHome && !model.Profile.VoiceCallMobile) { ModelState.AddModelError("VoiceForCall", "You selected to Enable Telephone alerting, but you didn't select a number to call you at. Please select either/both home phone or mobile phone."); } } if (model.IsOwnProfile) { bool checkPasswordSuccess = false; if (string.IsNullOrEmpty(model.OldPassword) == false && string.IsNullOrEmpty(model.NewPassword) == false) { try { checkPasswordSuccess = await _userManager.CheckPasswordAsync(model.User, model.OldPassword); } catch (Exception) { checkPasswordSuccess = false; } if (!checkPasswordSuccess) { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } if (!String.IsNullOrWhiteSpace(model.NewUsername)) { var newUser = await _userManager.FindByNameAsync(model.NewUsername); if (newUser != null) { ModelState.AddModelError("", "The NEW username you have supplied is already in use, please try another one. If you didn't mean to update your username please leave that field blank."); } } } if (ModelState.IsValid) { Address homeAddress = null; Address mailingAddress = null; var auditEvent = new AuditEvent(); auditEvent.DepartmentId = DepartmentId; auditEvent.UserId = UserId; auditEvent.Type = AuditLogTypes.ProfileUpdated; var savedProfile = await _userProfileService.GetProfileByUserIdAsync(model.UserId); if (savedProfile == null) { savedProfile = new UserProfile(); } auditEvent.Before = savedProfile.CloneJson(); savedProfile.UserId = model.UserId; savedProfile.MobileCarrier = (int)model.Carrier; savedProfile.FirstName = model.FirstName; savedProfile.LastName = model.LastName; savedProfile.MobileNumber = model.Profile.MobileNumber; savedProfile.SendEmail = model.Profile.SendEmail; savedProfile.SendPush = model.Profile.SendPush; savedProfile.SendSms = model.Profile.SendSms; savedProfile.SendMessageEmail = model.Profile.SendMessageEmail; savedProfile.SendMessagePush = model.Profile.SendMessagePush; savedProfile.SendMessageSms = model.Profile.SendMessageSms; savedProfile.SendNotificationEmail = model.Profile.SendNotificationEmail; savedProfile.SendNotificationPush = model.Profile.SendNotificationPush; savedProfile.SendNotificationSms = model.Profile.SendNotificationSms; savedProfile.DoNotRecieveNewsletters = model.Profile.DoNotRecieveNewsletters; savedProfile.HomeNumber = model.Profile.HomeNumber; savedProfile.IdentificationNumber = model.Profile.IdentificationNumber; savedProfile.TimeZone = model.Profile.TimeZone; if (model.CanEnableVoice) { savedProfile.VoiceForCall = model.Profile.VoiceForCall; if (savedProfile.VoiceForCall) { savedProfile.VoiceCallHome = model.Profile.VoiceCallHome; savedProfile.VoiceCallMobile = model.Profile.VoiceCallMobile; } else { savedProfile.VoiceCallHome = false; savedProfile.VoiceCallMobile = false; } } else { savedProfile.VoiceForCall = false; savedProfile.VoiceCallHome = false; savedProfile.VoiceCallMobile = false; } if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin()) { var currentGroup = await _departmentGroupsService.GetGroupForUserAsync(model.UserId, DepartmentId); if (model.UserGroup != 0 && (currentGroup == null || currentGroup.DepartmentGroupId != model.UserGroup)) { await _departmentGroupsService.MoveUserIntoGroupAsync(model.UserId, model.UserGroup, model.IsUserGroupAdmin, DepartmentId, cancellationToken); } else if (currentGroup != null && currentGroup.DepartmentGroupId == model.UserGroup) { var member = await _departmentGroupsService.GetGroupMemberForUserAsync(model.UserId, DepartmentId); if (member != null) { member.IsAdmin = model.IsUserGroupAdmin; _departmentGroupsService.SaveGroupMember(member); } } else if (model.UserGroup <= 0) { await _departmentGroupsService.DeleteUserFromGroupsAsync(model.UserId, DepartmentId, cancellationToken); } } if (form.ContainsKey("roles")) { var roles = form["roles"].ToString().Split(char.Parse(",")); if (roles.Any()) { await _personnelRolesService.SetRolesForUserAsync(DepartmentId, model.UserId, roles, cancellationToken); } } if (savedProfile.HomeAddressId.HasValue) { homeAddress = await _addressService.GetAddressByIdAsync(savedProfile.HomeAddressId.Value); } if (savedProfile.MailingAddressId.HasValue) { mailingAddress = await _addressService.GetAddressByIdAsync(savedProfile.MailingAddressId.Value); } if (!model.MailingAddressSameAsPhysical && homeAddress != null && mailingAddress != null && (homeAddress.AddressId == mailingAddress.AddressId)) { mailingAddress = new Address(); } if (!String.IsNullOrWhiteSpace(model.PhysicalAddress1)) { if (homeAddress == null) { homeAddress = new Address(); } homeAddress.Address1 = model.PhysicalAddress1; homeAddress.City = model.PhysicalCity; homeAddress.Country = model.PhysicalCountry; homeAddress.PostalCode = model.PhysicalPostalCode; homeAddress.State = model.PhysicalState; homeAddress = await _addressService.SaveAddressAsync(homeAddress, cancellationToken); savedProfile.HomeAddressId = homeAddress.AddressId; if (model.MailingAddressSameAsPhysical) { savedProfile.MailingAddressId = homeAddress.AddressId; } } if (!String.IsNullOrWhiteSpace(model.MailingAddress1) && !model.MailingAddressSameAsPhysical) { if (mailingAddress == null) { mailingAddress = new Address(); } mailingAddress.Address1 = model.MailingAddress1; mailingAddress.City = model.MailingCity; mailingAddress.Country = model.MailingCountry; mailingAddress.PostalCode = model.MailingPostalCode; mailingAddress.State = model.MailingState; mailingAddress = await _addressService.SaveAddressAsync(mailingAddress, cancellationToken); savedProfile.MailingAddressId = mailingAddress.AddressId; } savedProfile.LastUpdated = DateTime.UtcNow; await _userProfileService.SaveProfileAsync(DepartmentId, savedProfile, cancellationToken); auditEvent.After = savedProfile.CloneJson(); _eventAggregator.SendMessage <AuditEvent>(auditEvent); var depMember = await _departmentsService.GetDepartmentMemberAsync(model.UserId, DepartmentId); if (depMember != null) { // Users Department Admin status changes, invalid the department object in cache. if (model.IsDepartmentAdmin != depMember.IsAdmin) { _departmentsService.InvalidateDepartmentInCache(depMember.DepartmentId); } depMember.IsAdmin = model.IsDepartmentAdmin; depMember.IsDisabled = model.IsDisabled; depMember.IsHidden = model.IsHidden; await _departmentsService.SaveDepartmentMemberAsync(depMember, cancellationToken); } if (!model.Profile.DoNotRecieveNewsletters) { Unsubscribe(model.Email); } //var membershipUser = Membership.GetUser(model.UserId); //membershipUser.Email = model.Email; //Membership.UpdateUser(membershipUser); _usersService.UpdateEmail(model.User.Id, model.Email); if (model.IsOwnProfile) { // Change Password if (!string.IsNullOrEmpty(model.OldPassword) && !string.IsNullOrEmpty(model.NewPassword)) { var identityUser = await _userManager.FindByIdAsync(model.User.Id); var result = await _userManager.ChangePasswordAsync(identityUser, model.OldPassword, model.NewPassword); } if (!string.IsNullOrWhiteSpace(model.NewUsername)) { _usersService.UpdateUsername(model.User.UserName, model.NewUsername); } } _userProfileService.ClearUserProfileFromCache(model.UserId); _userProfileService.ClearAllUserProfilesFromCache(model.Department.DepartmentId); _departmentsService.InvalidateDepartmentUsersInCache(model.Department.DepartmentId); _departmentsService.InvalidatePersonnelNamesInCache(DepartmentId); _departmentsService.InvalidateDepartmentMembers(); _usersService.ClearCacheForDepartment(DepartmentId); return(RedirectToAction("Index", "Personnel", new { area = "User" })); } // If we got this far, something failed, redisplay form return(View(model)); }