public ActionResult Login(string email, string password) { ActionResult result = View(); if (ModelState.IsValid) { using (var context = new Domain.Entities()) { var employee = context.Employees.FirstOrDefault(e => e.Email == email); IPasswordValidator passwordService = new PasswordService(); if (employee == null) { ModelState.AddModelError("", "Gebruiker niet gevonden met het ingevoerde emailadres."); } else if (!passwordService.PasswordsCompare(password, employee.Password)) { ModelState.AddModelError("", "Wachtwoord ongeldig"); } else { var userSession = UserSession.Current; userSession.Employee = employee; //Redirect naar pagina result = RedirectToAction("Index", "Home"); } } } return(result); }
public ActionResult Register(RegisterView model, string returnUrl) { if (Session["UserId"] != null) { return(RedirectToAction("Index", "Home")); } var emailExist = (from user in db.Users where user.Email == model.Email.ToLower() select user).FirstOrDefault(); if (emailExist != null) { ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address."); } else if (ModelState.IsValid) { User user = new User(); user.Email = model.Email.ToLower(); user.UserTypeId = UserType.USER; user.Password = PasswordService.Hash(model.Password); db.Users.Add(user); db.SaveChanges(); Session["UserId"] = user.Id; Session["UserTypeId"] = UserType.USER; return(RedirectToAction("Index", "Home")); } return(View("Index", model)); }
public void password_service_compares_passwords_correctly() { IPasswordService ps = new PasswordService(new SHA512HashingService(), 8, 32); string rawPassword = "******"; byte[] s1, s2, s3; byte[] h1 = ps.CreatePassword(rawPassword, out s1), h2 = ps.CreatePassword(rawPassword, out s2), h3 = ps.CreatePassword(rawPassword, out s3); //passwords should match with their correct salt Assert.True(ps.ComparePasswords(rawPassword, h1, s1)); Assert.True(ps.ComparePasswords(rawPassword, h2, s2)); Assert.True(ps.ComparePasswords(rawPassword, h3, s3)); //passwords shouldn't match with incorrect salt Assert.False(ps.ComparePasswords(rawPassword, h1, s2)); Assert.False(ps.ComparePasswords(rawPassword, h1, s3)); Assert.False(ps.ComparePasswords(rawPassword, h2, s1)); Assert.False(ps.ComparePasswords(rawPassword, h2, s3)); Assert.False(ps.ComparePasswords(rawPassword, h3, s1)); Assert.False(ps.ComparePasswords(rawPassword, h3, s2)); }
static void Main(string[] args) { // Skriv ett program som genererar ett lösenord baserat på följande parametrar: // 1. Längd (positivt heltal) // 2. Antal stora bokstäver. // 3. Antal siffror. // 4. Antal specialtecken. Console.WriteLine("Password Generator"); Console.WriteLine("------------------"); Console.WriteLine(); Console.Write("How many characters do you want your password to be?"); var characterInput = Console.ReadLine(); var passwordLength = uint.Parse(characterInput); Console.Write("How many uppercase letters"); var uppercaseInput = Console.ReadLine(); var uppercaseCount = uint.Parse(uppercaseInput); Console.Write("How many numbers?"); var numbersInput = Console.ReadLine(); var numbersCount = uint.Parse(numbersInput); Console.Write("How many numbers?"); var specialInput = Console.ReadLine(); var specialCount = uint.Parse(specialInput); var passwordGenerator = new PasswordService(); var password = passwordGenerator.GeneratePassword(passwordLength, uppercaseCount, numbersCount, specialCount); Console.WriteLine($"Your password is: {password}"); }
public void too_many_parameters_throws_error() { var passwordService = new PasswordService(); Assert.ThrowsException <ArgumentOutOfRangeException> (() => passwordService.GeneratePassword(3, 2, 2, 2)); }
public async Task <ActionResult <Usuario> > Put([FromServices] DataContext context, int id, [FromBody] Usuario usuario) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != usuario.Id) { return(NotFound(new { message = "Usuário não encontrado" })); } try { context.Entry(usuario).State = EntityState.Modified; if (context.Entry(usuario).State == EntityState.Modified) { usuario.Password = PasswordService.GeneratePassword(usuario.Password); } await context.SaveChangesAsync(); return(usuario); } catch (Exception) { return(BadRequest(new { message = "Não foi possível atualizar o usuário" })); } }
public void LoginValidation() { var dbOptionsBuilder = new DbContextOptionsBuilder <MonAmieContext>() .UseInMemoryDatabase(databaseName: "LoginValidation"); var db = new MonAmieContext(dbOptionsBuilder.Options); IUserService us = new UserService(db); IPasswordService ps = new PasswordService(); string salt = ps.CreateSalt(16); string pwd = "Jsmith123"; string hashedPwd = ps.GenerateSHA256Hash(pwd, salt); User user = CreateUser(hashedPwd, salt); us.AddUser(user); User returnedUser = us.GetByEmail("*****@*****.**"); string pwdEntered = "Jsmith123"; string returnedHashedPwd = ps.GenerateSHA256Hash(pwdEntered, returnedUser.PasswordSalt); Assert.IsNotNull(returnedUser); Assert.AreEqual("John", returnedUser.FirstName); Assert.AreEqual("Smith", returnedUser.LastName); Assert.AreEqual(returnedHashedPwd, returnedUser.PasswordHash); }
bool TryGetUsernamePassword(URIish uri, CredentialItem[] items, out CredentialItem.Password passwordItem) { var actualUrl = new Uri(uri.ToString()); var username = (CredentialItem.Username)items.FirstOrDefault(i => i is CredentialItem.Username); var password = (CredentialItem.Password)items.FirstOrDefault(i => i is CredentialItem.Password); if (items.Length == 2 && username == null && password == null) { passwordItem = password; var passwordValue = PasswordService.GetWebPassword(actualUrl); if (passwordValue != null) { username.SetValue(actualUrl.UserInfo); password.SetValueNoCopy(passwordValue.ToArray()); return(true); } } else { passwordItem = null; } return(false); }
public async Task <IActionResult> ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (!model.Name.Equals(User.Identity.Name)) { ModelState.AddModelError("", "Доступ запрещён."); //попытка изменить пароль другому пользователю пресекается. return(View(model)); } User user = await db.Users.FirstOrDefaultAsync(u => u.Name == model.Name); if (user != null) { if (user.Password == PasswordService.GetPasswordHash(model.OldPassword)) { //меняем пароль пользователя на новый user.Password = PasswordService.GetPasswordHash(model.NewPassword); db.Entry(user).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Старый пароль введён неверно."); } } else { ModelState.AddModelError("", "Пользователь не найден."); } } return(View(model)); }
public User CreateUser(string email, Guid SSOID) { try { var useremail = new System.Net.Mail.MailAddress(email); var existingUserWithEmail = _userService.GetUser(email); if (existingUserWithEmail != null) { throw new UserAlreadyExistsException("User with that email already exists."); } } catch (FormatException e) { throw new InvalidEmailException("Invalid Email", e); } var _passwordService = new PasswordService(); DateTime timestamp = DateTime.UtcNow; byte[] salt = _passwordService.GenerateSalt(); string hash = _passwordService.HashPassword(timestamp.ToString(), salt); User user = new User { Username = email, PasswordHash = hash, PasswordSalt = salt, UpdatedAt = timestamp, Id = SSOID }; _userService.CreateUser(user); return(user); }
public ActionResult UpdateUser(AppUser appUser) { var email = HttpContext.User.Identity.Name; if (_appUserService.GetUserByEmail(appUser.Email) == null) { return(BadRequest()); } if (email != appUser.Email) { return(BadRequest()); } int.TryParse( _configuration.GetSection("Auth:PwdSize").Value, out var size); if (size == 0) { throw new ArgumentException(); } var salt = PasswordService.GenerateSalt(size); var pwd = PasswordService.HashPassword(appUser.Password, salt, size); var updatedUser = new AppUser { Email = appUser.Email, Password = pwd, Salt = salt, Name = appUser.Name }; _appUserService.UpdateUser(updatedUser); return(Ok(CreateAppUserDto(updatedUser))); }
public void RegisterConsultantSuccessTest() { // get a valid consultant account Consultant consultant = TestRepository.GetValidConsultant(); IConsultantService conService = new ConsultantService(); // must have a valid consultant Assert.NotNull(consultant); Logger.Debug(consultant, true); var task = conService.RegisterConsultant(consultant); task.Wait(); var conResponse = task.Result; // consultant registration should be successful Assert.True(conResponse.Select(conApiResponse => conApiResponse.Code == ApiResponseCode.RegisterSuccess).FirstOrDefault()); // generate and register new random password string plainPassword = TestRepository.GetValidPlainPassword(); IPasswordService passwordService = new PasswordService(); var passTask = passwordService.RegisterPassword(consultant.Username, plainPassword); passTask.Wait(); var passResponse = passTask.Result; // registration should be successful Assert.True(passResponse.Select(passApiResponse => passApiResponse.Code == ApiResponseCode.RegisterSuccess).FirstOrDefault()); }
protected override void Seed(ApplicationContext db) { db.Materials.Add(new Material { Id = 1, Title = "Material 1" }); for (int i = 0; i < 23; i++) { db.Products.Add(new Product { Title = "Pled Name " + i.ToString(), SizeW = 200, SizeH = 120, MaterialId = 1, InStock = 10, Price = 550 }); } db.UserTypes.Add(new UserType { Id = UserType.USER, Title = "User" }); db.UserTypes.Add(new UserType { Id = UserType.ADMIN, Title = "Admin" }); db.Users.Add(new User { Email = "*****@*****.**", Password = PasswordService.Hash("*****@*****.**"), UserTypeId = UserType.ADMIN }); base.Seed(db); }
private UserDropDownModel GetUserDropDownModel() { return(new UserDropDownModel { AutoPassword = PasswordService.GenerateNewPassword(GetRandomNumber(), GetRandomNumber(), GetRandomNumber(), GetRandomNumber()), Groups = new Dictionary <string, string> { { "TestGroup", "Test Group" } }, UserRoles = new List <UserRole> { new UserRole { Key = "Admin", Value = "App Admin" } }, UserBusinessDepartments = new List <UserBusinessDepartment> { new UserBusinessDepartment { Key = "TestBussDept", Value = "Test Dept" } }, UserLanguages = new List <UserLanguage> { new UserLanguage { Key = "Eng", Value = "English" } }, UserLocation = new List <Country> { new Country { CountryCode = "US", CountryName = "USA", Region = "CA" } }, UserTypes = new List <UserType> { new UserType { Key = "TestType", Value = "Test Type" } } }); }
public RegisterWindow(Window window) { InitializeComponent(); _passwordService = new PasswordService(); _userService = ServiceProvider.GetUserService(); }
public ActionResult CreateUser([FromBody] SignupUserDto dto) { if (!isValidUserCredential(dto)) { return(BadRequest()); } if (_service.GetAppUser(dto.Username) != null) { return(BadRequest()); } int.TryParse( _configuration.GetSection("Auth:PwdSize").Value, out var size); if (size == 0) { throw new ArgumentException(); } var salt = PasswordService.GenerateSalt(size); var pwd = PasswordService.HashPassword(dto.Password, salt, size); _service.CreateUser(dto.Username, pwd, salt); return(CreatedAtRoute(null, dto.Username)); }
public AccountController(ILogger <AccountController> logger, IConfiguration configuration) { _logger = logger; _configuration = configuration; _uservice = new UsuarioService(_logger); _pass = new PasswordService(_logger); }
public OrderController(ClientManagerContext context, EntityCRUDService entityCRUD, PasswordService passwordService, IHubContext <ClientHub> hubContext) { this.entityCRUD = entityCRUD; this.passwordService = passwordService; this.hubContext = hubContext; }
public async Task <IActionResult> PasswordResetLink(string email) { try { var pathToFile = HostingEnvironment.WebRootPath + Path.DirectorySeparatorChar.ToString() + "EmailTemplates" + Path.DirectorySeparatorChar.ToString() + "ResetPassword.html"; Func <string, string, string> confirmationLinkGenerator = (code, userId) => Url.Action("ResetPassword", "Auth", new { userid = userId, token = code }, protocol: HttpContext.Request.Scheme ); await PasswordService.SendPasswordResetEmailLinkAsync(email, confirmationLinkGenerator, pathToFile); return(Ok(null, $"Password reset Link Sent To {email}", ResponseStatus.OK)); } catch (InvalidOperationException ex) { return(BadRequest(null, ex.Message, ResponseStatus.APP_ERROR)); } catch (Exception ex) { return(BadRequest(null, "Oops Something Went Wrong", ResponseStatus.FATAL_ERROR)); } }
public ActionResult PasswordChange(string NewPassword, string Password, string ConfirmPassword) { try { if (NewPassword.Length < 6 || Password.Length < 6 || ConfirmPassword.Length < 6) { ModelState.AddModelError(string.Empty, "パスワードの長さが最低6桁をに入力ください。"); TempData["ViewData"] = ViewData; return(RedirectToAction("PasswordChange")); } if (!Password.Equals(ConfirmPassword)) { ModelState.AddModelError(string.Empty, "パスワードと確認パスワードが同じではないです。"); TempData["ViewData"] = ViewData; return(RedirectToAction("PasswordChange")); } PasswordService passwordService = new PasswordService(); EmployeeLoginOutput employee = (EmployeeLoginOutput)Session["employee"]; string employeeId = employee.Id; passwordService.ChangePassword(employeeId, Password, NewPassword); TempData["SuccessMessage"] = "パスワード変更ができました"; TempData["ViewData"] = ViewData; } catch (Exception e) { ModelState.AddModelError(string.Empty, e.Message); TempData["ViewData"] = ViewData; return(RedirectToAction("PasswordChange")); } return(RedirectToAction("PasswordChange")); }
public ActionResult Login([FromBody] UserDto dto) { var user = _userRepository.GetUserByUsername(dto.Username); if (user == null) { return(BadRequest(new { message = "Username not found." })); } var pwd = PasswordService.HashPassword(dto.Password, user.Salt, _size); if (user.Password != pwd) { return(BadRequest(new { message = "Wrong password." })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_configuration["Auth:Key"]); var tokenDescription = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()), }), Expires = DateTime.Now.AddDays(1), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var securityToken = tokenHandler.CreateToken(tokenDescription); var token = tokenHandler.WriteToken(securityToken); return(Ok(new { user.Username, token })); }
public async Task <IActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { User user = await db.Users.FirstOrDefaultAsync(u => u.Name == model.Name); if (user == null) { // добавляем пользователя в бд user = new User { Name = model.Name, Password = PasswordService.GetPasswordHash(model.Password), MaxLevel = 0, MaxScore = 0 }; Role userRole = db.Roles.FirstOrDefault(r => r.Name == "user"); if (userRole != null) { SetUserRole(ref user, ref userRole); } db.Users.Add(user); await db.SaveChangesAsync(); //аутентификация await Authenticate(user); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Пользователь с таким именем уже существует."); } } return(View(model)); }
private void btnOK_Click(object sender, EventArgs e) { string enteredPasswordHash = Security.HashString(txtPassword.Text); if (passwordHash == "") { if (txtPassword.Text != "" && txtPassword.Text == txtConfirm.Text) { PasswordService.AddNew(new MasterPassword { PasswordHash = enteredPasswordHash }); this.DialogResult = DialogResult.OK; } else if (txtPassword.Text == "") { SendMessage("I can't approve of this.", Color.Red); } else if (txtPassword.Text != txtConfirm.Text) { SendMessage("Passwords do not match.", Color.Red); } } else { if (enteredPasswordHash == passwordHash) { this.DialogResult = DialogResult.OK; } else { SendMessage("Incorrect.", Color.Red); } } }
public void password_follows_password_pattern_when_created() { IPasswordService ps = new PasswordService(new SHA512HashingService(), 8, 32); byte[] s; //correct character combination: number, special, upper and lower case letter Assert.True(ps.CreatePassword("Test123@bc", out s) != null); //password empty Assert.Throws <ArgumentNullException>(() => ps.CreatePassword("", out s)); //password null Assert.Throws <ArgumentNullException>(() => ps.CreatePassword(null, out s)); //too short Assert.Throws <ArgumentOutOfRangeException>(() => ps.CreatePassword("ki", out s)); //too long Assert.Throws <ArgumentOutOfRangeException>(() => ps.CreatePassword( "2314353453452345234523452345345345345345tg5446un 47j7%¤/#B&/B#B&7n67567657474756756754745", out s)); //invalid character combinations Assert.Throws <ArgumentOutOfRangeException>(() => ps.CreatePassword("abcdefg1234", out s)); Assert.Throws <ArgumentOutOfRangeException>(() => ps.CreatePassword("!QWerdggh", out s)); Assert.Throws <ArgumentOutOfRangeException>(() => ps.CreatePassword("avbcvb!!", out s)); Assert.Throws <ArgumentOutOfRangeException>(() => ps.CreatePassword("invt&&!!1", out s)); }
public void password_is_of_lenght() { var passwordService = new PasswordService(); var password = passwordService.GeneratePassword(8); Assert.AreEqual(8, password.Length); }
public void TestPasswordShouldMatchSetPasswordEvenIfDefaultIterationIsDifferent() { _service.SetPassword(_user, _password); var differentXervice = new PasswordService(_defaultIterations + 1, _defaultHashLength); Assert.True(differentXervice.CheckPassword(_user, _password)); }
public LoginUserHandler(IRead <UserDirectory> userDirectoryReader, ITokenGenerator tokenGenerator, IJWTService jwtService, PasswordService passwordService) { _userDirectoryReader = userDirectoryReader; _passwordService = passwordService; _tokenGenerator = tokenGenerator; _jwtService = jwtService; }
public async Task <ActionResult <dynamic> > Authenticate([FromServices] DataContext context, [FromBody] Usuario usuario) { try { string hash = PasswordService.GeneratePassword(usuario.Password); var user = await context.Usuario .AsNoTracking() .Where(x => x.Username == usuario.Username && x.Password == hash) .FirstOrDefaultAsync(); if (user == null) { return(NotFound(new { message = "Usuário ou senha inválidos" })); } var token = TokenService.GenerateToken(user); return(new { user = user, token = token }); } catch (Exception) { return(BadRequest(new { message = "Não foi possível realizar o login" })); } }
public UserValidationService( SecurityContextService securityContextService, PasswordService passwordService) { _securityContextService = securityContextService; _passwordService = passwordService; }
public void Arrange() { _configurationService = new Mock <IConfigurationService>(); _passwordProfileRepo = new Mock <IPasswordProfileRepository>(); _passwordService = new PasswordService(_configurationService.Object, _passwordProfileRepo.Object); }
public Rfc2988Benchmark() { var passwordService = new PasswordService(); var settings = new PasswordSettings() {Length = 12, MinimumDigits = 2, MaximumDigits = 4, MaximumUpperCase = 4, MinimumUpperCase = 2, MinimumNonAlphaChars = 2, MaximumNonAlphaChars = 4}; while(passwords.Count < 100) passwords.Add(passwordService.GeneratePassword(settings)); }
public PasswordChanger(AccountConfiguration config, IAccountContext context, AccountRepository repo, PasswordService passServ) { if (config == null) throw new ArgumentNullException("config"); if (context == null) throw new ArgumentNullException("context"); this.context = context; this.repo = new AccountRepositoryWrapper(config.RequireDependency(repo)); this.passServ = config.RequireDependency(passServ); }
public void GenerateCredentials_EmptyPassword_ReturnsNull() { UserEntity user = new UserEntity(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.UserPassword = string.Empty; PasswordService service = new PasswordService(); UserEntity retrieved = service.GenerateCredentials(user); Assert.IsNull(retrieved); }
public EmailChanger(AccountConfiguration config, IAccountContext context, AccountRepository repo, PasswordService passwordService, FormsAuthenticationService formsAuthService) { if (config == null) throw new ArgumentNullException("config"); if (context == null) throw new ArgumentNullException("context"); this.config = config; this.context = context; this.repo = new AccountRepositoryWrapper(config.RequireDependency(repo)); this.passServ = config.RequireDependency(passwordService); this.formsAuthService = config.RequireDependency(formsAuthService); }
public void GenerateCredentials_ValidUserEntity_ReturnedWithFields() { string plaintext = "Password123456789"; UserEntity user = new UserEntity(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.UserPassword = "******"; PasswordService service = new PasswordService(); UserEntity retrieved = service.GenerateCredentials(user); StringAssert.DoesNotMatch(plaintext, retrieved.UserPassword); Assert.NotNull(user.Registered); Assert.NotNull(user.Salt); Assert.NotNull(user.UserPassword); }
public void Test() { var fallback = new PasswordRequirement(0, PasswordService.AlphaChars); var settings = new PasswordSettings(); var passwordLength = 20; var reqs = new[] { new PasswordRequirement(settings.MinimumNonAlphaChars, settings.MaximumNonAlphaChars, settings.IsUsKeyboard ? PasswordService.UsKeyboardNonAlphas : PasswordService.NonAlphas), new PasswordRequirement(settings.MinimumUpperCase, settings.MaximumUpperCase, PasswordService.UpperAlphaChars), new PasswordRequirement(settings.MinimumDigits, settings.MaximumDigits, PasswordService.DigitChars) }; var passwordService = new PasswordService(); byte[] password = passwordService.GeneratePassword(passwordLength, fallback, reqs); Assert.NotNull(password); Assert.Equal(passwordLength, password.Length); foreach (PasswordRequirement req in reqs) { Assert.Equal(req.Required, req.Used); } }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationController"/> class, /// with the provided <paramref name="repo"/>, <paramref name="passwordService"/> and <paramref name="formsAuthService"/>. /// </summary> /// <param name="repo">The account repository.</param> /// <param name="passwordService">The password service.</param> /// <param name="formsAuthService">The forms authentication service.</param> public AuthenticationController(AccountRepository repo, PasswordService passwordService, FormsAuthenticationService formsAuthService) : this(repo, passwordService) { this.formsAuthService = formsAuthService; }
/// <summary> /// Initializes a new instance of the <see cref="ChangeController"/> class, /// with the provided <paramref name="repo"/> and <paramref name="passwordService"/>. /// </summary> /// <param name="repo">The account repository.</param> /// <param name="passwordService">The password service.</param> public ChangeController(AccountRepository repo, PasswordService passwordService) : this() { this.repo = new AccountRepositoryWrapper(repo); this.passServ = passwordService; }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationController"/> class, /// with the provided <paramref name="repo"/> and <paramref name="passwordService"/>. /// </summary> /// <param name="repo">The account repository.</param> /// <param name="passwordService">The password service.</param> public AuthenticationController(AccountRepository repo, PasswordService passwordService) : this() { this.repo = repo; this.passServ = passwordService; }
/// <summary> /// Initializes a new instance of the <see cref="ResetController"/> class, /// with the provided <paramref name="repo"/> and <paramref name="passwordService"/>. /// </summary> /// <param name="repo">The account repository.</param> /// <param name="passwordService">The password service.</param> public ResetController(AccountRepository repo, PasswordService passwordService) : this() { this.repo = repo; this.passServ = passwordService; }
/// <summary> /// Initializes data that might not be available when the constructor is called. /// </summary> /// <param name="requestContext">The HTTP context and route data.</param> protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); this.repo = this.Configuration.RequireDependency(this.repo); this.passServ = this.Configuration.RequireDependency(this.passServ); }
public void VerifyPassword_Length105_ReturnFalse() { PasswordService service = new PasswordService(); bool flag = service.VerifyPassword("TESTestTESTestTESTestTESTestTESTestTESTestTESTESTestTestTESTestTESTestTESTestTESTestTETESTestTESTestSTe23"); Assert.IsFalse(flag); }
public void GenerateSalt_NoParam_ReturnsSalt() { PasswordService service = new PasswordService(); string salt = service.GenerateSalt(); Assert.NotNull(salt); Assert.That(salt.Length >= 128); }
public void VerifyPassword_NoLowerCase_ReturnFalse() { PasswordService service = new PasswordService(); bool flag = service.VerifyPassword("IOJDSFDS23F"); Assert.IsFalse(flag); }
public void VerifyPassword_Length4_ReturnFalse() { PasswordService service = new PasswordService(); bool flag = service.VerifyPassword("Te43"); Assert.IsFalse(flag); }
public void VerifyPassword_NoUpperCase_ReturnFalse() { PasswordService service = new PasswordService(); bool flag = service.VerifyPassword("dsfgdsfljdsg456"); Assert.IsFalse(flag); }
public void VerifyPassword_StrongPassword_ReturnTrue() { PasswordService service = new PasswordService(); bool flag = service.VerifyPassword("JsdffdsD342234"); Assert.IsTrue(flag); }
public void GenerateCredentials_NullUserEntity_ReturnsNull() { PasswordService service = new PasswordService(); UserEntity retrieved = service.GenerateCredentials(null); Assert.IsNull(retrieved); }
public void GeneratePassword_EmptySalt_ReturnsEmpty() { PasswordService service = new PasswordService(); string password = service.GeneratePassword("TestingTest56734500", string.Empty); Assert.AreEqual(string.Empty, password); }
public void GeneratePassword_ValidString_ReturnsString() { PasswordService service = new PasswordService(); string password = service.GeneratePassword("TestingTest56734500", "1LavZgCrOZg2+YPs5EX59NNwP+ZwxfUT6u6dZ3ZkeZB049KHVyTWC8bZ2S2Gp9FYcmxDHZwojXDbyIHehR5z/9P8bVgL6xf6w9G/ybwPosj/ibEKc4iAq7MNiEWjbAB7cAjeTJ+Eeu7KGSenAOFAW9dwS0aWtzmLHxoCG7XgdtE="); Assert.NotNull(password); }