Verify() public static method

verify a password against a hash
public static Verify ( string password, string hashedPassword ) : bool
password string the password
hashedPassword string the hash
return bool
Example #1
0
 public bool ChangePassword(Guid userId, PasswordChangeEntity passwordEntity)
 {
     
     User User = context.Users.FirstOrDefault(u => u.Id.Equals(userId));
     if (User == null) return false;
     if (SecurePasswordHasher.Verify(passwordEntity.OldPassword, User.Password))
     {
         //User newPasswordUser = new User(passwordEntity.UserEntity);
         User.Password = SecurePasswordHasher.Hash(passwordEntity.UserEntity.Password);
         context.SaveChanges();
         return true;
     }
     return false;
 }
Example #2
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (txtNewPass.Text != txtNewPass2.Text)
            {
                MessageBox.Show(@"New Passwords do not match.");
                return;
            }

            var user = User.GetUserFromEmail(txtEmail.Text);

            if (user == null)
            {
                MessageBox.Show(@"Incorrect Username or Password");
                return;
            }
            var result = SecurePasswordHasher.Verify(txtPass.Text, user.PasswordHash);

            if (!result)
            {
                MessageBox.Show(@"Incorrect Username or Password");
                return;
            }

            user.UpdateUser(txtNewPass.Text);
        }
Example #3
0
            public async Task <Response> Handle(Request request, CancellationToken cancellationToken)
            {
                var resetTicket = _session.Query <ResetTicket>()
                                  .FirstOrDefault(x => x.UserEmail == request.Email);

                if (resetTicket == null)
                {
                    throw new NotFoundCoreException();
                }

                if (SecurePasswordHasher.Verify(request.Token, resetTicket.TokenHash) == false)
                {
                    throw new Exception(); //TODO new exception for this error.
                }
                if (resetTicket.TokenUsed)
                {
                    throw new Exception(); //TODO new exception for this error.
                }
                if (resetTicket.ExpirationDate < DateTime.UtcNow)
                {
                    throw new Exception(); //TODO new exception for this error.
                }
                var user = _session.Query <User>()
                           .FirstOrDefault(x => x.Email == resetTicket.UserEmail);

                user?.ResetPassword(request.Password);
                resetTicket.TokenUsed = true;

                _session.Store(resetTicket);
                _session.Store(user);

                return(new Response());
            }
        private async void OnLoginButtonClicked(object sender, EventArgs e)
        {
            if (!VerifyInput())
            {
                return;
            }
            IsBusy = true;

            try
            {
                MyDartBuddy.Common.Entities.Account account = await SelectAccountAsync();

                if (SecurePasswordHasher.Verify(passwordEntry.Text, account.Password))
                {
                    ApplicationData.Current.CurrentAccount = account;
                    await Navigation.PopAsync();
                }
                else
                {
                    messageLabel.Text = "Login has failed. Incorrect password";
                }
            }
            catch (Exception ex)
            {
                messageLabel.Text = $"Login has failed: {ex.Message}";
            }

            IsBusy = false;
        }
Example #5
0
        public IActionResult Mutq(User obj)
        {
            var user = (from item in baza.Users where item.login == obj.login select item).FirstOrDefault();

            if (user == null)
            {
                TempData["Namak"] = "login is wrong";
            }
            else if (user.type == 2)
            {
                TempData["Namak"] = "error";
            }

            else if (SecurePasswordHasher.Verify(obj.password, user.password) == false)
            {
                TempData["Namak"] = "password is wrong";
            }

            else if (user.type == 1)
            {
                HttpContext.Session.SetInt32("test", user.Id);
                return(Redirect("/User/Admin"));
            }
            else
            {
                HttpContext.Session.SetInt32("test", user.Id);
                return(Redirect("/User/Profile"));
            }
            return(View());
        }
Example #6
0
        private void Validation(object sender, System.EventArgs e)
        {
            // if user exist in table, then show the new form
            using (var context = new MyDbContext())
            {
                var userLogin = context
                                .Users
                                .FirstOrDefault(x => x.user_name == _loginForm.GetLogin.Text);
                if (userLogin is null)
                {
                    _loginForm.MyLabel.Visible = true;
                    _loginForm.MyLabel.Text    = "Invalid login.";
                    return;
                }
                if (!SecurePasswordHasher.Verify(_loginForm.GetPassword.Text, userLogin.password))
                {
                    _loginForm.MyLabel.Visible = true;
                    _loginForm.MyLabel.Text    = "Invalid password.";
                    return;
                }
                _loginForm.MyLabel.Visible = false;
                if (userLogin.role == "user")
                {
                    _mainForm.GetInsertButton.Visible   = false;
                    _mainForm.GetDeleteButton.Visible   = false;
                    _mainForm.GetGrid.RowHeadersVisible = false;
                }

                _loginForm.Hide();
                _mainForm.Show();
            }
        }
Example #7
0
        public ActionResult EditLogin(User p)
        {
            p = Session["CurrentUser"] as User;
            string curPass = Request.Params["curPassword"];
            string oldlog  = Request.Params["oldLogin"];
            string newlog  = Request.Params["newLogin"];

            if (!SecurePasswordHasher.Verify(curPass, p.password))
            {
                TempData["msg2"] = "sxal";
                return(Redirect("/User/Edit"));
            }
            else
            {
                var isLoginExist = context.User.Where(y => y.login == newlog).ToList();
                if (isLoginExist.Count > 0)
                {
                    TempData["msg2"] = "Sorry the login is busy";
                    return(Redirect("/User/Edit"));
                }
                p       = context.User.Where(m => m.id == p.id).ToList().First();
                p.login = newlog;
                context.SaveChanges();
                return(Redirect("/User/Profile"));
            }
        }
Example #8
0
        public void CreateUser_UserIsCreated()
        {
            string originalPwd = "somePwd";
            User   userToSave  = new User();

            userToSave.Id          = 1;
            userToSave.Username    = "******";
            userToSave.Email       = "*****@*****.**";
            userToSave.Password    = originalPwd;
            userToSave.Currency    = Models.Enums.Currency.CAD;
            userToSave.PhoneNumber = "51878928";

            List <User> userTable = new List <User>();

            SetupMocks(new List <User>());

            SaveResultModel <User> result = _userService.CreateUser(userToSave);
            User createdUser = _userService.GetUser(userToSave.Id);

            _dataMock.Verify(m => m.Add(It.IsAny <User>()), Times.Once);
            Assert.IsTrue(result.Success);
            Assert.IsNotNull(createdUser);
            Assert.AreEqual(createdUser.Username, userToSave.Username);
            Assert.IsTrue(SecurePasswordHasher.Verify(originalPwd, createdUser.Password));
            Assert.AreEqual(createdUser.Currency, userToSave.Currency);
            Assert.AreEqual(createdUser.PhoneNumber, userToSave.PhoneNumber);
        }
        public async void CreateUser_AddsUserRowIntoDatabase()
        {
            var userName = Guid.NewGuid().ToString();
            var fullName = Guid.NewGuid().ToString();
            var password = Guid.NewGuid().ToString();

            await this._Repository.CreateUser(userName : userName, password : password, fullName : fullName);

            var request = GraphQLQueryManager.GetQueryRequest(
                GraphQLQueryManager.QueryRequest.GetUserByUserName, new
            {
                UserName = userName
            });
            var response = await this._Client.PostAsync(request);

            var users = response.GetDataFieldAs <ICollection <User> >("User");

            Assert.NotEmpty(users);

            var user = users.First();

            Assert.Equal(userName, user.UserName);
            Assert.Equal(fullName, user.FullName);
            Assert.True(SecurePasswordHasher.Verify(password, user.PasswordHash));
        }
Example #10
0
        private bool CheckUserNamePass()
        {
            bool   isSuccessful = false;
            string username     = comboBox1.Text;
            string pass         = textBox1.Text;

            string filename = ".\\Accounts\\" + username + ".xml";

            if (!AccountExists(username))
            {
                MessageBox.Show("There is no account with this name ..."); return(false);
            }
            XmlSerializer       mySerializer        = new XmlSerializer(typeof(List <UserSettings>));
            StreamReader        xmlReader           = new StreamReader(filename);
            List <UserSettings> TestAllUserSettings = new List <UserSettings>();

            TestAllUserSettings = (List <UserSettings>)mySerializer.Deserialize(xmlReader);
            string hash = TestAllUserSettings[0].PassHashCode;

            isSuccessful = SecurePasswordHasher.Verify(pass, hash);
            xmlReader.Close();
            if (!isSuccessful)
            {
                MessageBox.Show("The password you entered is incorrect ...");
            }

            return(isSuccessful);
        }
        public ActionResult UserLogin([Bind] Users user)
        {
            BillingSystemContext context = new BillingSystemContext();
            Users userFromBase           = context.Users.FirstOrDefault(u => u.UserName == user.UserName);

            if (userFromBase != null && SecurePasswordHasher.Verify(user.Password, userFromBase.Password))
            {
                UsersBLL      usersBLL   = new UsersBLL();
                UserClaimsDto userRoles  = usersBLL.GetUserClaims(user.UserName);
                var           userClaims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, userRoles.UserName),
                    new Claim(ClaimTypes.Email, userRoles.Email)
                };

                foreach (RoleMaster rm in userRoles.Roles)
                {
                    userClaims.Add(new Claim(ClaimTypes.Role, rm.RollName));
                }

                var grandmaIdentity = new ClaimsIdentity(userClaims, "User Identity");

                var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity });
                HttpContext.SignInAsync(userPrincipal);

                return(RedirectToAction("Index", "Home"));
            }

            return(View(user));
        }
Example #12
0
        public async Task SecurePasswordHasher_test()
        {
            var hash = SecurePasswordHasher.Hash("2324");
            var v    = SecurePasswordHasher.Verify("2324", hash);

            v.ShouldBeTrue();
        }
Example #13
0
        public async Task <ActionResult <ApplicationUser> > DeleteApplicationUser(int id, ApplicationUser currentUser)
        {
            string cookieValue;

            try
            {
                Request.Cookies.TryGetValue("user_id", out cookieValue);
                if (Convert.ToInt32(cookieValue) != id)
                {
                    return(Unauthorized());
                }
            }
            catch
            {
                return(BadRequest());
            }

            var applicationUser = await _context.ApplicationUsers.FindAsync(id);

            if (applicationUser == null)
            {
                return(NotFound());
            }

            if (!SecurePasswordHasher.Verify(currentUser.password, applicationUser.password))
            {
                return(Unauthorized());
            }

            _context.ApplicationUsers.Remove(applicationUser);
            await _context.SaveChangesAsync();

            Response.Cookies.Delete("user_id");
            return(applicationUser);
        }
Example #14
0
        public async Task <IActionResult> PutPreferences(int id, ApplicationUser applicationUser)
        {
            var userList = _context.ApplicationUsers.Where(u => u.username.Equals(applicationUser.username) && u.Id == id);

            if (!(userList.Count() > 0) || !SecurePasswordHasher.Verify(applicationUser.password, userList.FirstOrDefault().password))
            {
                return(BadRequest());
            }

            var user = userList.FirstOrDefault();

            user.sitePref              = applicationUser.sitePref;
            user.reversePref           = applicationUser.reversePref;
            user.typePref              = applicationUser.typePref;
            user.sortPref              = applicationUser.sortPref;
            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ApplicationUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #15
0
 /// <summary>
 /// Verfies the auth password. Throws an exception if not valid.
 /// </summary>
 /// <param name="auth"></param>
 /// <param name="password"></param>
 private void VerifyAuthPassword(AuthModel auth, string password)
 {
     if (auth == null || !SecurePasswordHasher.Verify(password, auth.Password))
     {
         throw new PasswordException();
     }
 }
Example #16
0
        public HttpResponseMessage PostSignIn([FromBody] User user)
        {
            IEnumerable <DBUser> usrs = db.Users.AsEnumerable().Where(u =>
                                                                      u.Email.Equals(user.Email) &&
                                                                      SecurePasswordHasher.Verify(user.Password, u.PassHash)
                                                                      );

            if (usrs.Count() == 0)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid User", Configuration.Formatters.JsonFormatter));
            }

            DBUser profile = usrs.First();

            if (profile == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid User", Configuration.Formatters.JsonFormatter));
            }
            else
            {
                AuthenticationModule authentication = new AuthenticationModule();
                string token = authentication.GenerateTokenForUser(profile.Email, profile.Id);
                return(Request.CreateResponse(HttpStatusCode.OK, token, Configuration.Formatters.JsonFormatter));
            }
        }
Example #17
0
 public Guest Validate(string username, string password)
 {
     using (var context = new HotelManagementContext())
     {
         return(context.Guests.First(x => x.Username.ToLower() == username && SecurePasswordHasher.Verify(password, x.PasswordHash)));
     }
 }
Example #18
0
        public IActionResult UpdatePassword([FromBody] UpdatePassword updatePassword)
        {
            int?id = User.GetUserId();

            if (id == null)
            {
                return(BadRequest());
            }

            var user = _authHandler.FindById((int)id);

            if (user == null)
            {
                return(BadRequest());
            }

            if (!SecurePasswordHasher.Verify(updatePassword.CurrentPassword, user.PasswordHash))
            {
                ModelState.AddModelError("Fail", "Password is incorrect");
                return(BadRequest(ModelState));
            }

            user.PasswordHash = SecurePasswordHasher.Hash(updatePassword.Password);
            _authHandler.Update(user);
            return(Ok());
        }
Example #19
0
        public OperationResponse Login(LoginModel model)
        {
            var user = _userService.Get(model.Email);

            if (user == null)
            {
                return new OperationResponse()
                       {
                           Success = false, Message = "User not found"
                       }
            }
            ;

            bool isPasswordCorrect = SecurePasswordHasher.Verify(model.Password, user.Password);

            if (!isPasswordCorrect)
            {
                return new OperationResponse()
                       {
                           Success = false, Message = "Invalid password"
                       }
            }
            ;

            var token = GenerateJwtToken(user);

            return(new OperationResponse {
                Success = true, Data = new Dictionary <string, object> {
                    { "token", token }
                }
            });
        }
Example #20
0
        public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _api.GetAsync <UserModel>($"/users/{UserID}");

                if (user != null && SecurePasswordHasher.Verify(model.OldPassword, user.Password))
                {
                    if (model.NewPassword == model.OldPassword)
                    {
                        //New password must be different that current password
                        ModelState.AddModelError("CustomError", $"New password must be different that current password.");
                    }
                    else if (model.NewPassword == model.ConfirmPassword)
                    {
                        user.Password = SecurePasswordHasher.Hash(model.NewPassword);
                        await _api.PutAsync($"/users/{UserID}", user);

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        //passwords did not match
                        ModelState.AddModelError("CustomError", $"Passwords did not match.");
                    }
                }
                else
                {
                    //old password was not correct
                    ModelState.AddModelError("CustomError", $"Password was not correct.");
                }
            }
            return(View(model));
        }
Example #21
0
        public IHttpActionResult Authenticate(User user)
        {
            var loginRequest = new User
            {
                Username = user.Username,
                Password = user.Password
            };

            User databaseUser;

            if (user != null)
            {
                databaseUser = DatabaseAccessModel.GetUserByUsername(loginRequest.Username);

                var isUsernamePasswordValid = SecurePasswordHasher.Verify(loginRequest.Password, databaseUser.Password);

                if (isUsernamePasswordValid)
                {
                    //loginRequest.id = databaseUser.id;
                    loginRequest.Role = databaseUser.Role;
                    //var token = CreateToken(loginRequest.Username);
                    var token = CreateToken(loginRequest.Role, loginRequest.Username);
                    return(Ok(token));
                }
            }
            return(Unauthorized());
        }
        public JsonResult IsValidPassword1(string Password1, string IdPessoa)
        {
            if (Password1 == null)
            {
                return(Json(new string("Password inválida!")));
            }
            Pessoa Pessoa = _context.Pessoas.SingleOrDefault(p => p.NumCC == IdPessoa);

            if (Pessoa == null)
            {
                return(Json(false));
            }
            if (SecurePasswordHasher.Verify(Password1, Pessoa.Password))
            {
                return(Json(new string("A nova password não pode ser igual à sua password antiga!")));
            }
            if (HelperFunctions.IsValidPassword(Password1))
            {
                return(Json(true));
            }
            else
            {
                return(Json(new string("A Password tem de possuir 8 carateres, um carater maiúsculo, um mínusculo e um número!")));
            }
        }
Example #23
0
        public IActionResult ChangeLogin(User obj)
        {
            int?id   = HttpContext.Session.GetInt32("test");
            var data = (from item in baza.Users where item.Id == id select item).FirstOrDefault();

            if (SecurePasswordHasher.Verify(obj.password, data.password) == false)
            {
                TempData["Namak"] = "Password sxal e";
                return(Redirect("/user/ChangeLogin"));
            }
            else
            {
                var log = (from item in baza.Users where item.login == obj.login select item).Count();
                if (log > 0)
                {
                    TempData["Namak"] = "Login@ zbaxvac e";
                    return(Redirect("/user/ChangeLogin"));
                }
                else
                {
                    data.login = obj.login;
                    baza.SaveChanges();
                }
            }

            return(Redirect("/user/Profile"));
        }
        public async Task <LoginResponseDto> Login(LoginDto loginUser)
        {
            var user = await GetByEmail(loginUser.Email);

            if (user == null)
            {
                throw new Exception("Email doesn't exist");
            }

            if (!SecurePasswordHasher.Verify(loginUser.Password, user.PasswordHash))
            {
                throw new Exception("Password incorrect");
            }

            user.LastLoginDate = DateTime.Now;

            await _unitOfWork.SaveChangesAsync();

            var token = GenerateJwtToken(user);

            return(new LoginResponseDto
            {
                Token = token,
                User = _mapper.Map <UserDto>(user)
            });
        }
Example #25
0
        public async Task <User> Login(string userName, string password)
        {
            var request = GraphQLQueryManager.GetQueryRequest(
                GraphQLQueryManager.QueryRequest.GetUserByUserName, new
            {
                UserName = userName
            });
            var response = await this._Client.PostAsync(request);

            var users = response.GetDataFieldAs <ICollection <User> >("User");

            if (!users.Any())
            {
                throw new AccountNotFoundException(userName);
            }

            var user = users.First();

            if (!SecurePasswordHasher.Verify(password, user.PasswordHash))
            {
                throw new WrongPasswordException();
            }

            return(user);
        }
Example #26
0
        public JsonResult IsValidPassword(string Password, string Username)
        {
            if (Password == null)
            {
                return(Json(new string("Password incorrecta!")));
            }
            Pessoa Pessoa = _context.Pessoas.SingleOrDefault(p => p.Username == Username);

            if (Pessoa == null)
            {
                return(Json(false));
            }
            if (String.IsNullOrWhiteSpace(Pessoa.Password))
            {
                if (HelperFunctions.IsValidPassword(Password))
                {
                    return(Json(true));
                }
                else
                {
                    return(Json(new string("A Password tem de possuir 8 carateres, um carater maiúsculo, um mínusculo e um número!")));
                }
            }
            if (SecurePasswordHasher.Verify(Password, Pessoa.Password))
            {
                return(Json(true));
            }
            else
            {
                return(Json(new string("A password está incorrecta!")));
            }
        }
Example #27
0
        public async Task <IActionResult> OnPostAsync(string button)
        {
            if (button != "submit")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                var factors = await _multiFactorUserStore.GetFactorsAsync(user, CancellationToken.None);

                var factorDictionary = new Dictionary <string, ApplicationFactor>();
                foreach (var factor in factors)
                {
                    factorDictionary.Add(factor.Challenge, factor);
                }

                bool challengeResponseValid = true;
                foreach (var inputFactor in Input.Factors)
                {
                    var factor = factorDictionary[inputFactor.Challenge];
                    challengeResponseValid = SecurePasswordHasher.Verify(inputFactor.ChallengeResponse, factor.ChallengeResponseHash);

                    if (!challengeResponseValid)
                    {
                        ModelState.AddModelError(string.Empty, $"{inputFactor.Challenge}: Invalid Challenge Response.");
                    }
                }

                if (challengeResponseValid)
                {
                    // we can now signin.
                    await _signInManager.SignInAsync(user, false, IdentityConstants.ApplicationScheme);

                    return(LocalRedirect(ReturnUrl));
                }
            }


            return(Page());
        }
Example #28
0
        public BucketListSignInResult SignInUser(string email, string password)
        {
            BucketListSignInResult result = new BucketListSignInResult();

            result.Errors = new List <string>();
            User user = _context.Users.Single(x => x.Email == email);

            if (user != null)
            {
                if (SecurePasswordHasher.Verify(password, user.PasswordHash))
                {
                    result.Succeeded = true;
                }
                else
                {
                    result.Errors.Add("Password was incorrect");
                    result.Succeeded = false;
                }
            }
            else
            {
                result.Errors.Add("Couldn't find user");
                result.Succeeded = false;
            }
            return(result);
        }
Example #29
0
        public async Task <IActionResult> Login(Users user)
        {
            string pass = user.Password;

            user = (from item in context.Users where item.Login == user.Login
                    select item)

                   .ToList().FirstOrDefault();
            if (user == null)
            {
                TempData["msg"] = "Login sxal en";
                return(Redirect("/"));
            }
            else
            {
                Users current = user;
                if (!SecurePasswordHasher.Verify(pass, current.Password))
                {
                    //TempData["msg"] = "password sxal en";
                    return(Redirect("/"));
                }
            }
            HttpContext.Session.SetString("user", user.Id.ToString());
            await Authenticate(user.Login);

            return(Redirect("/User/Profile"));
        }
Example #30
0
        public async Task <IActionResult> Login([FromForm] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var dbUser = await _context.User.SingleOrDefaultAsync(c => c.Email == user.Email);

            bool verified = SecurePasswordHasher.Verify(user.Password, dbUser.Password);

            if (verified == true)
            {
                var token = Authentication.GenerateToken(dbUser.Username, _configuration);

                var retVal = new
                {
                    dbUser.UserID,
                    dbUser.Email,
                    dbUser.Username,
                    Token = new JwtSecurityTokenHandler().WriteToken(token)
                };

                return(Ok(retVal));
            }
            else
            {
                return(Unauthorized());
            }
        }