public UserAccountInfoViewModel(TicketDeskUser user, IEnumerable<string> roles) { var lockDate = (user.LockoutEndDateUtc ?? DateTime.MinValue).ToUniversalTime(); User = user; IsLocked = lockDate > DateTime.UtcNow && lockDate < DateTime.MaxValue.ToUniversalTime(); IsDisabled = lockDate == DateTime.MaxValue.ToUniversalTime(); Roles = roles ?? new string[] {}; }
/// <summary> /// Migrates the users and roles from a legacy database to the new TD 2.5 schema. /// </summary> /// <param name="context">The identity database context</param> /// <param name="userManager">The user manager.</param> /// <param name="roleManager">The role manager.</param> /// <returns><c>true</c> if users migrated, <c>false</c> otherwise.</returns> public static bool MigrateSecurity(TdIdentityContext context, TicketDeskUserManager userManager, TicketDeskRoleManager roleManager) { roleManager.EnsureDefaultRolesExist(); var appId = context.Database.SqlQuery<Guid>( "select ApplicationId from aspnet_Applications where ApplicationName = 'TicketDesk'").First().ToString(); var users = context.Database.SqlQuery<LegacyUser>( "select UserId, Email, Password, PasswordFormat, Comment from aspnet_Membership where ApplicationId = '" + appId + "' and IsApproved = 1 and IsLockedOut = 0").ToList(); const string roleQuery = "SELECT r.RoleName FROM aspnet_UsersInRoles u inner join aspnet_Roles r on u.RoleId = r.RoleId WHERE u.UserId = @userId and r.ApplicationId = @appId"; foreach (var user in users) { var newUser = new TicketDeskUser { UserName = user.Email, Email = user.Email, DisplayName = user.Comment, }; var result = user.PasswordFormat == 0 ? userManager.Create(newUser, user.Password) : userManager.Create(newUser); if (result.Succeeded) { var rolesForUser = context.Database.SqlQuery<string>(roleQuery, new SqlParameter("userId", user.UserId), new SqlParameter("appId", appId)); var newRoles = new List<string>(); foreach (var role in rolesForUser) { switch (role.ToLowerInvariant()) { case "administrators": newRoles.Add("TdAdministrators"); break; case "helpdesk": newRoles.Add("TdHelpDeskUsers"); break; case "ticketsubmitters": newRoles.Add("TdInternalUsers"); break; default: newRoles.Add("TdPendingUsers"); break; } } userManager.AddToRoles(newUser.Id, newRoles.ToArray()); } } return true; }
public async Task<ActionResult> Register(UserRegisterViewModel model) { if (ModelState.IsValid) { var user = new TicketDeskUser { UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); await UserManager.AddToRolesAsync(user.Id, DomainContext.TicketDeskSettings.SecuritySettings.DefaultNewUserRoles.ToArray()); HostingEnvironment.QueueBackgroundWorkItem(ct => { using ( var notificationContext = DependencyResolver.Current.GetService<TdPushNotificationContext>() ) { notificationContext.SubscriberPushNotificationSettingsManager.AddSettingsForSubscriber( new SubscriberNotificationSetting { SubscriberId = user.Id, IsEnabled = true, PushNotificationDestinations = new[] { new PushNotificationDestination() { DestinationType = "email", DestinationAddress = user.Email, SubscriberName = user.DisplayName } } }); notificationContext.SaveChanges(); } }); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
public static void SetupDemoIdentityData(TdIdentityContext context) { var userStore = new UserStore<TicketDeskUser>(context); var roleStore = new RoleStore<TicketDeskRole>(context); var userManager = new TicketDeskUserManager(userStore); var roleManager = new TicketDeskRoleManager(roleStore); roleManager.EnsureDefaultRolesExist(); var admin = new TicketDeskUser { Id = "64165817-9cb5-472f-8bfb-6a35ca54be6a", UserName = "******", Email = "*****@*****.**", DisplayName = "Admin User" }; var staff = new TicketDeskUser { Id = "72bdddfb-805a-4883-94b9-aa494f5f52dc", UserName = "******", Email = "*****@*****.**", DisplayName = "HelpDesk User" }; var reguser = new TicketDeskUser { Id = "17f78f38-fa68-445f-90de-38896140db28", UserName = "******", Email = "*****@*****.**", DisplayName = "Regular User" }; var users = new[] { admin, staff, reguser }; var rolesNames = new Dictionary<string, string[]> { {"*****@*****.**", new[] {"TdAdministrators"}}, {"*****@*****.**", new[] {"TdHelpDeskUsers"}}, {"*****@*****.**", new[] {"TdInternalUsers"}} }; foreach (var tdUser in users) { var user = userManager.FindByName(tdUser.UserName); if (user == null) { user = tdUser; userManager.Create(user, "123456"); } var rnames = rolesNames[user.UserName]; var rolesForUser = userManager.GetRoles(user.Id); foreach (var rname in rnames.Where(rname => !rolesForUser.Contains(rname))) { userManager.AddToRole(user.Id, rname); } } }
private async Task SignInAsync(TicketDeskUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); }
private async Task ResetMailEmailDestination(TicketDeskUser user, string oldEmail) { var noteSettings = await NotificationContext.SubscriberPushNotificationSettingsManager.GetSettingsForSubscriber(user.Id); var dest = noteSettings.PushNotificationDestinations.FirstOrDefault( d => d.DestinationType == "email" && d.DestinationAddress == oldEmail); if (dest == null) { dest = new PushNotificationDestination() {SubscriberId = user.Id, DestinationType = "email"}; noteSettings.PushNotificationDestinations.Add(dest); } dest.DestinationAddress = user.Email; dest.SubscriberName = user.DisplayName; await NotificationContext.SaveChangesAsync(); }
private async Task<bool> SetLockout(UserAccountInfoViewModel model, TicketDeskUser user) { var currentlyLocked = UserManager.IsLockedOut(model.User.Id); var currentlyDisabled = currentlyLocked && (user.LockoutEndDateUtc ?? DateTime.MinValue).ToUniversalTime() == DateTime.MaxValue.ToUniversalTime(); if (currentlyDisabled != model.IsDisabled || currentlyLocked != model.IsLocked) { DateTimeOffset newLockoutDate = DateTimeOffset.MinValue; if (model.IsDisabled) { newLockoutDate = DateTimeOffset.MaxValue; } else if (model.IsLocked) { newLockoutDate = DateTimeOffset.Now.Add(UserManager.DefaultAccountLockoutTimeSpan); } var result = await UserManager.SetLockoutEndDateAsync(model.User.Id, newLockoutDate); if (!result.Succeeded) { AddErrors(result); } return result.Succeeded; } return true; }
private async Task<bool> RemoveRoles(IEnumerable<string> roleIdsToRemove, TicketDeskUser user) { var roleNamesToRemove = RoleManager.Roles.Where(r => roleIdsToRemove.Any(ri => ri == r.Id)).Select(r => r.Name); if (roleNamesToRemove.Any()) { var result = await UserManager.RemoveFromRolesAsync(user.Id, await roleNamesToRemove.ToArrayAsync()); if (!result.Succeeded) { AddErrors(result); } return result.Succeeded; } return true; }
private async Task<bool> UpdateUserInfo(TicketDeskUser user, UserAccountInfoViewModel model) { user.UserName = model.User.Email; user.Email = model.User.Email; user.DisplayName = model.User.DisplayName; var result = await UserManager.UpdateAsync(user); if (!result.Succeeded) { AddErrors(result); } return result.Succeeded; }