public static void IsFailure(IdentityResult result, IdentityError error) { Assert.NotNull(result); Assert.False(result.Succeeded); Assert.Equal(error.Description, result.Errors.First().Description); Assert.Equal(error.Code, result.Errors.First().Code); }
public async Task <IdentityResult> DeleteAsync(Colaborador user, CancellationToken cancellationToken) { try { await Repositorio.RemoverAsync(user); return(IdentityResult.Success); } catch (Exception e) { IdentityError error = new IdentityError { Description = e.Message }; return(IdentityResult.Failed(error)); } }
///EDITAR public List <IdentityError> ModeloEditarUsuario(int usuarioId, string nombre, string apellido, DateTime fecha_nacimiento, string sexo, string nacionalidad, DateTime fecha_alta, string direccion, string email, string telefono, string estado_civil, int numero_hijos, int numero_seguridad_social, string tipo, string porcentaje, string identificacion, string n_identificacion, string permiso_trabajo, string permiso_recidencia, string empadronado, string tipo_licencia) { List <IdentityError> ListaEditar = new List <IdentityError>(); IdentityError regresa = new IdentityError(); var usuario = new Usuario { UsuarioId = usuarioId, Nombre = nombre, Apellido = apellido, Fecha_Nacimiento = fecha_nacimiento, Sexo = sexo, Nacionalidad = nacionalidad, Fecha_Alta = fecha_alta, Direccion = direccion, Email = email, Telefono = telefono, EstadoCivil = estado_civil, NumeroHijos = numero_hijos, NumeroSeguridadSocial = numero_seguridad_social, Identificacion = identificacion, N_Identificacion = n_identificacion, Permiso_Trabajo = permiso_trabajo, Permiso_Recidencia = permiso_recidencia, Empadronado = empadronado, Tipo_Licencia = tipo_licencia }; try { _contexto.Usuario.Update(usuario); _contexto.SaveChanges(); regresa = new IdentityError { Code = "save", Description = "save" }; }catch (Exception ex) { regresa = new IdentityError { Code = ex.Message, Description = ex.Message }; } ListaEditar.Add(regresa); return(ListaEditar); }
//POST: /api/AvioAdmin/Register public async Task<Object> PostAdmin(AdminModel body) { Console.WriteLine("post pozvan"); var admin = new Admin() { UserName = body.UserName, Email = body.Email, Name = body.Name, Lastname = body.Lastname, Grad = body.Grad, Drzava = body.Drzava, BrojPasosa = body.BrojPasosa.ToString(), BrojTelefona = body.BrojTelefona.ToString(), PromenioPassword = false, TipKorisnika = body.TipKorisnika }; try { var svi = await _userManager.Users.ToListAsync(); foreach (var u in svi) { if (u.Email == admin.Email) { IdentityError err = new IdentityError(); err.Code = "DuplicateEmail"; IdentityResult res = new IdentityResult(); res.Errors.Append(err); return Ok(res); } } var result = await _userManager.CreateAsync(admin, body.Password); if (result.Errors.Any()) { var test = result.Errors.ToList(); //return BadRequest(new { message = test[0].Description}); return Ok(result); } return Ok(result); } catch (Exception ex) { throw ex; } }
public IdentityError Inscripcion(string idUser, int cursoID) { IdentityError identityError; try { var cursoInscripcion = context._TInscripcion.Where( c => c.CursoID.Equals(cursoID) && c.EstudianteID.Equals(idUser)).ToList(); if (cursoInscripcion.Count.Equals(0)) { var curso = getTCurso(cursoID); var inscripcion = new Inscripcion { EstudianteID = idUser, Fecha = DateTime.Now, Pago = curso.Costo, CursoID = curso.CursoID }; context.Add(inscripcion); context.SaveChanges(); identityError = new IdentityError { Description = "Done" }; } else { identityError = new IdentityError { Description = "Ya está suscrito en el curso" }; } } catch (Exception e) { identityError = new IdentityError { Code = "Error", Description = e.Message }; } return(identityError); }
/// <summary> /// Validates payment configuration. /// </summary> /// <param name="paymentConfig">The Payment configuration.</param> public void ValidateConfiguration(PaymentConfiguration paymentConfig) { string[] supportedPaymentModes = { "sandbox", "live" }; paymentConfig.AssertNotNull(nameof(paymentConfig)); paymentConfig.ClientId.AssertNotEmpty(nameof(paymentConfig.ClientId)); paymentConfig.ClientSecret.AssertNotEmpty(nameof(paymentConfig.ClientSecret)); paymentConfig.AccountType.AssertNotEmpty(nameof(paymentConfig.AccountType)); if (!supportedPaymentModes.Contains(paymentConfig.AccountType)) { throw new PartnerDomainException(Resources.InvalidPaymentModeErrorMessage); } try { Dictionary <string, string> configMap = new Dictionary <string, string> { { "clientId", paymentConfig.ClientId }, { "clientSecret", paymentConfig.ClientSecret }, { "mode", paymentConfig.AccountType }, { "connectionTimeout", "120000" } }; string accessToken = new OAuthTokenCredential(configMap).GetAccessToken(); APIContext apiContext = new APIContext(accessToken); } catch (PayPalException paypalException) { if (paypalException is IdentityException) { // thrown when API Context couldn't be setup. IdentityException identityFailure = paypalException as IdentityException; IdentityError failureDetails = identityFailure.Details; if (failureDetails != null && failureDetails.error.Equals("invalid_client", StringComparison.InvariantCultureIgnoreCase)) { throw new PartnerDomainException(ErrorCode.PaymentGatewayIdentityFailureDuringConfiguration).AddDetail("ErrorMessage", Resources.PaymentGatewayIdentityFailureDuringConfiguration); } } // if this is not an identity exception rather some other issue. throw new PartnerDomainException(ErrorCode.PaymentGatewayFailure).AddDetail("ErrorMessage", paypalException.Message); } }
public async Task ReturnsInvalidIfNotSucceeded() { var identityError = new IdentityError(); identityError.Description = "Something went wrong"; roleManager.Setup(rm => rm.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(new Role()); roleManager.Setup(rm => rm.DeleteAsync(It.IsAny <Role>())).ReturnsAsync(IdentityResult.Failed(identityError)); var result = await roleService.DeleteRole(It.IsAny <int>()); roleManager.Verify(rm => rm.FindByIdAsync(It.IsAny <string>()), Times.Once); roleManager.Verify(rm => rm.DeleteAsync(It.IsAny <Role>()), Times.Once); Assert.IsNull(result.Data); Assert.AreEqual(ResultType.Invalid, result.ResultType); Assert.IsNotNull(result.Errors); }
public override async Task <IdentityResult> UpdateAsync(CustomIdentityUser user) { Task <IdentityResult> UpdateTask = base.UpdateAsync(user); try { IdentityResult identityResult = await UpdateTask; } catch (Exception ex) { IdentityError error = new IdentityError() { Code = ex.HResult.ToString(), Description = ex.Message }; return(IdentityResult.Failed(error)); } return(UpdateTask.Result); }
public async static Task <IdentityResult> ConfirmEmailByCodeAsync(this UserManager <ApplicationUser> userManager, ApplicationUser user, string code) { var confirmedUser = await userManager.Users.FirstOrDefaultAsync(u => u.confirmCode == code); var result = new IdentityResult(); var codeError = new IdentityError { Code = "confirmCode", Description = "this confirm code is not valid" }; if (confirmedUser == null) { result.Errors.Append(codeError); return(result); } confirmedUser.EmailConfirmed = true; confirmedUser.confirmCode = null; return(await userManager.UpdateAsync(confirmedUser)); }
#pragma warning disable 1998 public async Task <IdentityResult> TwoFactorDisableAsync(ApplicationUser user) #pragma warning restore 1998 { var result = m_userManager.DisableTwoFactorAuth(user.Id); if (result.HasError) { var error = new IdentityError { Description = result.Error.Message, Code = result.Error.Code }; return(IdentityResult.Failed(error)); } return(IdentityResult.Success); }
public async Task <IdentityResult> DeleteAsync(User user, CancellationToken cancellationToken) { try { await _repo.DeleteUser(user); return(IdentityResult.Success); } catch (Exception ex) { var error = new IdentityError { Code = "", Description = $"Identity Error: {ex.Message}" }; return(IdentityResult.Failed(error)); } }
public List <IdentityError> ClaseGuardarCliente( int Cedula, string Primernombre, string Segundonombre, string Primerapellido, string Segundoapellido, int Telefono, string Correo, string Tipo_prefe_inmueble, int Importe_maximo, DateTime Fecha_registro, int ClienteId ) { List <IdentityError> ListaResultado = new List <IdentityError>(); IdentityError error = new IdentityError(); var objetocliente = new Cliente { Cedula = Cedula, Primernombre = Primernombre, Segundonombre = Segundonombre, Primerapellido = Primerapellido, Segundoapellido = Segundoapellido, Telefono = Telefono, Correo = Correo, Tipo_prefe_inmueble = Tipo_prefe_inmueble, Importe_maximo = Importe_maximo, Fecha_registro = Fecha_registro, ClienteId = ClienteId }; try { _contexto.Cliente.Add(objetocliente); _contexto.SaveChanges(); error = new IdentityError { Code = "Save", Description = "Save" }; } catch (Exception ex) { error = new IdentityError { Code = ex.Message, Description = ex.Message }; } ListaResultado.Add(error); return(ListaResultado); }
private bool HandleNewPasswordIdentityError(IdentityError error, IList <string> errors) { var added = false; switch (error.Code) { case nameof(IdentityErrorDescriber.PasswordTooShort): errors.Add(error.Description); added = true; break; case nameof(IdentityErrorDescriber.PasswordRequiresUniqueChars): errors.Add(error.Description); added = true; break; case nameof(IdentityErrorDescriber.PasswordRequiresNonAlphanumeric): errors.Add(error.Description); added = true; break; case nameof(IdentityErrorDescriber.PasswordRequiresDigit): errors.Add(error.Description); added = true; break; case nameof(IdentityErrorDescriber.PasswordRequiresLower): errors.Add(error.Description); added = true; break; case nameof(IdentityErrorDescriber.PasswordRequiresUpper): errors.Add(error.Description); added = true; break; case TooCommonPasswordErrorCode: errors.Add(error.Description); added = true; break; } return(added); }
public async Task <IdentityResult> DeleteAsync(string id) { var user = await _userManager.FindByIdAsync(id); if (user != null) { var result = await _userManager.DeleteAsync(user); return(result); } var identityError = new IdentityError { Code = "DeleteError", Description = "User not found", }; return(IdentityResult.Failed(identityError)); }
public async Task ResetPasswordWithInvalidToken() { var authenticateService = _serviceProvider.GetService <AuthenticateService>(); var user = new User { Fullname = "John Doe", UserName = "******", Email = "*****@*****.**" }; var password = Guid.NewGuid().ToString(); var mockResetTokenPassword = Guid.NewGuid().ToString(); var mockInvalidPassword = new IdentityError { Code = nameof(IdentityErrorDescriber.InvalidToken) }; _userManagerMock .Setup(x => x.FindByEmailAsync(It.IsAny <string>())) .ReturnsAsync(user); _userManagerMock .Setup(x => x.ResetPasswordAsync(It.IsAny <User>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(IdentityResult.Failed(mockInvalidPassword)); try { await authenticateService.ResetPasswordAsync(user.Email, password, mockResetTokenPassword); } catch (InvalidTokenException e) { Assert.That(e.Error.Code == mockInvalidPassword.Code, $"Error code should be {mockInvalidPassword.Code}"); Assert.That(e.Message == "Invalid Token.", "Message should be 'Invalid Token.'"); } _userManagerMock.Verify(x => x.FindByEmailAsync(user.Email), $"Should call FindByEmailAsync with {user.Email}"); _userManagerMock.Verify(x => x.ResetPasswordAsync( It.Is <User>(p => p.Email == user.Email && p.UserName == user.Email && p.Fullname == user.Fullname), It.Is <string>(p => p == mockResetTokenPassword), It.Is <string>(p => p == password) ), "Should call ResetPasswordAsync"); }
public async Task <IdentityResult> UpdateBillingAddressAsync(ApplicationUser user, Address billingAddress, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (billingAddress == null) { throw new System.ArgumentNullException(nameof(billingAddress)); } if (user == null) { throw new System.ArgumentNullException(nameof(user)); } if (user.CreditCard == null || user.CreditCard.BillingAddress == null) { throw new System.ArgumentNullException(nameof(ApplicationUser.CreditCard)); } if (user.CreditCard.BillingAddress.Id != billingAddress.Id) { var error = new IdentityError { Description = $"Invalid billing address id = { billingAddress.Id }" }; return(IdentityResult.Failed(error)); } // merge changes Context.Entry(user.CreditCard.BillingAddress).CurrentValues.SetValues(billingAddress); try { await SaveChanges(cancellationToken); } catch (DbUpdateConcurrencyException) { return(IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure())); } return(IdentityResult.Success); }
public async Task <IdentityResult> UpdateDriverLicenseAsync(ApplicationUser user, DriverLicense driverLicense, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (driverLicense == null) { throw new System.ArgumentNullException(nameof(driverLicense)); } if (user == null) { throw new System.ArgumentNullException(nameof(user)); } if (user.DriverLicense == null) { throw new System.ArgumentNullException(nameof(ApplicationUser.DriverLicense)); } if (user.DriverLicense.Id != driverLicense.Id) { var error = new IdentityError { Description = $"Invalid driver license id = { driverLicense.Id }" }; return(IdentityResult.Failed(error)); } // merge changes Context.Entry(user.DriverLicense).CurrentValues.SetValues(driverLicense); try { await SaveChanges(cancellationToken); } catch (DbUpdateConcurrencyException) { return(IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure())); } return(IdentityResult.Success); }
public async Task <IdentityResult> AddToRole([FromBody] AccessModel accessModel) { var user = await _userManager.FindByIdAsync(accessModel.UserId); var role = await _roleManager.FindByIdAsync(accessModel.RoleId); if (user != null && role != null) { return(await _userManager.AddToRoleAsync(user, role.Name)); } var identityError = new IdentityError { Code = "AddToRoleError", Description = "User or role not found.", }; return(IdentityResult.Failed(identityError)); }
public async Task <IdentityResult> RemoveFromRole(string userId, string roleId) { var user = await _userManager.FindByIdAsync(userId); var role = await _roleManager.FindByIdAsync(roleId); if (user != null && role != null) { return(await _userManager.RemoveFromRoleAsync(user, role.Name)); } var identityError = new IdentityError { Code = "RemoveFromRoleError", Description = "User or role not found.", }; return(IdentityResult.Failed(identityError)); }
internal async Task <List <object[]> > userLogin(string email, string password) { try { var result = await _signInManager.PasswordSignInAsync(email, password, false, //En false no bloquea la cuenta si no se autentica correctamente lockoutOnFailure : false); if (result.Succeeded) { //Buscamos en la BD el usuario logueado y cargamos sus datos en appUser var appUser = _userManager.Users.Where(u => u.Email.Equals(email)).ToList(); _userRoles = await _usersRole.getRole(_userManager, _roleManager, appUser[0].Id); _userData = new UserData { Id = appUser[0].Id, Role = _userRoles[0].Text, UserName = appUser[0].UserName }; code = "0"; description = result.Succeeded.ToString(); } else { code = "1"; description = "Correo o contraseña inválidos"; } } catch (Exception ex) { code = "2"; description = ex.Message; } _identityError = new IdentityError { Code = code, Description = description }; object[] data = { _identityError, _userData }; dataList.Add(data); return(dataList); }
public async Task DoesNotCreateUserAsync() { var identityError = new IdentityError(); identityError.Description = "Something went wrong"; var identityerrorArray = new IdentityError[1] { identityError }; userManager.Setup(x => x.CreateAsync(It.IsAny <User>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed(identityerrorArray)); var result = await userService.CreateUser("Test", "Test", "Test"); userManager.Verify(m => m.CreateAsync(It.IsAny <User>(), It.IsAny <string>()), Times.Once); Assert.AreEqual(ResultType.Invalid, result.ResultType); Assert.IsNotNull(result.Errors); Assert.IsNull(result.Data); }
internal async Task <object[]> userLogin(string email, string password, int commisionerid) { try { var userObtainedByEmail = await _userManager.FindByEmailAsync(email); if (userObtainedByEmail.Email.Equals(email)) { await _singInManager.SignInAsync(userObtainedByEmail, false); var user = _userManager.Users.Where(u => u.Email.Equals(email)).ToList(); _userRoles = await _usersRole.getRole(_userManager, _roleManager, user[0].Id); _userData = new UserData { Id = user[0].Id, Role = _userRoles[0].Text, UserName = user[0].UserName, CommisionerId = commisionerid, }; code = "0"; description = "True"; } else { code = "1"; description = "Usuario o contraseña invalidas"; } } catch (Exception ex) { code = "2"; description = ex.Message; } _identityError = new IdentityError { Code = code, Description = description }; object[] data = { _identityError, _userData }; return(data); }
public override IdentityError InvalidEmail(string email) { IdentityError identityError = new IdentityError(); identityError.Code = "InvalidEmail"; String result = ""; if (string.IsNullOrEmpty(email)) { result = $"邮箱不能为空无效。"; } else { result = $"邮箱({email})无效。"; } identityError.Description = result; return(identityError); }
/// <summary> /// Check Password of User /// </summary> /// <typeparam name="T">Usually it is ApplicationUser</typeparam> /// <param name="userManager">The manager which give Validation Rules</param> /// <param name="errors">If Password is not valid then return rules which not passed, else return null</param> /// <returns></returns> public bool IsValid <T>(UserManager <T> userManager, T user, out IdentityError error) where T : class { IdentityError returnErrors = null; async ValueTask <bool> IsNotValid(object x) { IdentityResult validResul; switch (x) { case IPasswordValidator <T> p: validResul = await p.ValidateAsync(userManager, user, Password); break; case IUserValidator <T> u: validResul = await u.ValidateAsync(userManager, user); break; default: return(true); } if (!validResul.Succeeded) { returnErrors = validResul.Errors.FirstOrDefault(); return(true); } else { return(false); } } var IsAnyPasswordRulesNotPassed = userManager.PasswordValidators .Any(x => IsNotValid(x).GetAwaiter().GetResult()); var IsAnyUserRulesNotPassed = userManager.UserValidators .Any(x => IsNotValid(x).GetAwaiter().GetResult()); error = returnErrors; return(!(IsAnyPasswordRulesNotPassed || IsAnyUserRulesNotPassed)); }
public async Task <IActionResult> Delete([FromBody] Credentials credentials) { IdentityError error = null; var userToDelete = userManager.Users.SingleOrDefault(user => user.Email.Equals(credentials.Email)); if (userToDelete != null) { if (await userManager.CheckPasswordAsync(userToDelete, credentials.Password)) { var result = await userManager.DeleteAsync(userToDelete); if (!result.Succeeded) { return(BadRequest(result.Errors)); } } else { error = new IdentityError() { Code = "Invalid Credentails", Description = "Please make sure your credentials is correct." }; } } else { error = new IdentityError() { Code = "Not Found", Description = "Username not exist." }; } if (error != null) { var errors = new List <IdentityError> { error }; return(BadRequest(errors)); } return(Ok()); }
public async Task <IdentityResult> CreateUserAsync(UsuarioDTO user) { try { IdentityResult result = userManager.CreateAsync(Util.castUsuarioToIdentity(user), user.Contrasena).Result; if (result.Succeeded) { Usuario appUser = userManager.FindByNameAsync(user.UserName).Result; foreach (int rol in user.Roles) { Rol rolApp = DBContext.Roles.Where(r => r.Id == rol).Single(); if ((appUser != null) && (rolApp != null)) { IdentityUserRole <int> role = new IdentityUserRole <int>(); role.RoleId = rolApp.Id; role.UserId = appUser.Id; DBContext.UserRoles.Add(role); await DBContext.SaveChangesAsync(); result = IdentityResult.Success; } } } return(result); } catch (Exception e) { IdentityError error = new IdentityError(); error.Code = e.Message; error.Description = e.StackTrace.ToString(); IdentityResult result = IdentityResult.Failed(error); return(result); } }
public async Task <RegistrationAttempt> Register(RegisterViewModel model, string returnUrl = null) { var registrationErrors = new IdentityError[] { new IdentityError() { Code = "UNC1", Description = "User manager has not attempted to create a user" } }; IdentityResult result = IdentityResult.Failed(registrationErrors); if (ModelState.IsValid) { result = await _accountService.Register(model, "http"); } return(new RegistrationAttempt(model, result.Succeeded, result.Errors)); }
public Task <IdentityResult> ValidateAsync(UserManager <User> manager, User user, string password) { IdentityResult result; if (password.Length >= options.Value.Password.RequiredLength) { result = IdentityResult.Success; } else { var error = new IdentityError() { Description = $"Password length must be over {options.Value.Password.RequiredLength} characters." }; result = IdentityResult.Failed(error); } return(Task.FromResult(result)); }
public async void CreateErrorTest() { var umMock = GetUserManagerMock(); var rmMock = GetRoleManagerMock(); var rolesController = new RolesController(rmMock.Object, umMock.Object); IdentityError ErrorMessage = new IdentityError { Description = "something was wrong" }; rmMock.Setup(item => item.CreateAsync(It.IsAny <IdentityRole>())) .ReturnsAsync(IdentityResult.Failed(ErrorMessage)); rolesController.ModelState.Clear(); var result = await rolesController.Create("rolename"); Assert.NotNull(result); Assert.Single(rolesController.ModelState[""].Errors); Assert.Equal(rolesController.ModelState[""].Errors[0].ErrorMessage.ToString(), ErrorMessage.Description.ToString()); }
public static string LocalizeErrorMessage(this IdentityError error, IStringLocalizer localizer) { var key = $"Identity.{error.Code}"; var localizedString = localizer[key]; if (!localizedString.ResourceNotFound) { var englishLocalizedString = localizer.WithCulture(CultureInfo.GetCultureInfo("en"))[key]; if (!englishLocalizedString.ResourceNotFound) { if (FormattedStringValueExtracter.IsMatch(error.Description, englishLocalizedString.Value, out var values)) { return(string.Format(localizedString.Value, values.Cast <object>().ToArray())); } } } return(localizer["Identity.Default"]); }
public async Task ReturnsInvalidIfNotDeleted() { var identityError = new IdentityError(); identityError.Description = "Something went wrong"; var identityerrorArray = new IdentityError[1] { identityError }; userManager.Setup(x => x.GetUserAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(new User()); userManager.Setup(x => x.DeleteAsync(It.IsAny <User>())).ReturnsAsync(IdentityResult.Failed(identityError)); var result = await userService.DeleteUser(It.IsAny <ClaimsPrincipal>()); userManager.Verify(m => m.GetUserAsync(It.IsAny <ClaimsPrincipal>()), Times.Once); userManager.Verify(m => m.DeleteAsync(It.IsAny <User>()), Times.Once); Assert.AreEqual(ResultType.Invalid, result.ResultType); Assert.IsNull(result.Data); }