/// param name="entity">/param> public int Inserir(Pessoa entity) { var NomeExistente = _pessoaRepositorio.SelecionarPorNomeEspecifico(entity.Nome); if (string.IsNullOrEmpty(entity.Nome)) { throw new ConflitoException("Não é permitido uma Pessoa sem nome"); } if (NomeExistente != null) { throw new ConflitoException($"Já existe uma Pessoa cadastrada com este nome {entity.Nome}!"); } var EmailExistente = _pessoaRepositorio.SelecionarPorEmail(entity.Email); if (EmailExistente != null) { throw new ConflitoException($"Já existe uma Pessoa cadastrada com este Email {entity.Email}!"); } if (entity.Id_squad == 0) { entity.Id_squad = null; } entity.Senha = PasswordHash.Create(entity.Senha.ToString()); var IdPessoa = _pessoaRepositorio.Inserir(entity); if (entity.Permissao == 2) { _mentorRepositorio.Inserir(IdPessoa); } return(IdPessoa); }
public bool ChangePassword(string userName, string currentPassword, string newPassword) { if (string.IsNullOrEmpty(userName)) { throw new ArgumentException(Resources.ArgumentNullOrEmpty, "userName"); } var user = this.db.Users.Where(u => u.UserName == userName).SingleOrDefault(); if (user == null) { throw new InvalidOperationException(string.Format(Resources.MembershipUserNotFound, userName)); } if (!PasswordHash.Validate(currentPassword, user.PasswordHash, user.PasswordSalt)) { return(false); } var dateNow = DateTime.UtcNow; var hash = PasswordHash.Create(newPassword); user.PasswordHash = hash.Hash; user.PasswordSalt = hash.Salt; user.LastActivityDate = dateNow; user.LastPasswordChangedDate = dateNow; db.SaveChanges(); return(true); }
public async Task<IActionResult> Login(User user) { if (ModelState.IsValid) { var hashedPassword = PasswordHash.Create(user.Password, user.Username.ToLower()); var dbUser = await _context.Users .FirstOrDefaultAsync(u => u.Username == user.Username && u.Password == hashedPassword); if (dbUser != null) { var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, dbUser.Username), new Claim(ClaimTypes.Role, dbUser.Role) }, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return RedirectToAction("Index", "Quizzes"); } ModelState.AddModelError(string.Empty, "Invalid username/password combination."); } return View("Login"); }
public void RetornaFalseComparacaoHash() { var senha = "123Aa321"; var hash = PasswordHash.Create(senha); var hashTeste = "3a2a61c6a7c01232132118cda"; Assert.NotEqual(hash, hashTeste); }
public void RetornaOkComparacaoHash() { var senha = "123Aa321"; var hash = PasswordHash.Create(senha); var hashTeste = "3a2a61c6a7c040dd9153b7de23018cda"; Assert.Equal(hash, hashTeste); }
public User CreateUser(string userName, string email, string password, string displayName, string providerName = null, string providerUserID = null, string providerUserName = null) { var dateNow = DateTime.UtcNow; var hash = string.IsNullOrEmpty(password) ? PasswordHash.Empty : PasswordHash.Create(password); var user = new User { UserName = userName, Email = email, PasswordHash = hash.Hash, PasswordSalt = hash.Salt, DisplayName = displayName, IsApproved = true, CreatedDate = dateNow, LastLoginDate = dateNow, LastActivityDate = dateNow }; if (db.Users.Where(u => u.UserName == userName).Any()) { this.AddModelError(string.Format("The username '{0}' is already registered.", userName)); return(null); } if (db.Users.Any(u => u.Email == email)) { this.AddModelError(string.Format("A user with email '{0}' is already registered."), email); return(null); } if (!string.IsNullOrWhiteSpace(providerName)) { user.OpenAuthAccounts.Add(new UserOpenAuthAccount { ProviderName = providerName, ProviderUserID = providerUserID, ProviderUserName = providerUserName, LastUsedDate = dateNow }); } try { this.db.Users.Add(user); this.db.SaveChanges(); } catch (DataException ex) { // Username already exists if (ex.InnerException != null && ex.InnerException.InnerException != null && ex.InnerException.InnerException.Message.Contains("UK_User_UserName")) { this.AddModelError(string.Format("The username '{0}' is already registered.", userName)); return(null); } else { throw; } } return(user); }
public void Create_Hashes_Same_Password_Differently_Per_User() { // Act var user1Actual = PasswordHash.Create("password", "testuser1"); var user2Actual = PasswordHash.Create("password", "testuser2"); // Assert Assert.AreNotEqual(user1Actual, user2Actual); }
public ActionResult Index([Bind(Include = "ID,UserName,Password")] LoginModel loginModel) { if (ModelState.IsValid) { Contact user = context.ContactSet .Where(a => a.expl_PortalLogin.Equals(loginModel.UserName)) .Select(row => row).FirstOrDefault(); if (null == user) { TempData["loginError"] = "Nie ma takiego użytkownika."; return(RedirectToAction("Index")); } if (null == user.expl_passwordhash) { TempData["loginError"] = "Użytkownik nie posiada uprawnień do logowania do Portalu."; return(RedirectToAction("Index")); } PasswordHash pHash = PasswordHash.Create(user.expl_salt, user.expl_passwordhash); if (pHash.Verify(loginModel.Password)) { Session["loggedUser"] = loginModel.UserName; Session["guid"] = user.ContactId; Session["userName"] = user.FullName; string check = ""; CreateTree ct = new CreateTree(context, (Guid)user.ContactId); Session["tree"] = check = ct.Html; CreateTreeAdversumSettlement ctas = new CreateTreeAdversumSettlement(context, (Guid)user.ContactId); Session["treeAS"] = ctas.Html; if (check != "") { Session["netUser"] = 1; } else { Session["netUser"] = 0; } return(RedirectToAction("AccountOrContact", "Login")); } TempData["loginError"] = "Błędne hasło."; return(RedirectToAction("Index")); } return(View(loginModel)); }
public void Create_Hashes_A_Password() { // Arrange var expected = "tW4ZMsh7Y2dJisWmumhGu7J1QxMzuqvtbQVA4ipS/zA="; // Act var actual = PasswordHash.Create("password", "testuser"); // Assert Assert.AreEqual(expected, actual); }
public virtual bool AuthenticateAndGenerateToken(LoginModel model, out string token) { if (UserRepository.FindByUsernameAsync(model.Username).Result is TUser user && UserRepository.AuthenticateAsync(user.ID, PasswordHash.Create(user.ID, model.Password)).Result) { token = TokenService.GenerateToken(model.Username); return(true); } token = null; return(false); }
/// <summary> /// /// </summary> /// <param name="userName"></param> /// <param name="pass"></param> /// <param name="newpassword"></param> /// <returns></returns> public bool updateExpirepassword(string userName, string pass, string newpassword) { Int64 addedDays = 0; Guid? user_level_Id = null; Guid? user_id = null; var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["iMFASDataServices"].ConnectionString; var conn = new SqlConnection(connectionString); conn.Open(); var command1 = new SqlCommand("select password,isnull(user_level_Id,newId()) user_level_Id,id from user_info where user_id = '" + userName + "'", conn) { CommandTimeout = 600 }; SqlDataReader oReader1 = command1.ExecuteReader(); while (oReader1.Read()) { pass = oReader1["password"].ToString(); user_level_Id = Guid.Parse(oReader1["user_level_Id"].ToString()); user_id = Guid.Parse(oReader1["id"].ToString()); } oReader1.Close(); var enCrypNewpassword = PasswordHash.Create(newpassword).ToString(); var sqlString = "update user_info set password ='******',passWordCreateDate = '" + DateTime.Now + "',isReset = 0 where password = '******' and user_id ='" + userName + "'"; var command = new SqlCommand(sqlString, conn) { CommandTimeout = 600 }; SqlDataReader oReader = command.ExecuteReader(); oReader.Close(); conn.Close(); var PasswordChanges = new PasswordChangeHistory { Id = Guid.NewGuid(), User_Id = user_id, Branch_Id = user_level_Id, Password = enCrypNewpassword, PasswordChangeDate = DateTime.Now, PrevPassword = pass }; ErpContext.PasswordChangeHistorys.Add(PasswordChanges); ErpContext.SaveChanges(); return(true); }
public EmployeeEditModelProfile() { CreateMap <EmployeeEditModel, Employees>() .ForMember(x => x.PasswordHash, opt => { opt.PreCondition(src => !string.IsNullOrEmpty(src.Password)); opt.MapFrom(src => PasswordHash.Create(src.ID, src.Password)); }); CreateMap <Employees, EmployeeEditModel>() .ForMember(x => x.Password, opt => { opt.Ignore(); }); }
public static User Add(this DbSet <User> users, string userName, string email, string password, string displayName) { var now = DateTime.UtcNow; var pwd = PasswordHash.Create(password); return(users.Add(new User { UserName = userName, Email = email, PasswordHash = pwd.Hash, PasswordSalt = pwd.Salt, DisplayName = displayName, IsApproved = true, CreatedDate = now, LastLoginDate = now, LastActivityDate = now })); }
/// <param name="username"></param> /// <param name="password"></param> public PessoaDto Entrar(string username, string password) { var pwHash = PasswordHash.Create(password); var obj = _autenticacaoRepositorio.Entrar(username, pwHash); if (obj == null) { throw new NaoEncontradoException("Usuário ou senha inválidos !"); } if (!obj.Ativo) { throw new RecusadoException("Esse usuário está desativado no sistema !"); } return(obj); }
public ActionResult Index([Bind(Include = "ID,UserName,OldPassword,Password,ConfirmPassword")] Reset reset) { if (ModelState.IsValid) { Contact user = context.ContactSet .Where(a => a.expl_PortalLogin == reset.UserName) .Select(row => row).FirstOrDefault(); string email = user.EMailAddress1; if (null == email) { Session.RemoveAll(); TempData["loginError"] = "Użytkownik nie posiada przypisanego adresu email w systemie CRM."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } if (null == user) { Session.RemoveAll(); TempData["loginError"] = "Nie ma takiego użytkownika."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } PasswordHash pHash = PasswordHash.Create(reset.Password); PasswordHash pVerify = null; try { pVerify = PasswordHash.Create(user.expl_salt, user.expl_passwordhash); } catch { Session.RemoveAll(); TempData["loginError"] = "Użytkownik nie może w tej chwili resetować hasła."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } if (!pVerify.Verify(reset.OldPassword)) { Session.RemoveAll(); TempData["loginError"] = "Wpisz poprawnie stare hasło."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Reset")); } string emailGuid = (context.ContactSet .Where(a => a.expl_PortalLogin == reset.UserName) .Select(row => row.ContactId).FirstOrDefault()).ToString(); Session[emailGuid] = reset.Password; Session[emailGuid + "_hash"] = pHash.Hash; Session[emailGuid + "_salt"] = pHash.Salt; //string link = "<a href='http://localhost:60774/Reset/ResetPassword" + "?id=" + // emailGuid + "'>Resetuj hasło</a>"; string link = "<a href='" + GetBaseUrl() + "Reset/ResetPassword" + "?id=" + emailGuid + "'>Resetuj hasło</a>"; try { var message = new MailMessage(); message.To.Add(new MailAddress(email)); message.From = new MailAddress(ConfigurationManager.AppSettings["email"]); message.Subject = "Reset hasła"; message.Body = "Link do resetu hasła: " + link; message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = ConfigurationManager.AppSettings["email_username"], Password = ConfigurationManager.AppSettings["email_password"] }; smtp.Credentials = credential; smtp.Host = ConfigurationManager.AppSettings["email_host"]; smtp.Port = Convert.ToInt16(ConfigurationManager.AppSettings["email_smtp_port"]); smtp.EnableSsl = false; smtp.Send(message); TempData["info"] = "Potwierdzajacy email został wysłany na podany adres email."; return(RedirectToAction("Index", "Login")); } } catch (Exception e) { Session.RemoveAll(); TempData["loginError"] = "Wystąpił błąd. Skontaktuj się z administracją."; return(RedirectToAction("Index", "Login")); } } return(View(reset)); }
public HttpResponseMessage createHash() { var h = PasswordHash.Create("001"); return(Request.CreateResponse(HttpStatusCode.OK, h)); }
public ActionResult DoRegistration([Bind(Include = "ID,UserName,Email,Password,ConfirmPassword")] Register reset) { if (ModelState.IsValid) { Contact user = context.ContactSet .Where(a => a.expl_PortalLogin == reset.UserName) .Select(row => row).FirstOrDefault(); if (null == user) { Session.RemoveAll(); TempData["loginError"] = "Nie ma takiego użytkownika."; Session["loggedUser"] = null; return(RedirectToAction("Index", "Login")); } PasswordHash pHash = PasswordHash.Create(reset.Password); string emailGuid = (context.ContactSet .Where(a => a.expl_PortalLogin == reset.UserName) .Select(row => row.ContactId).FirstOrDefault()).ToString(); Session[emailGuid] = reset.Password; Session[emailGuid + "_hash"] = pHash.Hash; Session[emailGuid + "_salt"] = pHash.Salt; string link = "<a href='http://localhost:60774/Reset/ResetPassword" + "?id=" + emailGuid + "'>Resetuj hasło</a>"; try { var message = new MailMessage(); message.To.Add(new MailAddress(reset.Email)); message.From = new MailAddress(""); message.Subject = "Reset hasła"; message.Body = "Link do resetu hasła: " + link; message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = "", Password = "" }; smtp.Credentials = credential; smtp.Host = ""; smtp.Port = 25; smtp.EnableSsl = false; smtp.Send(message); Session.RemoveAll(); TempData["info"] = "Potwierdzajacy email został wysłany na podany adres email."; return(RedirectToAction("Index", "Login")); } } catch (Exception e) { Session.RemoveAll(); TempData["loginError"] = "Wystąpił błąd. Skontaktuj się z administracją."; return(RedirectToAction("Index", "Login")); } } return(View(reset)); }
public void Configure(EntityTypeBuilder <Employees> builder) { builder.Property(x => x.IsActive).HasDefaultValueSql("1"); builder.Property(x => x.Username).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); builder.HasIndex(x => x.Username).IsUnique().IncludeProperties(x => new { x.ID, x.PasswordHash }); builder.HasData(new Employees[] { new Employees() { ID = 1, FullName = "Demo user", Username = "******", PasswordHash = PasswordHash.Create(1, "demo") } }); }