// delete a user account and all history: comments, posts and votes public static bool DeleteUser(string userName) { using (whoaverseEntities db = new whoaverseEntities()) { using (UserManager<ApplicationUser> tmpUserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { var tmpuser = tmpUserManager.FindByName(userName); if (tmpuser != null) { //remove voting history for submisions db.Votingtrackers.RemoveRange(db.Votingtrackers.Where(x => x.UserName == userName)); //remove voting history for comments db.Commentvotingtrackers.RemoveRange(db.Commentvotingtrackers.Where(x => x.UserName == userName)); //remove all comments var comments = db.Comments.Where(c => c.Name == userName); foreach (Comment c in comments) { c.Name = "deleted"; c.CommentContent = "deleted"; db.SaveChangesAsync(); } //remove all submissions var submissions = db.Messages.Where(c => c.Name == userName); foreach (Message s in submissions) { if (s.Type == 1) { s.Name = "deleted"; s.MessageContent = "deleted"; s.Title = "deleted"; } else { s.Name = "deleted"; s.Linkdescription = "deleted"; s.MessageContent = "http://whoaverse.com"; } } db.SaveChangesAsync(); var result = tmpUserManager.DeleteAsync(tmpuser); return true; } else { return false; } } } }
public async Task RemoveTenantSampleData(MyHealthContext context, UserManager<ApplicationUser> userManager, int tenantId) { if (context.Tenants.Any(t => t.TenantId == tenantId)) { context.HomeAppointments.RemoveRange(context.HomeAppointments.Where(t => t.TenantId == tenantId)); context.ClinicAppointments.RemoveRange(context.ClinicAppointments.Where(t => t.TenantId == tenantId)); context.Medicines.RemoveRange(context.Medicines.Where(t => t.TenantId == tenantId)); var usersToDelete = context.Users.Where(t => t.TenantId == tenantId).ToList(); foreach (var user in usersToDelete) await userManager.DeleteAsync(user); context.Tenants.Remove(context.Tenants.FirstOrDefault(t => t.TenantId == tenantId)); await context.SaveChangesAsync(); } }
public void DeleteUserByID(string userID) { try { var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context1)); var userToDelete = userMgr.FindById(userID); userMgr.DeleteAsync(userToDelete); } catch (OptimisticConcurrencyException ocex) { throw ocex; } catch (ArgumentNullException argex) { throw argex; } catch (Exception ex) { throw ex; } }
public Boolean delete() { //delete from user table String deleteUserID = Request.Params["id"]; int id = int.Parse(deleteUserID); IRepository<User> repository = new UserRepository(); User deletedUser = repository.findById(id); if (deletedUser == null) { return false; } repository.Delete(deletedUser); //delete from asp.netUser table var context = new NetCafeWeb.Models.ApplicationDbContext(); var UserManager = new UserManager<NetCafeWeb.Models.ApplicationUser>(new UserStore<NetCafeWeb.Models.ApplicationUser>(context)); ApplicationUser aspSelectedUser = context.Users.Where(u => u.UserName.Equals((deletedUser.UserName), StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); UserManager.DeleteAsync(aspSelectedUser); return true; }
public virtual async Task <IdentityResult> DeleteUserAsync(string userId) { var userIdentity = await UserManager.FindByIdAsync(userId); return(await UserManager.DeleteAsync(userIdentity)); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); InputLogin = new InputModelLogin(); InputRegister = new InputModelRegister(); // Username and password from phone number InputLogin.Username = InputModel.PhoneNumber; InputLogin.Password = InputModel.PhoneNumber; InputRegister.UserName = InputModel.PhoneNumber; InputRegister.Password = InputModel.PhoneNumber; InputRegister.FullPhoneNumber = InputModel.PhoneNumber; // try login if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(InputLogin.Username, InputLogin.Password, false, lockoutOnFailure : true); if (result.Succeeded) { // try verify var user = new ApplicationUser { UserName = InputRegister.UserName, PhoneNumber = InputRegister.FullPhoneNumber }; HttpContext.Session.SetString("_UserId", user.Id); await _signInManager.PasswordSignInAsync(InputRegister.UserName, InputRegister.Password, false, lockoutOnFailure : true); return(LocalRedirect(Url.Content($"~/Identity/Account/Verify/?phoneNumber={user.PhoneNumber}&returnUrl={returnUrl}"))); return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { return(RedirectToPage("./Lockout")); } // try register var userRegister = new ApplicationUser { UserName = InputRegister.UserName, PhoneNumber = InputRegister.FullPhoneNumber }; var resultRegister = await _userManager.CreateAsync(userRegister, InputRegister.Password); if (resultRegister.Succeeded) { HttpContext.Session.SetString("_UserId", userRegister.Id); await _signInManager.PasswordSignInAsync(InputRegister.UserName, InputRegister.Password, false, lockoutOnFailure : true); return(LocalRedirect(Url.Content($"~/Identity/Account/Verify/?phoneNumber={userRegister.PhoneNumber}&returnUrl={returnUrl}"))); await _userManager.DeleteAsync(userRegister); } foreach (var error in resultRegister.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <(bool Succeeded, string[] Errors)> DeleteUserAsync(AppUser user) { var result = await _userManager.DeleteAsync(user); return(result.Succeeded, result.Errors.Select(e => e.Description).ToArray()); }
public async Task<bool> Delete(Guid id) { return (await _um.DeleteAsync(await _um.FindByIdAsync(id.ToString()))).Succeeded; }
public async Task <Result> DeleteUserAsync(ApplicationUser user) { var result = await _userManager.DeleteAsync(user); return(result.ToApplicationResult()); }
public async Task<ActionResult> DeleteAccount() { // get the user to delete from the claims principle. var user = await _userManager.FindByNameAsync(User.GetUsername()); // 1. Delete all their photos var photos = await _unitOfWork.PhotoRepository.GetUsersPhotos(user.UserName); if (photos.Count() > 0) { foreach (var photo in photos) { // remove from cloudinary if (photo.PublicId != null) { var r = await _photoService.DeletePhotoAsync(photo.PublicId); if (r.Error != null) return BadRequest(r.Error.Message); } // tell EF to track for removal from db user.Photos.Remove(photo); } } // 2. Delete all messages that are connected to them var allMessages = await _unitOfWork.MessageRepository.GetAllUsersMessages(user.UserName); if (allMessages.Count() > 0) { // no need to check if sender deleted or recipient deleted here. Just delete it no matter what. // TODO: in the future see if you can keep the message history, like facebook does with deleted/deactivated profiles. For now, delete the entire profile and all messages. _unitOfWork.MessageRepository.DeleteMessages(allMessages); } // 3. Delete their message groups and any remaining connections on that group (should remove automatically when they leave a hub) // but in case there are any existing hubs with this username and connection. var groups = await _unitOfWork.MessageRepository.GetMessageGroupsByUsername(user.UserName); if (groups.Count() > 0) { // Delete connections associated with the group (revisit this) foreach (var group in groups) { var connection = group.Connections.FirstOrDefault(); if (connection != null) { _unitOfWork.MessageRepository.RemoveConnection(connection); } } // after deleting connections associated with the username, delete the message groups. _unitOfWork.MessageRepository.DeleteMessageGroups(groups); } // 4. Now, use ASPNET Identity. Delete their roles. var userRoles = await _userManager.GetRolesAsync(user); if (userRoles.Count() > 0) { // Then remove the user from all roles. var deleteRolesResult = await _userManager.RemoveFromRolesAsync(user, userRoles); if (!deleteRolesResult.Succeeded) return BadRequest("Encountered an error while trying to delete your account."); } // 5...and finally delete the user. var result = await _userManager.DeleteAsync(user); // ASPNET identity takes care of saving the db changes for us // if it didn't succeed, return bad request if (!result.Succeeded) return BadRequest("Encountered an error while trying to delete your account."); // check if _unitOfWork has changes (other than ASPNET Identity) if (_unitOfWork.HasChanges()) { // save if the changes exist if (await _unitOfWork.Complete()) return Ok(); // if issues with this, return bad request return BadRequest("Encountered an error while trying to delete your account."); } // if we make it here, no EF changes were made. Delete was successful. return Ok(); }
public async Task <IdentityResult> DeleteUserAsync(AppUser entity) { return(await _userManager.DeleteAsync(entity)); }
public async Task DeleteUser(ApplicationIdentityUser user) { await _userManager.DeleteAsync(user); }
public async Task <IdentityResult> DeleteUser(RelationalDatabase.DBEntities.User user) { var result = await _userManager.DeleteAsync(user); return(result); }
async public Task <IActionResult> SeedUsers() { var allUsers = userManager.Users.ToList(); foreach (var x in allUsers) { await userManager.DeleteAsync(x); } ApplicationUser adam = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; ApplicationUser viktor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; ApplicationUser susan = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; ApplicationUser peter = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; ApplicationUser xerxes = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; await userManager.CreateAsync(adam); await userManager.AddClaimAsync(adam, new System.Security.Claims.Claim("role", "administrator")); await userManager.CreateAsync(viktor); await userManager.AddClaimAsync(viktor, new System.Security.Claims.Claim("role", "subscriber")); await userManager.AddClaimAsync(viktor, new System.Security.Claims.Claim("age", "15")); await userManager.CreateAsync(susan); await userManager.AddClaimAsync(susan, new System.Security.Claims.Claim("role", "subscriber")); await userManager.AddClaimAsync(susan, new System.Security.Claims.Claim("age", "48")); await userManager.CreateAsync(peter); await userManager.AddClaimAsync(peter, new System.Security.Claims.Claim("role", "publisher")); await userManager.CreateAsync(xerxes); //await userManager.AddClaimAsync(xerxes, new System.Security.Claims.Claim("role", "administrator")); //List<ApplicationUser> userList = new List<ApplicationUser>() //{ // new ApplicationUser {UserName="******", Email="*****@*****.**"}, // new ApplicationUser {UserName="******", Email="*****@*****.**"}, // new ApplicationUser {UserName="******", Email="*****@*****.**"}, // new ApplicationUser {UserName="******", Email="*****@*****.**"}, // new ApplicationUser {UserName="******", Email="*****@*****.**"} //}; //foreach (ApplicationUser applicationUser in userList) //{ // await userManager.CreateAsync(applicationUser); //} // Skapa användare med userManager... return(Ok()); /* * foreach (ApplicationUser applicationUser in databaseContext.Users) * { * databaseContext.Remove(applicationUser); * } * * List<ApplicationUser> userList = new List<ApplicationUser>() * { * new ApplicationUser {UserName="******", Email="*****@*****.**"}, * new ApplicationUser {UserName="******", Email="*****@*****.**"}, * new ApplicationUser {UserName="******", Email="*****@*****.**"}, * new ApplicationUser {UserName="******", Email="*****@*****.**"}, * new ApplicationUser {UserName="******", Email="*****@*****.**"} * }; * foreach (ApplicationUser applicationUser in userList) * { * databaseContext.Add(applicationUser); * } * databaseContext.SaveChanges(); * return Ok("hej"); */ }
//delete employee public void DeleteEmployee(string email) { var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = manager.FindByEmail(email); if (user != null) { DeleteAllEmployeeShifts(email); manager.DeleteAsync(user); }; UserManagerExtensions.Delete(manager, user); _repo.SaveChanges(); }
public async Task <IdentityResult> DeleteUserAsync(string userId) { ApplicationUser user = await _userManager.FindByIdAsync(userId); return(await _userManager.DeleteAsync(user)); }
public async Task <IActionResult> Register([FromBody] RegisterViewModel model, int version) { if (version == 2) { return(Response(new { Message = "API V2 não disponível" })); } var userEF = await _userManager.FindByEmailAsync(model.Email); if (userEF != null && !string.IsNullOrEmpty(userEF.Email)) { return(Response_BadRequest("Já existe usuário cadastrado com o email informado.")); } if (model.FuncionarioId <= 0 && model.ProfissionalId <= 0) { return(Response_BadRequest("O ID do funcionário ou o ID do profisssional deve ser informado.")); } if (model.FuncionarioId > 0 && model.ProfissionalId > 0) { return(Response_BadRequest("O ID do funcionário e o ID do profisssional não podem ser informados ao mesmo tempo.")); } if (!ModelState.IsValid) { NotifyErrorInvalidModel(); return(Response()); } userEF = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(userEF, model.Senha); if (result.Succeeded) { await _userManager.AddClaimAsync(userEF, new Claim("Tipos", "Ler")); try { var registerCommand = new RegisterAppUserCommand(Guid.Parse(userEF.Id), userEF.Email); await _mediator.SendCommand(registerCommand); if (!InvalidOperation()) { await _userManager.DeleteAsync(userEF); return(Response(model)); } var usuarioCore_Api = _appUserRepository.GetById(Guid.Parse(userEF.Id)); if (usuarioCore_Api == null || usuarioCore_Api.Id != Guid.Parse(userEF.Id)) { await _userManager.DeleteAsync(userEF); throw new Exception("Couldn't create the user."); } _logger.LogInformation(1, "Sucess!"); var response = new { Message = "Sucess!", NovoUserID = userEF.Id }; return(Response(response)); } catch (Exception exc1) { _appUserRepository.Remove(Guid.Parse(userEF.Id)); await _userManager.DeleteAsync(userEF); var response = new { Message = "Couldn't create the user: " + exc1.Message }; //_bugsnag.Notify(new Exception(exc1.Message)); return(Response(response)); } } AddIdentityErrors(result); return(Response(model)); }
public async Task MergeAccounts(string sourceId, string targetId, bool eraseContent) { var sourceAccount = (await Records()).First(item => item.Id == sourceId); var targetAccount = (await Records()).First(item => item.Id == targetId); var updateTasks = new List <Task>(); var pSourceId = new SqlParameter("@SourceId", sourceId); var pTargetId = new SqlParameter("@TargetId", targetId); if (eraseContent) { updateTasks.AddRange(new List <Task> { DbContext.Database.ExecuteSqlCommandAsync($"DELETE FROM [{nameof(ApplicationDbContext.Notifications)}] WHERE {nameof(DataModels.Notification.UserId)} = @SourceId", pSourceId), DbContext.Database.ExecuteSqlCommandAsync($"DELETE FROM [{nameof(ApplicationDbContext.Participants)}] WHERE {nameof(DataModels.Participant.UserId)} = @SourceId", pSourceId), DbContext.Database.ExecuteSqlCommandAsync($"DELETE FROM [{nameof(ApplicationDbContext.Bookmarks)}] WHERE {nameof(DataModels.Bookmark.UserId)} = @SourceId", pSourceId), DbContext.Database.ExecuteSqlCommandAsync($"DELETE FROM [{nameof(ApplicationDbContext.ViewLogs)}] WHERE {nameof(DataModels.ViewLog.UserId)} = @SourceId", pSourceId), DbContext.Database.ExecuteSqlCommandAsync($"DELETE FROM [{nameof(ApplicationDbContext.Quotes)}] WHERE {nameof(DataModels.Quote.PostedById)} = @SourceId", pSourceId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Messages)}] SET {nameof(DataModels.Message.EditedById)} = @TargetId WHERE {nameof(DataModels.Message.EditedById)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Messages)}] SET {nameof(DataModels.Message.LastReplyById)} = @TargetId WHERE {nameof(DataModels.Message.LastReplyById)} = @SourceId", pSourceId, pTargetId), }); updateTasks.Add(DbContext.Database.ExecuteSqlCommandAsync($@" UPDATE [{nameof(ApplicationDbContext.Messages)}] SET {nameof(DataModels.Message.PostedById)} = @TargetId, {nameof(DataModels.Message.OriginalBody)} = '', {nameof(DataModels.Message.DisplayBody)} = 'This account has been deleted.', {nameof(DataModels.Message.LongPreview)} = '', {nameof(DataModels.Message.ShortPreview)} = '', {nameof(DataModels.Message.Cards)} = '' WHERE {nameof(DataModels.Message.PostedById)} = @SourceId" , pSourceId, pTargetId)); } else { updateTasks.AddRange(new List <Task> { DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Notifications)}] SET {nameof(DataModels.Notification.UserId)} = @TargetId WHERE {nameof(DataModels.Notification.UserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Participants)}] SET {nameof(DataModels.Participant.UserId)} = @TargetId WHERE {nameof(DataModels.Participant.UserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Bookmarks)}] SET {nameof(DataModels.Bookmark.UserId)} = @TargetId WHERE {nameof(DataModels.Bookmark.UserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.ViewLogs)}] SET {nameof(DataModels.ViewLog.UserId)} = @TargetId WHERE {nameof(DataModels.ViewLog.UserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Quotes)}] SET {nameof(DataModels.Quote.PostedById)} = @TargetId WHERE {nameof(DataModels.Quote.PostedById)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Messages)}] SET {nameof(DataModels.Message.PostedById)} = @TargetId WHERE {nameof(DataModels.Message.PostedById)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Messages)}] SET {nameof(DataModels.Message.EditedById)} = @TargetId WHERE {nameof(DataModels.Message.EditedById)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Messages)}] SET {nameof(DataModels.Message.LastReplyById)} = @TargetId WHERE {nameof(DataModels.Message.LastReplyById)} = @SourceId", pSourceId, pTargetId), }); } updateTasks.AddRange(new List <Task> { DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.MessageBoards)}] SET {nameof(DataModels.MessageBoard.UserId)} = @TargetId WHERE {nameof(DataModels.MessageBoard.UserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.MessageThoughts)}] SET {nameof(DataModels.MessageThought.UserId)} = @TargetId WHERE {nameof(DataModels.MessageThought.UserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Notifications)}] SET {nameof(DataModels.Notification.TargetUserId)} = @TargetId WHERE {nameof(DataModels.Notification.TargetUserId)} = @SourceId", pSourceId, pTargetId), DbContext.Database.ExecuteSqlCommandAsync($"UPDATE [{nameof(ApplicationDbContext.Quotes)}] SET {nameof(DataModels.Quote.SubmittedById)} = @TargetId WHERE {nameof(DataModels.Quote.SubmittedById)} = @SourceId", pSourceId, pTargetId), }); Task.WaitAll(updateTasks.ToArray()); DbContext.SaveChanges(); await UserManager.DeleteAsync(sourceAccount); DbContext.SaveChanges(); }
public async Task <IdentityResult> RemoveAsync(ApplicationUser user) { return(await _userManager.DeleteAsync(user)); }
public async Task MudarRole(string email, string cargo, string status, string senha) { var user2 = await _userManager.FindByEmailAsync(funcionarioAdd.Email); if (funcionarioAdd.Email != email && user2 != null) { var user = await _userManager.FindByEmailAsync(funcionarioAdd.Email); user.Email = email; user.UserName = email; await _userManager.UpdateAsync(user); string cargo1 = ""; if (funcionarioAdd.Cargo != cargo) { var applicationRole = await _roleManager.FindByNameAsync(funcionarioAdd.Cargo); await _userManager.RemoveFromRoleAsync(user, applicationRole.Name); var applicationRole1 = await _roleManager.FindByNameAsync(cargo); if (applicationRole1 != null) { await _userManager.AddToRoleAsync(user, applicationRole1.Name); } cargo1 = cargo; } else { cargo1 = funcionarioAdd.Cargo; } if (funcionarioAdd.Status == "Ativo" && status == "Inativo") { var user1 = await _userManager.FindByNameAsync(email); var applicationRole = await _roleManager.FindByNameAsync(cargo1); await _userManager.RemoveFromRoleAsync(user, applicationRole.Name); await _userManager.DeleteAsync(user); } else if (funcionarioAdd.Status == "Inativo" && status == "Ativo") { var user1 = new IdentityUser { UserName = email, Email = email }; if (user1 == null) { var result = await _userManager.CreateAsync(user, senha); var applicationRole = await _roleManager.FindByNameAsync(cargo1); if (applicationRole != null) { await _userManager.AddToRoleAsync(user1, applicationRole.Name); } } } } else if (funcionarioAdd.Cargo != cargo) { var user = await _userManager.FindByNameAsync(funcionarioAdd.Email); if (user != null) { var applicationRole = await _roleManager.FindByNameAsync(funcionarioAdd.Cargo); await _userManager.RemoveFromRoleAsync(user, applicationRole.Name); var applicationRole1 = await _roleManager.FindByNameAsync(cargo); if (applicationRole1 != null) { await _userManager.AddToRoleAsync(user, applicationRole1.Name); } } } else { if (funcionarioAdd.Status == "Ativo" && status == "Inativo") { var user = await _userManager.FindByNameAsync(funcionarioAdd.Email); var applicationRole = await _roleManager.FindByNameAsync(funcionarioAdd.Cargo); await _userManager.RemoveFromRoleAsync(user, applicationRole.Name); await _userManager.DeleteAsync(user); } else if (funcionarioAdd.Status == "Inativo" && status == "Ativo") { var user = new IdentityUser { UserName = email, Email = email }; await _userManager.CreateAsync(user, senha); var applicationRole = await _roleManager.FindByNameAsync(cargo); if (applicationRole != null) { await _userManager.AddToRoleAsync(user, applicationRole.Name); } } } }
/// <summary> /// Deletes the user by cascading the associated data /// </summary> /// <param name="userId">User Id</param> /// <returns>Task</returns> public async Task RemoveUser(string userId) { await userManager.DeleteAsync(userManager.FindById(userId)); }
public async Task DeleteAsync(string id) { var user = await _userManager.FindByIdAsync(id); await _userManager.DeleteAsync(user); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { var claim = new System.Security.Claims.Claim("Nome", Input.Cliente.Nome); await _userManager.AddClaimAsync(user, claim); await _userManager.AddToRoleAsync(user, "cliente"); _logger.LogInformation("User created a new account with password."); try { Clientes novoCliente = new Clientes { Nome = Input.Cliente.Nome, Email = Input.Email, UserNameId = user.Id, Morada = Input.Cliente.Morada, CodPostal = Input.Cliente.CodPostal, Contacto = Input.Cliente.Contacto, NIF = Input.Cliente.NIF }; _context.Add(novoCliente); await _context.SaveChangesAsync(); } catch (Exception) { await _userManager.RemoveFromRoleAsync(user, "cliente"); await _userManager.RemoveClaimAsync(user, claim); await _userManager.DeleteAsync(user); // falta aqui enviar uma mensagem de erro ao utilizador ModelState.AddModelError("Erro", "Não foi possivel efetuar o seu registo."); return(RedirectToAction("Index", "Home")); } if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IUser> CreateAsync(string email, UserValues?values = null, bool lockAutomatically = false, CancellationToken ct = default) { Guard.NotNullOrEmpty(email); var user = userFactory.Create(email); try { var isFirst = !userManager.Users.Any(); await userManager.CreateAsync(user).Throw(log); values ??= new UserValues(); values.Roles ??= new HashSet <string>(); if (string.IsNullOrWhiteSpace(values.DisplayName)) { values.DisplayName = email; } if (isFirst) { values.Roles.Add(NotifoRoles.HostAdmin); } await userManager.SyncClaims(user, values).Throw(log); if (!string.IsNullOrWhiteSpace(values.Password)) { await userManager.AddPasswordAsync(user, values.Password).Throw(log); } foreach (var role in values.Roles) { await userManager.AddToRoleAsync(user, role).Throw(log); } if (!isFirst && lockAutomatically) { await userManager.SetLockoutEndDateAsync(user, LockoutDate()).Throw(log); } } catch (Exception) { try { if (userFactory.IsId(user.Id)) { await userManager.DeleteAsync(user); } } catch (Exception ex2) { log.LogError(ex2, "Failed to cleanup user after creation failed."); } throw; } var resolved = await ResolveAsync(user); foreach (var @events in userEvents) { await @events.OnUserRegisteredAsync(resolved); } if (HasConsentGiven(values, null !)) { foreach (var @events in userEvents) { await @events.OnConsentGivenAsync(resolved); } } return(resolved); }
private async Task <bool> AutoLinkAndSignInExternalAccount(ExternalLoginInfo loginInfo) { //Here we can check if the provider associated with the request has been configured to allow // new users (auto-linked external accounts). This would never be used with public providers such as // Google, unless you for some reason wanted anybody to be able to access the backend if they have a Google account // .... not likely! var authType = OwinContext.Authentication.GetExternalAuthenticationTypes().FirstOrDefault(x => x.AuthenticationType == loginInfo.Login.LoginProvider); if (authType == null) { Logger.Warn <BackOfficeController>("Could not find external authentication provider registered: " + loginInfo.Login.LoginProvider); return(false); } var autoLinkOptions = authType.GetExternalAuthenticationOptions(); if (autoLinkOptions != null) { if (autoLinkOptions.ShouldAutoLinkExternalAccount(UmbracoContext, loginInfo)) { //we are allowing auto-linking/creating of local accounts if (loginInfo.Email.IsNullOrWhiteSpace()) { ViewData[TokenExternalSignInError] = new[] { "The requested provider (" + loginInfo.Login.LoginProvider + ") has not provided an email address, the account cannot be linked." }; } else { //Now we need to perform the auto-link, so first we need to lookup/create a user with the email address var foundByEmail = Services.UserService.GetByEmail(loginInfo.Email); if (foundByEmail != null) { ViewData[TokenExternalSignInError] = new[] { "A user with this email address already exists locally. You will need to login locally to Umbraco and link this external provider: " + loginInfo.Login.LoginProvider }; } else { var defaultUserType = autoLinkOptions.GetDefaultUserType(UmbracoContext, loginInfo); var userType = Services.UserService.GetUserTypeByAlias(defaultUserType); if (userType == null) { ViewData[TokenExternalSignInError] = new[] { "Could not auto-link this account, the specified User Type does not exist: " + defaultUserType }; } else { if (loginInfo.Email.IsNullOrWhiteSpace()) { throw new InvalidOperationException("The Email value cannot be null"); } if (loginInfo.ExternalIdentity.Name.IsNullOrWhiteSpace()) { throw new InvalidOperationException("The Name value cannot be null"); } var autoLinkUser = new BackOfficeIdentityUser() { Email = loginInfo.Email, Name = loginInfo.ExternalIdentity.Name, UserTypeAlias = userType.Alias, AllowedSections = autoLinkOptions.GetDefaultAllowedSections(UmbracoContext, loginInfo), Culture = autoLinkOptions.GetDefaultCulture(UmbracoContext, loginInfo), UserName = loginInfo.Email }; //call the callback if one is assigned if (autoLinkOptions.OnAutoLinking != null) { autoLinkOptions.OnAutoLinking(autoLinkUser, loginInfo); } var userCreationResult = await UserManager.CreateAsync(autoLinkUser); if (userCreationResult.Succeeded == false) { ViewData[TokenExternalSignInError] = userCreationResult.Errors; } else { var linkResult = await UserManager.AddLoginAsync(autoLinkUser.Id, loginInfo.Login); if (linkResult.Succeeded == false) { ViewData[TokenExternalSignInError] = linkResult.Errors; //If this fails, we should really delete the user since it will be in an inconsistent state! var deleteResult = await UserManager.DeleteAsync(autoLinkUser); if (deleteResult.Succeeded == false) { //DOH! ... this isn't good, combine all errors to be shown ViewData[TokenExternalSignInError] = linkResult.Errors.Concat(deleteResult.Errors); } } else { //sign in await SignInManager.SignInAsync(autoLinkUser, isPersistent : false, rememberBrowser : false); } } } } } } return(true); } return(false); }
public async Task <IdentityResult> RemoveAsync(string username, string password) { var result = await _userManager.DeleteAsync(await _userManager.FindAsync(username, password)); return(result); }
public async Task <Tuple <bool, string> > RenewLoanAccountForUser(User userModel) { Tuple <bool, string> identityUserResult = null; IdentityResult identityUser = null; ApplicationUser appUser = null; int isUserInserted = -1; _baseControler = new BaseController(); try { userModel.DcID = "DCUSR" + Helper.GenerateDCID(); appUser = new ApplicationUser { EmailConfirmed = userModel.EmailConfirmed, PasswordHash = userModel.PasswordHash, PhoneNumber = userModel.PhoneNumber == "" ? "" : userModel.PhoneNumber.Trim(), PhoneNumberConfirmed = userModel.PhoneNumberConfirmed, TwoFactorEnabled = userModel.TwoFactorEnabled, LockoutEnabled = userModel.LockoutEnabled, AccessFailedCount = userModel.AccessFailedCount, UserName = userModel.UserName.Trim(), FirstName = userModel.FirstName.Trim(), LastName = userModel.LastName == "" ? "" : userModel.LastName.Trim(), IsActive = userModel.IsActive, CreatedOn = DateTime.Now, LastUpdatedOn = DateTime.Now, RoleID = userModel.RoleID }; identityUser = await _userManager.CreateAsync(appUser, userModel.Password); if (identityUser.Succeeded) { var parameters = new DynamicParameters(); using (SqlConnection cxn = new SqlConnection(_dcDb)) { parameters.Add("@UserID", appUser.UserID, DbType.Int32); parameters.Add("@Id", appUser.Id, DbType.String); parameters.Add("@RoleId", appUser.RoleID, DbType.String); parameters.Add("@FatherName", userModel.FatherName, DbType.String); parameters.Add("@AadharNumber", userModel.AadharNumber, DbType.String); if (userModel.ParentID != 0) { parameters.Add("@ParentID", userModel.ParentID, DbType.Int32); } if (userModel.SponserID != 0) { parameters.Add("@SponserID", userModel.SponserID, DbType.Int32); } if (userModel.UnderID != 0) { parameters.Add("@UnderID", userModel.UnderID, DbType.Int32); } if (userModel.SourceID != 0) { parameters.Add("@SourceID", userModel.SourceID, DbType.Int32); } parameters.Add("@Position", userModel.Position, DbType.String); parameters.Add("@DcID", userModel.DcID, DbType.String); parameters.Add("@SecretCode", userModel.SecretCode, DbType.String); parameters.Add("@UserStatusID", userModel.UserStatusID, DbType.Int32); parameters.Add("@PositionsCompleted", userModel.PositionsCompleted, DbType.Int32); parameters.Add("@CreatedBy", userID, DbType.Int32); parameters.Add("@CreatedDate", DateTime.Now, DbType.DateTime); isUserInserted = await cxn.ExecuteScalarAsync <int>("dbo.InsertOrUpdate_UserDetails_Renewal", parameters, commandType : CommandType.StoredProcedure); cxn.Close(); string smsBody = $"Welcome to DIAMAND CARE " + $"Your USERNAME :- {userModel.UserName} " + $"DCID number :- {userModel.DcID} " + $"Your PASSWORD :- {userModel.Password} " + $"Login at " + _url; await SendSMSDCID(userModel.PhoneNumber, smsBody); if (isUserInserted != 0) { await _userManager.DeleteAsync(appUser); return(identityUserResult = Tuple.Create(false, "Renew loan account not created.Please try again.")); } } identityUserResult = Tuple.Create(true, "Renew loan account created successfully!"); } else { identityUserResult = Tuple.Create(identityUser.Succeeded, string.Join(",", identityUser.Errors)); } } catch (Exception ex) { ErrorLog.Write(ex); await _userManager.DeleteAsync(appUser); identityUserResult = Tuple.Create(false, "Oops! Renew loan account created failed with error " + ex.Message + ".Please try again."); } return(identityUserResult); }
// Deletes the specified user public async Task <IdentityUser> Delete(IdentityUser user) { await _userManager.DeleteAsync(user); return(user); }
public async Task <Tuple <bool, string[]> > DeleteUserAsync(ApplicationUser user) { var result = await _userManager.DeleteAsync(user); return(Tuple.Create(result.Succeeded, result.Errors.Select(e => e.Description).ToArray())); }
public async Task <IActionResult> ConfirmDeleteUser(int id) { try { Notification noti; var user = await _userManager.FindByIdAsync(id.ToString()); var fullName = user.FullName; if (user.UserName == "admin") { noti = new Notification { Title = "Thất bại", Content = "Không được xóa account này !", Icon = "remove", MessageType = "negative", Button = "Quay lại" }; return(PartialView("_Notify", noti)); } else { var userRoles = await _userManager.GetRolesAsync(user); if (userRoles.Count > 0) { await _userManager.RemoveFromRolesAsync(user, userRoles); } var result = await _userManager.DeleteAsync(user); if (result.Succeeded) { _bookStoreData.Commit(); noti = new Notification { Title = "Thành công", Content = "Đã xóa nhân viên " + fullName + " !", Icon = "checkmark", MessageType = "positive", Button = "Hoàn tất" }; return(PartialView("_Notify", noti)); } } noti = new Notification { Title = "Thất bại", Content = "Không được xóa account này !", Icon = "remove", MessageType = "negative", Button = "Quay lại" }; return(PartialView("_Notify", noti)); } catch (Exception) { var noti = new Notification { Title = "Thất bại", Content = "Không được xóa nhân viên này !", Icon = "remove", MessageType = "negative", Button = "Quay lại" }; return(PartialView("_Notify", noti)); } }
public async Task RemoveAsync(User entity) { await _userManager.DeleteAsync(entity); }
public override async Task DeleteAsync(EntityDto <long> input) { var user = await _userManager.GetUserByIdAsync(input.Id); await _userManager.DeleteAsync(user); }
public async Task <IActionResult> Register(RegisterViewModel model) { try { if (ModelState.IsValid) { var user = new ApplicationUser { FullName = model.FullName, UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); var ownerId = _userManager.GetUserId(User); if (result.Succeeded) { ////generate email confirmation token var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = token }, Request.Scheme); _logger.Log(LogLevel.Warning, confirmationLink); //compose email var messageSubject = "Confirm your email"; string emailBody = $"<h3>Hello {model.FullName}</h3>, <br><p>Please Click on this <a href='{confirmationLink}'>Link</a> to verify your account</p>"; //initiate sending email await _emailSender.SendMail(model.Email, messageSubject, emailBody); //check if role exists var roleExists = await _roleManager.RoleExistsAsync("Owner"); IdentityResult roleResult; //if roleExists add newly registered user to "Owner" role //else create "Owner" role and add newly registered to the role if (roleExists) { roleResult = await _userManager.AddToRoleAsync(user, "Owner"); } else { await _roleManager.CreateAsync(new IdentityRole("Owner")); roleResult = await _userManager.AddToRoleAsync(user, "Owner"); } if (roleResult.Succeeded) { var userid = Guid.Parse(user.Id); var owner = new Owner() { FullName = model.FullName, Email = model.Email, }; //add new user to Owner table var addOwner = _ownerDataStore.Post(owner); if (addOwner == null) { await _userManager.RemoveFromRoleAsync(user, "Owner"); await _userManager.DeleteAsync(user); } //await _signInManager.SignInAsync(user, isPersistent: false); //return RedirectToAction("index", "dash"); //show email confirmation message ViewBag.ErrorTitle = "Registration Successful"; ViewBag.ErrorMessage = "Please confirm your email by clicking on the " + "link we sent to your email"; return(View("Confirmation")); } else { foreach (var item in roleResult.Errors) { ModelState.AddModelError("", item.Description); } } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } catch (Exception error) { // throw error; return(View(error)); } return(View(model)); }
public async Task DeleteAsync(string id) => await umanager.DeleteAsync(await umanager.FindByIdAsync(id));
public async Task <JsonResult> Register([Bind("Email,FirstName,LastName,Address,PhoneNumber,ConfirmPassword,Password")] RegisterViewModel model) { ErrorMessage errorMsg = new ErrorMessage(); errorMsg.IsSuccess = false; if (ModelState.IsValid) { var user = new ApplicationUser { Email = model.Email, UserName = model.Email, FirstName = model.FirstName, LastName = model.LastName, Address = model.Address, PhoneNumber = model.PhoneNumber, PictureUrl = "blank-profile.png", AccountCreatedDate = DateTime.Now, }; var result = await _UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { try { //GENERATE EMAIL GENERATION TOKEN var token = await _UserManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action("ConfirmEmail", "Account", new { userID = user.Id, token = token }, Request.Scheme); //SENDING EMAIL (REENABLE THIS LATER) MailMessage message = new MailMessage("*****@*****.**", model.Email); message.Subject = "Confirm your E-mail registration - HomeSquare"; message.Body = "Thank you for registering with us, Click here to activate your account: \n" + confirmationLink; EmailController.SendEmail(message); errorMsg.IsSuccess = true; errorMsg.Message.Add($"Registration Successful - To activate your account, please visit on the link that has been sent to {model.Email}"); await _UserManager.AddToRoleAsync(user, "CUSTOMER"); } catch { await _UserManager.DeleteAsync(user); errorMsg.Message.Add("Failure in sending Email confirmation, Please try again."); } return(Json(errorMsg)); } foreach (var error in result.Errors) { if (error.Code == "DuplicateUserName") { continue; } errorMsg.Message.Add($"{error.Description}"); } } var allErrors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage)); foreach (string error in allErrors) { errorMsg.Message.Add($"{error}"); } return(Json(errorMsg)); }
public async Task<ActionResult> DeleteConfirmed(string id) { var roleStore = new RoleStore<IdentityRole>(db); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(db); var userManager = new UserManager<ApplicationUser>(userStore); if (ModelState.IsValid) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var user = await userManager.FindByIdAsync(id); // ev. 3parts inloggningar var logins = user.Logins; foreach (var login in logins.ToList()) { await userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey)); } var rolesForUser = await userManager.GetRolesAsync(id); if (rolesForUser.Count() > 0) { foreach (var item in rolesForUser.ToList()) { // item should be the name of the role var result = await userManager.RemoveFromRoleAsync(user.Id, item); } } if (user.Documents.Count() > 0) { foreach (var doc in user.Documents.ToList()) { db.Documents.Remove(doc); } } await userManager.DeleteAsync(user); return RedirectToAction("Index"); } else { return View(); } }
private async Task Seed(IUnitOfWork uow , UserManager<ApplicationUser> usrMan, RoleManager<IdentityRole> _RoleManager) { var email = "*****@*****.**"; var RoleName = "CustomerAdmin"; var role = await _RoleManager.FindByNameAsync(RoleName); if (role == null) { role = new IdentityRole { Name = RoleName }; await _RoleManager.CreateAsync(role); } RoleName = "superadmin"; role = await _RoleManager.FindByNameAsync( RoleName ); if ( role == null) { role = new IdentityRole { Name = "SuperAdmin" }; await _RoleManager.CreateAsync(role); } var appUser = await usrMan.FindByEmailAsync(email); if (appUser != null) { var result = await usrMan.DeleteAsync(appUser); } else { appUser = new ApplicationUser() { UserName = email, Email = email }; var result2 = await usrMan.CreateAsync(appUser, "Shafiro2,"); if (result2.Succeeded) { await usrMan.AddToRoleAsync(appUser, RoleName ); var hrmUser = new User() { UserID = "7310209296", FirstName = "Gabriel", LastName = "Tekin", UserName = "******", UserCode = "tekgab", PhoneNumber = "0702385537" }; if (uow.UserRepository.GetEagerLoad( w => w.UserID.Equals( hrmUser.UserID, StringComparison.OrdinalIgnoreCase )).FirstOrDefault() == null ) { uow.UserRepository.Insert(hrmUser); uow.Save(); } } else { var code = result2.Errors.FirstOrDefault().Code; } } } // method seed