public bool Put(AccountPasswordResetModel model) { using (DatabaseContext context = Util.CreateContext()) { var smsConfirmationCode = (from c in context.SmsConfirmationCodes where c.MobileNumber == model.MobileNumber orderby c.Created descending select c).FirstOrDefault(); if (smsConfirmationCode == null || smsConfirmationCode.ConfirmationCode != model.Code) { return(false); } string salt = PWDTK.GetRandomSaltHexString(); byte[] saltBytes = PWDTK.HashHexStringToBytes(salt); string passwordHash = PWDTK.PasswordToHashHexString(saltBytes, model.Password); var account = (from a in context.Accounts where a.Email == model.MobileNumber || a.Phone == model.MobileNumber select a).FirstOrDefault(); if (account == null) { return(false); } account.Salt = salt; account.PasswordHash = passwordHash; context.SmsConfirmationCodes.Remove(smsConfirmationCode); context.SaveChanges(); return(true); } }
internal Guid CreateAccount(AccountCreateInfo model, bool isAdmin = false) { using (DatabaseContext context = Util.CreateContext()) { string passwordHash = ""; string salt = ""; if (String.IsNullOrEmpty(model.FacebookUserId)) //if not a facebook user, hex password. { salt = PWDTK.GetRandomSaltHexString(); byte[] saltBytes = PWDTK.HashHexStringToBytes(salt); passwordHash = PWDTK.PasswordToHashHexString(saltBytes, model.Password); } string role = isAdmin ? "Administrator" : "User"; Account account = new Account { Guid = Guid.NewGuid(), Username = model.Username, FacebookUserId = model.FacebookUserId, Salt = salt, PasswordHash = passwordHash, Roles = JsonConvert.SerializeObject(new string[] { role }), Phone = model.Phone, LanguageCode = model.LanguageCode, IsActive = true, Created = DateTime.UtcNow, LastLogin = DateTime.UtcNow }; context.Accounts.Add(account); context.SaveChanges(); return(account.Guid); } }
public bool VerifyCredentials(VerifyCredentialsRequest model) { if (model == null || String.IsNullOrEmpty(model.Username) || String.IsNullOrEmpty(model.Password)) { throw new HttpResponseException(HttpStatusCode.BadRequest); } using (DatabaseContext context = new DatabaseContext()) { Account account = (from a in context.Accounts where model.Username == a.Username || model.Username == a.FacebookUserId select a).FirstOrDefault(); if (account == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); } //test access token login if (model.Username == account.FacebookUserId) { return(FacebookVerifyCredentials(account.FacebookUserId, model.Password)); } //user has facebook account, but attempting password. if (model.Username == account.Username && !String.IsNullOrEmpty(account.FacebookUserId)) { return(false); } var saltBytes = PWDTK.HashHexStringToBytes(account.Salt); var passwordBytes = PWDTK.HashHexStringToBytes(account.PasswordHash); return(PWDTK.ComparePasswordToHash(saltBytes, model.Password, passwordBytes)); } }
public bool ComparePassword(string password, string hash, string salt) { Hash = PWDTK.HashHexStringToBytes(hash); Salt = PWDTK.HashHexStringToBytes(salt); return(PWDTK.ComparePasswordToHash(Salt, password, Hash, iterations)); }
private void CbUser_ChangeItem() { try { var pass = from p in _db where p.UserName == CbUser_SelectedItem select p; cmdEdit_IsEnabled = true; cmdEditPass_IsEnabled = true; cmdCancel_IsEnabled = true; cmdAdd_IsEnabled = false; cmdDelete_IsEnabled = true; Password_IsEnabled = false; Password_Cls_Visibility = Visibility.Hidden; cambiarPassword_IsChecked = false; //A autorizarLotes_IsChecked = false; //B procesarLotes_IsChecked = false; //C verElector_IsChecked = false; //D reportes_IsChecked = false; //E reversarLote_IsChecked = false; //F configuraciones_IsChecked = false; //G corregirEndosos_IsChecked = false; //H _AreasDeAcceso = new string[9]; foreach (var pss in pass) { Byte[] hash = PWDTK.HashHexStringToBytes(pss.PasswordHash); password_Cls = PWDTK.HashBytesToHexString(hash); // Helper.PasswordHash.HashPasswordDecrypt(pss.PasswordHash); // Helper.PasswordHash.Decrypt(pss.PasswordHash); verificacionPassword_Cls = password_Cls; //_Id = pss.UserId; Id = pss.UserId.ToString(); foreach (char c in pss.AreasDeAcceso.ToCharArray()) { switch (c) { case 'A': _AreasDeAcceso[1] = "A"; cambiarPassword_IsChecked = true; break; case 'B': _AreasDeAcceso[2] = "B"; autorizarLotes_IsChecked = true; break; case 'C': _AreasDeAcceso[3] = "C"; procesarLotes_IsChecked = true; break; case 'D': _AreasDeAcceso[4] = "D"; verElector_IsChecked = true; break; case 'E': _AreasDeAcceso[5] = "E"; reportes_IsChecked = true; break; case 'F': _AreasDeAcceso[6] = "F"; reversarLote_IsChecked = true; break; case 'G': _AreasDeAcceso[7] = "G"; configuraciones_IsChecked = true; break; case 'H': _AreasDeAcceso[8] = "H"; corregirEndosos_IsChecked = true; break; } } } } catch (Exception ex) { MethodBase site = ex.TargetSite; MessageBox.Show(ex.Message, site.Name, MessageBoxButton.OK, MessageBoxImage.Error); } }
private void MyOK_Click(object param) { MiCursor = Cursors.Wait; try { if (txtUserName_txt != "Applica") { PasswordBox passwordBox = param as PasswordBox; txtPassword_txt = passwordBox.Password; ObservableCollection <Users> db = new ObservableCollection <Users>(); using (SqlExcuteCommand get = new SqlExcuteCommand() { DBCnnStr = DBEndososCnnStr }) { _MyUsersTable = get.MyGetUsers(); foreach (DataRow r in _MyUsersTable.Rows) { Users mUsers = new Users(); mUsers.UserId = (Guid)r["UserId"]; mUsers.UserName = r["UserName"].ToString(); mUsers.PasswordHash = r["PasswordHash"].ToString(); mUsers.SecurityStamp = r["SecurityStamp"].ToString(); mUsers.AreasDeAcceso = r["AreasDeAcceso"].ToString(); db.Add(mUsers); } } var user = from u in db where u.UserName == txtUserName_txt select new { passwordHash = u.PasswordHash, salt = u.SecurityStamp, acceso = u.AreasDeAcceso, id = u.UserId }; if (user.Count() == 0) { throw new Exception("Error con el usuario o el password."); } // if (!PasswordMeetsPolicy(txtPassword_txt, PwdPolicy)) return; string hashedPassword = user.First().passwordHash; _salt = PWDTK.HashHexStringToBytes(user.First().salt); _hash = PWDTK.HashHexStringToBytes(hashedPassword); if (!PWDTK.ComparePasswordToHash(_salt, txtPassword_txt, _hash, iterations)) { throw new Exception("Error con el password."); } WhatIsUserName = "******" + txtUserName_txt; _AreasDeAcceso = user.First().acceso; _Id = user.First().id; } else { WhatIsUserName = "******"; _AreasDeAcceso = "ABCDEFGH"; _Id = Guid.NewGuid(); } //"Aspirante = 1" //"Partido = 2" if (isRdbCandidato) { WhatIsModo = 1; } else if (isRdbPartido) { WhatIsModo = 2; } else { WhatIsModo = 0; } this.View.DialogResult = true; this.View.Close(); } catch (Exception ex) { MethodBase site = ex.TargetSite; MessageBox.Show(ex.Message, site.Name, MessageBoxButton.OK, MessageBoxImage.Error); } finally { MiCursor = Cursors.Arrow; } }
/* * protected void btnLogin_Click(object sender, EventArgs e) { * if (Membership.ValidateUser(tbUserName.Text, tbPassword.Text)) { * if(string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) { * FormsAuthentication.SetAuthCookie(tbUserName.Text, false); * Response.Redirect("~/"); * } * else * FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false); * } * else { * tbUserName.ErrorText = "Invalid user"; * tbUserName.IsValid = false; * } * } */ protected void ASPxButtonLogin_Click(object sender, EventArgs e) { Page.Validate(); if (!Page.IsValid) { return; } if (string.IsNullOrEmpty(recaptchaUserValue.Value)) { Msg.Visible = true; Msg.InnerHtml = "Error en los datos de seguridad, vuelva a recargar la página."; return; } var Recaptchav3 = new RecaptchaVerificationHelper(); // If your site is behind CloudFlare, be sure you're suing the CF-Connecting-IP header value instead: // https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers RecaptchaVerificationResult recaptchaResult = Recaptchav3.VerifyRecaptchav3Response( Global.Configuration.Security.Google.Recaptcha.v3.GetGoogleRecaptchaSecretKey() , Global.Configuration.Security.Google.Recaptcha.v3.GetGoogleRecaptchaWebsiteKey() , Request.UserHostAddress , recaptchaUserValue.Value ); if (recaptchaResult == RecaptchaVerificationResult.Success) { //divMessage.InnerHtml = "Score: " + Recaptchav3.Score; decimal?minScore = new decimal(0.6); if (Recaptchav3.Score < minScore) { Response.Redirect("~/Captcha.aspx", true); } //create session // Global.Sessions.UserCreateSession(); // Go main menu. if (ValidateLogin()) { HttpCookie userid = new HttpCookie("User.Email", Email.Value.ToString()) { Expires = DateTime.Now.AddYears(1) }; Response.Cookies.Add(userid); Response.Redirect("~/recursos/"); } else { Msg.Visible = true; } Msg.InnerHtml = "Login fallido. Por favor revise sus datos e intente de nuevo."; } else { Msg.Visible = true; Msg.InnerHtml = "Existe un problema para validar la seguridad, intente mas tarde o por favor contacte a soporte técnico."; } bool ValidateLogin() { bool loginOK = false; string salt = string.Empty, encrypass = string.Empty, dbpassword = string.Empty; SqlParameter[] parameters = { new SqlParameter { ParameterName = "Email", DbType = DbType.AnsiString, Size = 50, Value = Email.Value.ToString() } }; string tsql = @" SELECT TOP 1 [UserRegisterID] ,[Names] ,[LastName] ,[Email] ,[Password] ,[PasswordSalt] FROM [CMSUserRegister] WHERE Email = @Email ORDER BY [UserRegisterID] DESC ;"; var sqlserver = new SqlApiSqlClient(); using (sqlserver.Connection = new SqlConnection(Global.Configuration.DB.GetConnectionStringDBMain())) { using (var dr = sqlserver.DataReaderSqlString(tsql, parameters)) { if (dr.Read()) { salt = dr["PasswordSalt"].ToString();; dbpassword = dr["Password"].ToString();; Byte[] _salt; Byte[] _hash; //This is the password policy that all passwords must adhere to, if the password doesn't meet the policy we save CPU processing time by not even bothering to calculate hash of a clearly incorrect password PWDTK.PasswordPolicy PwdPolicy = new PWDTK.PasswordPolicy(numberUpper, numberNonAlphaNumeric, numberNumeric, minPwdLength, maxPwdLength); //or we can just use the default password policy provided by the API like below //PWDTK.PasswordPolicy PwdPolicy = PWDTK.cDefaultPasswordPolicy; _salt = PWDTK.HashHexStringToBytes(salt); // reverse operation ; //Generate the hash value _hash = PWDTK.PasswordToHash(_salt, Password.Value.ToString(), iterations); encrypass = PWDTK.HashBytesToHexString(_hash); if (encrypass == dbpassword) { loginOK = true; // Session["User.UserEmail"] = dr["UserEmail"].ToString(); } else { loginOK = false; } } else { loginOK = false; } dr.Close(); } sqlserver.Connection.Close(); }; if (loginOK) { return(true); } else { return(false); } } }