public Manager() { // If necessary, add constructor code here // Initialize the UserAccount property UserAccount = new UserAccount(HttpContext.Current.User as ClaimsPrincipal); // Turn off the Entity Framework (EF) proxy creation features // We do NOT want the EF to track changes - we'll do that ourselves ds.Configuration.ProxyCreationEnabled = false; // Also, turn off lazy loading... // We want to retain control over fetching related objects ds.Configuration.LazyLoadingEnabled = false; }
// Delete User public void DeleteUser(string id) { var user = UserManager.FindById(id); // Initialize UserAccount var userIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie) as ClaimsIdentity; var claimsPrincipal = new ClaimsPrincipal(userIdentity); var userAccount = new UserAccount(claimsPrincipal); // Get all claims var claims = claimsPrincipal.Claims; // Set a flag for successful remove var check = true; // Remove all claims from user foreach (var claim in claims) { var r = UserManager.RemoveClaimAsync(user.Id, new Claim(claim.Type, claim.Value)).Result; if (!r.Succeeded) { check = false; } } // Finally remove the user if (check) { var result = UserManager.DeleteAsync(user).Result; } }
// Edit User Claims - For Now Only Roles public ApplicationUserDetail ApplicationUserEdit(ApplicationUserEdit newItem) { var result = new IdentityResult(); // Attempt to fetch the object var o = UserManager.FindById(newItem.Id); if (o == null) { return null; } var userIdentity = UserManager.CreateIdentity(o, DefaultAuthenticationTypes.ApplicationCookie) as ClaimsIdentity; var claimsPrincipal = new ClaimsPrincipal(userIdentity); var userAccount = new UserAccount(claimsPrincipal); // Remove all roles foreach (var role in userAccount.RoleClaims) { result = UserManager.RemoveClaimAsync(o.Id, new Claim(ClaimTypes.Role, role)).Result; } // If successful removal, Add Roles if (result.Succeeded) { foreach (var newRole in newItem.Roles) { result = UserManager.AddClaimAsync(o.Id, new Claim(ClaimTypes.Role, newRole)).Result; } if (result.Succeeded) { return Mapper.Map<ApplicationUserDetail>(newItem); } } return null; }
// Get User by Id public ApplicationUserDetail GetUserById(string id) { // Fetch the User by Id var user = UserManager.FindById(id); if( user == null) { return null; } // Initialize UserAccount var userIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie) as ClaimsIdentity; var claimsPrincipal = new ClaimsPrincipal(userIdentity); var userAccount = new UserAccount(claimsPrincipal); // Map user details var details = Mapper.Map<ApplicationUserDetail>(userAccount); details.UserName = user.UserName; details.Email = user.UserName; details.Roles = userAccount.RoleClaims; return details; }