public void TestDecodePassword_Successful() { const string expectedDecodePassword = "******"; var result = PasswordUtils.Decode(testStr); Assert.AreEqual(expectedDecodePassword, result); }
/// <summary> /// Perform database migration<br/> /// 迁移数据库<br/> /// </summary> protected void MigrateDatabase( string database, string connectionString, FluentConfiguration configuration) { // initialize database scheme // flow: // - generate ddl script // - compare to App_Data\nh_{hash}.ddl // - if they are different, upgrade database scheme and write ddl script to file // it can make the website startup faster var fileStorage = Application.Ioc.Resolve <IFileStorage>(); var hash = PasswordUtils.Sha1Sum( Encoding.UTF8.GetBytes(database + connectionString)).ToHex(); var ddlFileEntry = fileStorage.GetStorageFile($"nh_{hash}.ddl"); configuration.ExposeConfiguration(c => { var scriptBuilder = new StringBuilder(); scriptBuilder.AppendLine("/* this file is for database migration checking, don't execute it */"); new SchemaExport(c).Create(s => scriptBuilder.AppendLine(s), false); var script = scriptBuilder.ToString(); if (!ddlFileEntry.Exists || script != ddlFileEntry.ReadAllText()) { var logManager = Application.Ioc.Resolve <LogManager>(); var schemaUpdate = new SchemaUpdate(c); schemaUpdate.Execute(false, true); foreach (var ex in schemaUpdate.Exceptions) { logManager.LogError($"NHibernate schema update error: ({ex.GetType()}) {ex.Message}"); } // Write ddl script to file // Since Nhibernate 5.0 ExposeConfiguration is executed on fly ddlFileEntry.WriteAllText(script); } }); }
public void TestMatchFails() { var slightVariation = _plainPassword.Replace('$', 'S'); var match = PasswordUtils.Match(slightVariation, _salt, _hashedPassword); Assert.IsFalse(match); }
public X509Certificate2 ConvertCertificate(X509Certificate certificate, AsymmetricCipherKeyPair subjectKeyPair, SecureRandom random, string password) { // Now to convert the Bouncy Castle certificate to a .NET certificate. // See http://web.archive.org/web/20100504192226/http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx // ...but, basically, we create a PKCS12 store (a .PFX file) in memory, and add the public and private key to that. var store = new Pkcs12Store(); // What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name". string friendlyName = certificate.SubjectDN.ToString(); // Add the certificate. var certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); // Add the private key. store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); var temporaryPassword = password ?? PasswordUtils.GeneratePassword(12, 6); // Convert it to an X509Certificate2 object by saving/loading it from a MemoryStream. // It needs a password. Since we'll remove this later, it doesn't particularly matter what we use. var stream = new MemoryStream(); store.Save(stream, temporaryPassword.ToCharArray(), random); var convertedCertificate = new X509Certificate2(stream.ToArray(), temporaryPassword, X509KeyStorageFlags.Exportable); return(convertedCertificate); }
public User EditUser(int userId, string passwd, string confirmPasswd, string firstName, string lastName) { User user = db.Users.Find(userId); // Guard block if (user == null) { throw new MembershipCreateUserException("Unable to find User"); } if (!string.IsNullOrEmpty(passwd) && !string.IsNullOrEmpty(confirmPasswd) && passwd.Equals(confirmPasswd)) { string hashedPasswd = PasswordUtils.Sha256(passwd + user.Salt); user.Passwd = hashedPasswd; } if (!string.IsNullOrEmpty(firstName)) { user.FirstName = firstName; } if (!string.IsNullOrEmpty(lastName)) { user.LastName = lastName; } user.UpdateDate = DateTime.Now.Date; db.Users.AddOrUpdate(user); db.SaveChanges(); return(user); }
/// <summary> /// The user Add flow works differently than other adds. After adding the record here, the calling code will also /// generate a token to send to user so they can complete registration. /// </summary> /// <param name="model"></param> /// <param name="userId"></param> /// <returns></returns> //add this layer so we can instantiate the new entity here. public override async Task <int?> Add(UserModel model, UserToken userToken) { //generate random password and then encrypt in here. var password = PasswordUtils.GenerateRandomPassword(_configUtil.PasswordConfigSettings.RandomPasswordLength); User entity = new User { ID = null , Created = DateTime.UtcNow //not actually used during registration but keep it here because db expects non null. //if future, the user sets their own pw on register complete , Password = PasswordUtils.EncryptNewPassword(_configUtil.PasswordConfigSettings.EncryptionSettings, password) }; this.MapToEntity(ref entity, model, userToken); //do this after mapping to enforce isactive is true on add entity.IsActive = true; //this will add and call saveChanges await _repo.AddAsync(entity); model.ID = entity.ID; // Return id for newly added user return(entity.ID); }
public void Update(User userParam, string password = null) { var user = _context.Users.Find(userParam.Id); if (user == null) { throw new AppException("User not found"); } if (userParam.Username != user.Username) { // username has changed so check if the new username is already taken if (_context.Users.Any(x => x.Username == userParam.Username)) { throw new AppException("Username " + userParam.Username + " is already taken"); } } // update user properties user.FirstName = userParam.FirstName; user.LastName = userParam.LastName; user.Username = userParam.Username; // update password if it was entered if (!string.IsNullOrWhiteSpace(password)) { PasswordUtils.CreatePasswordHash(password, out var passwordHash, out var passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; } _context.Users.Update(user); _context.SaveChanges(); }
/// <summary> /// Executes the query /// </summary> /// <returns></returns> public virtual User Execute() { // Make the supplised username lower case and trimmed _email = _email.Trim().ToLower(); // Return the user with the matching username var user = _unitOfWork.Users .Fetch() .Where(x => x.Email == _email) .SingleOrDefault(); // If no user was found, return null if (user == null) { return(null); } // Check if the password is correct if (PasswordUtils.CheckPasswordHash(_email, _password, user.Password)) { return(user); } else { return(null); } }
public async Task <Users> Authen_Validate(string username, string password) { if (username.isNOEOW() || password.isNOEOW()) { throw new ArgumentNullException($"Username or password is required"); } try { var user = await dbSet.Include(x => x.User_Credential).Include(x => x.User_Role).FirstOrDefaultAsync(x => x.email.Equals(username) && x.is_active == true && x.User_Role.is_active == true);// && x.User_Role.role_level > 1); if (user != null) { var policy_db = this.storageContext.Set <Policy_Roles>(); user.User_Role.Policy_Roles = await policy_db.Where(x => x.role_id == user.role_id && x.is_active == true).ToListAsync(); bool check = PasswordUtils.VerifyPasswordHash(user.email, password, user.User_Credential.password_hash, user.User_Credential.password_salt); if (check) { user.User_Role.User = null; user.User_Credential = null; return(user); } } return(null); } catch (Exception) { throw; } }
public void TestEncodPassword_Error_v2() { const string expectedDecodePassword = "******"; var result = PasswordUtils.Encode(testStr); StringAssert.Contains(expectedDecodePassword, result); }
private void InitializeComponent() { _ = this.WhenActivated((CompositeDisposable disposable) => { }); AvaloniaXamlLoader.Load(this); _passwordSection = this.FindControl <StackPanel>("PasswordSection"); _reminderSection = this.FindControl <StackPanel>("ReminderSection"); _bankCartSection = this.FindControl <StackPanel>("BankCartSection"); _personalDataSection = this.FindControl <StackPanel>("PersonalDataSection"); _txtPassword = this.FindControl <TextBox>("txtPassword"); _pbHard = this.FindControl <ProgressBar>("pbHard"); _txtStartTime = this.FindControl <TextBox>("tbStartTime"); _cbType = this.FindControl <ComboBox>("cbType"); _bColor = this.FindControl <Border>("bColor"); _pColorPicker = this.FindControl <Popup>("pColorPicker"); _colorPicker = this.FindControl <ColorPicker>("colorPicker"); _tbColor = this.FindControl <TextBox>("tbColor"); _txtPassword.GetObservable(TextBox.TextProperty).Subscribe(value => PasswordUtils.DeterminingPasswordComplexity(_pbHard, value)); _cbType.SelectionChanged += SectionChanged; _tbColor.Text = ((Color)Application.Current.FindResource("ThemeSelectedControlColor")).ToString(); _argbColorViewModel = new ArgbColorViewModel { Hex = _tbColor.Text }; _pColorPicker.DataContext = _argbColorViewModel; _bColor.Background = new SolidColorBrush(ColorHelpers.FromHexColor(_tbColor.Text)); _colorPicker.ChangeColor += _colorPicker_ChangeColor; }
public void TestEncodPassword_Error() { const string expectedDecodePassword = "******"; var result = PasswordUtils.Encode(testStr); Assert.AreEqual(expectedDecodePassword, result, "Значения не совпали"); }
public void TestEncodePassword_Successful() { const string expectedDecodePassword = "******"; var result = PasswordUtils.Encode(testStr); Assert.AreEqual(expectedDecodePassword, result, "Корректный результат"); }
public void TestDecodePassword_Empty() { const string expectedDecodePassword = ""; var result = PasswordUtils.Decode(testStr); Assert.AreEqual(expectedDecodePassword, result); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { bool isValid = true; User dbUser = DataAccess.GetUserByEmail(loginData.Email); if (dbUser == null) { isValid = false; } else { isValid = PasswordUtils.checkPassword(dbUser.PasswordHash, dbUser.Salt, loginData.Password); } if (!isValid) { ModelState.AddModelError("", "Email or Password is invalid"); return(Page()); } var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, dbUser.Email)); identity.AddClaim(new Claim(ClaimTypes.Name, dbUser.Email)); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.Now.AddHours(2) }); return(RedirectToPage("Index")); } else { ModelState.AddModelError("", "Email or Password fields are blank"); return(Page()); } }
/// <summary> /// Atualiza um usuário. /// </summary> /// <param name="newUserRequest"></param> /// <returns>Token de autenticação em caso de sucesso.</returns> public static AuthResult UpdateUser(NewRequest newUserRequest) { AuthResult authResult = ValidateRequest(newUserRequest, true); if (authResult.AuthStatus == AuthStatus.OK) { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { UserAccountEntity user = AccountRepository.Instance.FindByUserName(newUserRequest.Username); if (!String.IsNullOrWhiteSpace(newUserRequest.Password)) { var security = PasswordUtils.CreateHash(newUserRequest.Password); user.PasswordHash = security.Item2; user.SecurityStamp = security.Item1; } else { user.PasswordHash = user.PasswordHash; user.SecurityStamp = user.SecurityStamp; } if (!String.IsNullOrWhiteSpace(newUserRequest.Email)) { user.UserName = newUserRequest.Email; } AccountRepository.Instance.Update(user); scope.Complete(); } } return(authResult); }
/// <summary> /// Complete user registration /// </summary> /// <param name="id"></param> /// <param name="orgId"></param> /// <returns></returns> public async void CompleteRegistration(int id, string userName, string newPassword) { //get user - match on user id, user name and is active var result = _repo.FindByCondition(u => u.ID.Equals(id) && u.UserName.ToLower().Equals(userName) && u.IsActive) .Include(p => p.UserPermissions) .FirstOrDefault(); if (result == null) { return; } //if (result == null) return null; //only allow completing registration if NOT already completed if (result.RegistrationComplete.HasValue) { // Null value is used on initial creation, therefore null may not be passed into this method. var ex = new InvalidOperationException("User has already completed registration."); _logger.Error(ex); // Log this within all targets as an error. throw ex; // Throw an explicit exception, those using this should be aware this cannot be allowed. } //encrypt and save password w/ profile result.Password = PasswordUtils.EncryptNewPassword(_configUtil.PasswordConfigSettings.EncryptionSettings, newPassword); result.LastLogin = DateTime.UtcNow; result.RegistrationComplete = DateTime.UtcNow; await _repo.UpdateAsync(result); await _repo.SaveChanges(); //return this.MapToModel(result); }
/// <summary> /// Altera a senha de um usuário /// </summary> /// <param name="userId"></param> /// <param name="currentPwd"></param> /// <param name="newPwd"></param> /// <returns></returns> public static AuthResult ChangePassword(int userId, string currentPwd, string newPwd) { AuthResult authResult = new AuthResult(); UserAccountEntity user = AccountRepository.Instance.GetById(userId); if (user == null) { authResult.AuthStatus = AuthStatus.USER_NOT_EXISTS; return(authResult); } //Valida senha bool isValidPassword = PasswordUtils.ValidatePassword(currentPwd, user.SecurityStamp, user.PasswordHash); //Senha inválida if (!isValidPassword) { authResult.AuthStatus = AuthStatus.INVALID_CREDENTIALS; return(authResult); } var security = PasswordUtils.CreateHash(newPwd); user.PasswordHash = security.Item2; user.SecurityStamp = security.Item1; AccountRepository.Instance.Update(user); authResult.UserRoles = AccountRepository.Instance.GetUserRoles(user.Id); return(authResult); }
public User Create(User user, string password, int groupId) { // validation if (string.IsNullOrWhiteSpace(password)) { throw new AppException("Password is required"); } if (_context.Users.Any(x => x.Username == user.Username)) { throw new AppException("Username \"" + user.Username + "\" is already taken"); } PasswordUtils.CreatePasswordHash(password, out var passwordHash, out var passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.GroupId = groupId; _context.Users.Add(user); _context.SaveChanges(); return(user); }
public async Task <IActionResult> Index(IFormCollection collection) { string email = collection["email"]; string password = PasswordUtils.MD5Crypt(collection["password"]); var dbFactory = new AdminDataContextFactory(dataProvider: SQLiteTools.GetDataProvider(), connectionString: ConnectionString); Task <Admin> admin; using (var db = dbFactory.Create()) admin = db.GetTable <Admin>().FirstOrDefaultAsync(c => c.Email.Equals(email) && c.Password.Equals(password)); if (admin.Result != null) { ViewBag.AdminEmail = email; return(View(new DoctorsPatients { Doctors = await DoctorController.Read(), Patients = await PatientCollectionController.Read() })); } else { TempData["ErrorAdminMessage"] = "Mail or password wrong"; return(Redirect("~/signin")); } }
public async Task <(string Error, Session)> Login(string username, string password) { using (var session = _store.OpenSession()) { try { var lowered = username.ToLower(); var user = await session.Query <User>() .Where(x => x.Username == lowered) .FirstOrDefaultAsync(); if (user == null) { return("User is not found.", null); } if (PasswordUtils.Verify(user.PasswordHashed, password) == false) { return("Authentication faild.", null); } return(null, new Session { User = user }); } catch (Exception exp) { Log.Error(exp, string.Empty); return("Unexpected Error.", null); } } }
public object Update(string email, IFormCollection collection) { string oldPassword = PasswordUtils.MD5Crypt(collection["oldPassword"]); string newPassword = PasswordUtils.MD5Crypt(collection["newPassword"]); var dbFactory = new AdminDataContextFactory(dataProvider: SQLiteTools.GetDataProvider(), connectionString: ConnectionString); Task <Admin> admin; using (var db = dbFactory.Create()) { admin = db.GetTable <Admin>().FirstOrDefaultAsync(c => c.Email.Equals(email) && c.Password.Equals(oldPassword)); if (admin.Result != null) { db.Update(new Admin { Email = email, Password = newPassword }); return("Password changed"); } else { return("Old password wrong, or an error occurred."); } } }
public void VerifyPasswordCreation() { var randomText = Guid.NewGuid().ToString(); PasswordUtils.CreatePasswordHash(randomText, out var passwordHash, out var passwordSalt); Assert.IsTrue(PasswordUtils.VerifyPasswordHash(randomText, passwordHash, passwordSalt)); }
public async Task <IActionResult> Register([FromBody] RegisterDto model) { if (ModelState.IsValid) { var newUser = new User() { Email = model.Email, FirstName = model.FirstName, IsActivated = false, LastName = model.LastName, Password = PasswordUtils.HashPassword(model.Password), Role = "User", UserName = model.UserName, CreatedOnUtc = DateTime.Now, Valid = true }; MessageDto result = await _userService.Insert(newUser); if (result.Success) { return(new OkObjectResult(result)); } return(BadRequest(result)); } var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList() .Select(c => c.Select(x => x.ErrorMessage).FirstOrDefault()); return(BadRequest(errors)); }
//protected void ChangePassword1_ChangingPassword(object sender, EventArgs e) //{ // DBAccess ChangePassword = new DBAccess(); // ChangePassword.CommandText = "ChangePassword"; // ChangePassword.AddParameter("@LoginID", Session["LoginID"]); // ChangePassword.AddParameter("@LoginName", Session["LoginName"]); // ChangePassword.AddParameter("@OldPassword", PasswordUtils.encode(ChangePassword1.CurrentPassword.ToString())); // ChangePassword.AddParameter("@NewPassword", PasswordUtils.encode(ChangePassword1.NewPassword.ToString())); // SqlParameter Exist = new SqlParameter(); // Exist.Direction = ParameterDirection.Output; // Exist.SqlDbType = SqlDbType.Int; // Exist.Size = 4; // Exist.ParameterName = "@Exist"; // ChangePassword.AddParameter(Exist); // ChangePassword.ExecuteNonQuery(); // if (Exist.Value.Equals(null) || Exist.Value.Equals(0)) // ChangePassword1.ChangePasswordFailureText = "Old Password is incorrect. Please Try Again."; // else // { // ChangePassword1.SuccessText = "Password Changed."; // ChangePassword1.ChangePasswordFailureText = "Password Changed"; // } // return; //} protected void ChangePassword1_ChangingPassword(object sender, EventArgs e) { if ((ChangePassword1.NewPassword.Length < 6) || (ChangePassword1.ConfirmNewPassword.Length < 6)) { ChangePassword1.ChangePasswordFailureText = "Password must be at least 6 characters long."; return; } else { if (ChangePassword1.CurrentPassword == Session["OldPassword"].ToString()) { DBAccess ChangePassword = new DBAccess(); ChangePassword.CommandText = "ChangePassword"; ChangePassword.AddParameter("@LoginID", Session["LoginID"]); ChangePassword.AddParameter("@LoginName", Session["LoginName"]); ChangePassword.AddParameter("@NewPassword", PasswordUtils.encode(ChangePassword1.NewPassword.ToString())); ChangePassword.ExecuteNonQuery(); ChangePassword1.ChangePasswordFailureText = "Password Changed"; } else { ChangePassword1.ChangePasswordFailureText = "Old Password is Incorrect. Try again."; } } return; }
public async Task <ActionResult <ResponseData> > Auth(RequestData requestData) { if (!ValidationUtils.ValidateEmail(requestData.Email)) { return(BadRequest(new { Message = "Email is invalid" })); } UserRepository userRepository = UserRepository; var user = userRepository.Find(requestData.Email); if (user == null || !PasswordUtils.Verify(requestData.Password, user.PasswordHash)) { return(new UnauthorizedResult()); } var response = new ResponseData() { Id = user.Id, Email = user.Email, Token = JwtUtils.GenerateToken(user, _jwtConfig) }; return(Ok(response)); }
public void TestVerifyPasswordReturnTrueWhenCorrect() { var hashed = PasswordUtils.Hashpassword("aaa"); Assert.NotEqual(hashed, "aaa"); Assert.True(PasswordUtils.Verify(hashed, "aaa")); }
public async Task <ClaimsIdentity> GetClaimsIdentity(LoginDto user) { if (user != null) { if (!string.IsNullOrEmpty(user.UserName) && !string.IsNullOrEmpty(user.Password)) { var userEntity = await _userService.GetUserByUserName(user.UserName); if (userEntity == null) { userEntity = await _userService.GetUserByEmail(user.UserName); } if (userEntity != null) { if (PasswordUtils.VerifyHashedPassword(userEntity.Password, user.Password)) { var roles = new List <string>() { userEntity.Role }; IList <string> claims = new List <string>(); return(await Task.FromResult(GenerateClaimsIdentity(userEntity.UserName, userEntity.Id, roles, claims))); } } } } return(await Task.FromResult <ClaimsIdentity>(null)); }
// Read existing stored values for token secrets & issuers private TokenSettingsFile ReadTokenSettingsFile() { try { // Attempt reading the file using (var reader = new StreamReader(Path.Combine(_config["ConfigFilePath"], JWT_CONFIG_FILENAME))) { return(JsonSerializer.Deserialize <TokenSettingsFile>(reader.ReadToEnd())); } } catch (IOException) { // If any errors, then regenerate the local secrets file // Generate values and serialize object var tokenSettings = new TokenSettingsFile() { Secret = PasswordUtils.GenerateSalt(128), Issuer = Convert.ToBase64String(PasswordUtils.GenerateSalt(64), Base64FormattingOptions.None), Audience = Convert.ToBase64String(PasswordUtils.GenerateSalt(64), Base64FormattingOptions.None) }; // Write new values to file if (!Directory.Exists(_config["ConfigFilePath"])) { Directory.CreateDirectory(_config["ConfigFilePath"]); } var file = File.Create(Path.Combine(_config["ConfigFilePath"], JWT_CONFIG_FILENAME)); using (var writer = new StreamWriter(file, Encoding.UTF8)) { writer.WriteLine(JsonSerializer.Serialize(tokenSettings)); return(tokenSettings); } } }
public void Username_Supplied_Is_Case_Insensitive_And_Trimmed() { // Setup User user1 = new User { Email = "user1", Password = PasswordUtils.CreatePasswordHash("user1", "pass1") }; User user2 = new User { Email = "user2", Password = PasswordUtils.CreatePasswordHash("user2", "pass2") }; User user3 = new User { Email = "user3", Password = PasswordUtils.CreatePasswordHash("user3", "pass3") }; _unitOfWork.Users.Add(user1); _unitOfWork.Users.Add(user2); _unitOfWork.Users.Add(user3); _unitOfWork.Commit(); // Act User result = new UserByCredentialsQuery(_unitOfWork).WithEmail(" USER2 ") .WithPassword("pass2") .Execute(); // Verify Assert.IsNotNull(result, "Query returned a null user"); Assert.AreEqual(user2.Id, result.Id, "Query returned the wrong user"); Assert.AreEqual(user2.Email, result.Email, "Query returned a user with an incorrect email"); }