Exemplo n.º 1
0
        /// <summary>
        /// Repeated logic from SetNewPassword.
        ///
        /// Pass it a resetToken to destroy on success (if user is anonymous).
        ///
        /// Returns null if everything is OK, and an ActionResult if an error occurred.
        /// </summary>
        private ActionResult ChangePasswordAndSendEmail(string password, string password2, string token, PasswordReset resetToken, User user, DateTime now)
        {
            string message;

            if (!Password.CheckPassword(password, password2, user.Email, user.VanityProviderId, user.ProviderId, out message))
            {
                return(RecoverableError(message, new { token }));
            }

            user.ChangePassword(now, password);

            if (resetToken != null)
            {
                Current.WriteDB.PasswordResets.DeleteOnSubmit(resetToken);
            }

            Current.WriteDB.SubmitChanges();

            var account = SafeRedirect((Func <ActionResult>)(new UserController()).ViewUser);

            if (!Current.Email.SendEmail(user.Email, Email.Template.PasswordChanged, new { AccountLink = Current.Url(account.Url).AsLink() }))
            {
                return(IrrecoverableError("An error occurred sending the email", "This has been recorded, and will be looked into shortly"));
            }

            return(null);
        }
Exemplo n.º 2
0
        public bool IsValidUser(string email, string password)
        {
            UserModel user = _dbService.GetUserByEmail(email);

            if (user == null)
            {
                return(false);
            }
            return(Password.CheckPassword(password, user.Salt, user.Password));
        }
Exemplo n.º 3
0
        public void ValidPasswords()
        {
            string ignored;

            Assert.IsTrue(Password.CheckPassword("Password1234-", "Password1234-", "*****@*****.**", "blah.so", null, out ignored));
            Assert.IsTrue(Password.CheckPassword("!@#$asdF6-", "!@#$asdF6-", "*****@*****.**", "blah.so", null, out ignored));
            Assert.IsTrue(Password.CheckPassword("Password1234", "Password1234", "*****@*****.**", "blah.so", null, out ignored));
            Assert.IsTrue(Password.CheckPassword("-password1234", "-password1234", "*****@*****.**", "blah.so", null, out ignored));
            Assert.IsTrue(Password.CheckPassword("-Password", "-Password", "*****@*****.**", "blah.so", null, out ignored));
        }
Exemplo n.º 4
0
        public ActionResult SendEmailVerficationToken(string email, string password, string password2, string realname)
        {
            if (email.IsNullOrEmpty())
            {
                return(RecoverableError("Email is required", new { realname }));
            }
            if (!Models.User.IsValidEmail(ref email))
            {
                return(RecoverableError("Email is not valid", new { email, realname, password, password2 }));
            }

            // Check that the captcha succeeded
            string error;

            if (!Captcha.Verify(Request.Form, out error))
            {
                return(RecoverableError(error, new { email, realname }));
            }

            string message;

            if (!Password.CheckPassword(password, password2, email, null, null, out message))
            {
                return(RecoverableError(message, new { email, realname }));
            }

            string token, authCode;

            if (!PendingUser.CreatePendingUser(email, password, realname, out token, out authCode, out error))
            {
                return(RecoverableError(error, new { email, realname, password, password2 }));
            }

            var toComplete =
                SafeRedirect(
                    (Func <string, string, string, string, ActionResult>)CompleteRegistration,
                    new
            {
                token,
                email,
                realname,
                authCode
            }
                    );

            var completeLink = Current.Url(toComplete.Url);

            if (!Current.Email.SendEmail(email, Email.Template.CompleteRegistration, new { RegistrationLink = completeLink.AsLink() }))
            {
                return(IrrecoverableError("An error occurred sending the email", "This has been recorded, and will be looked into shortly"));
            }

            return(SuccessEmail("Registration Email Sent to " + email, "Check your email for the link to complete your registration"));
        }
Exemplo n.º 5
0
        public void CheckPassword_PasswordAndEncryptedPasswordShouldBeSame()
        {
            //Arrange
            var password          = "******";
            var encryptedPassword = Password.EncryptPassword(password);
            //Act
            bool result = Password.CheckPassword(password, encryptedPassword);

            //Assert
            result.Should().BeTrue();
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            Console.WriteLine(Password.CheckPassword("$Alphes"));

            Console.WriteLine(Password.CheckPassword("@John123"));

            Console.WriteLine(Password.CheckPassword("Sami&123"));

            Console.WriteLine(Password.CheckPassword("Aum Chant"));

            Console.WriteLine(Password.CheckPassword("abracaDabrabra"));

            bool result = Password.CheckPassword("Smith");

            Console.WriteLine(result);
        }
Exemplo n.º 7
0
        public ActionResult CompleteTrustedPasswordRecovery(string email, string resetToken, string password)
        {
            if (!CurrentAffiliate.IsTrusted)
            {
                return(NotFound());
            }

            if (!Models.User.IsValidEmail(ref email))
            {
                return(ApiFailure("Invalid email [" + email + "]"));
            }

            var user = Models.User.FindUserByEmail(email);

            if (user == null)
            {
                return(ApiFailure("No user found with email [" + email + "]", (int)HttpStatusCode.NotFound));
            }

            var hash = Current.WeakHash(resetToken);
            var t    = Current.WriteDB.PasswordResets.Where(p => p.TokenHash == hash).SingleOrDefault();

            if (t == null)
            {
                return(ApiFailure("Could not find a pending password reset request."));
            }

            if (t.UserId != user.Id)
            {
                return(ApiFailure("Token user doesn't match email user"));
            }

            string errorMessage;

            if (!Password.CheckPassword(password, password, email, user.VanityProviderId, user.ProviderId, out errorMessage))
            {
                return(ApiFailure(errorMessage));
            }

            user.ChangePassword(Current.Now, password, "via " + CurrentAffiliate.DisplayableHostFilter);

            // Don't let that token be used twice.
            Current.WriteDB.PasswordResets.DeleteOnSubmit(t);
            Current.WriteDB.SubmitChanges();

            return(ApiSuccess());
        }
Exemplo n.º 8
0
        public void PasswordShouldHave1LowerCaseChar()
        {
            var  input    = "CACTUS";
            bool expected = false;
            bool actual   = Password.CheckPassword(input);
            bool test;

            if (expected.Equals(actual))
            {
                test = true;
            }
            else
            {
                test = false;
            }
            Assert.IsTrue(test, "Password should contain one lower case character");
        }
Exemplo n.º 9
0
        public void PasswordShouldHaveNoWhiteSpace()
        {
            var  input    = "alPhas ";
            bool expected = false;
            bool actual   = Password.CheckPassword(input);
            bool test;

            if (expected.Equals(actual))
            {
                test = true;
            }
            else
            {
                test = false;
            }
            Assert.IsTrue(test, "Password string cannot have white space");
        }
Exemplo n.º 10
0
        public void PasswordLengthShouldNotBeMoreThan12Chars()
        {
            var  input    = "passwordalpha";
            bool expected = false;
            bool actual   = Password.CheckPassword(input);
            bool test;

            if (expected.Equals(actual))
            {
                test = true;
            }
            else
            {
                test = false;
            }
            Assert.IsTrue(test, "Length of the Password string cannot be more than 12 characters");
        }
Exemplo n.º 11
0
        public void PasswordShouldHave1SpecialChar()
        {
            var  input    = "$Smithonian";
            bool expected = true;
            bool actual   = Password.CheckPassword(input);
            bool test;

            if (expected.Equals(actual))
            {
                test = true;
            }
            else
            {
                test = false;
            }
            Assert.IsTrue(test, "Password Should have 1 Special character");
        }
Exemplo n.º 12
0
        public void PasswordShouldNotHaveTwoSimilarCharactersConsecutively()
        {
            var  input    = "Tomorrow";
            bool expected = false;
            bool actual   = Password.CheckPassword(input);
            bool test;

            if (expected.Equals(actual))
            {
                test = true;
            }
            else
            {
                test = false;
            }
            Assert.IsTrue(test, "Password string cannot have two similar characters consecutively");
        }
Exemplo n.º 13
0
        public void InvalidPasswords()
        {
            string msg;

            Assert.IsFalse(Password.CheckPassword("password", "Password", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("Password", "Password", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("password", "password", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("12345678", "12345678", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("Pass1234", "Pass1234", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("1234!@#$", "1234!@#$", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("pP1-", "pP1-", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("pass!@#$", "pass!@#$", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("PASS!@#$", "PASS!@#$", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("*****@*****.**", "*****@*****.**", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("eMail1234@", "eMail1234@", "*****@*****.**", "blah.so", null, out msg));
            Assert.IsNotNull(msg);

            Assert.IsFalse(Password.CheckPassword("Indeed.1234", "Indeed.1234", "*****@*****.**", "so.Indeed.1234.go", null, out msg));
            Assert.IsNotNull(msg);

            var guid = Guid.NewGuid();

            Assert.IsFalse(Password.CheckPassword(guid.ToString(), guid.ToString(), "*****@*****.**", "hello", guid, out msg));
            Assert.IsNotNull(msg);
        }
Exemplo n.º 14
0
        public IActionResult ChangePassword([FromBody] ChangePasswordModel model)
        {
            try
            {
                var connectionString = _configuration.GetConnectionString("LaboratoryBookConnectionString");

                var userIdstr = HttpContext
                                .User
                                .Claims
                                .First(claim => claim.Type == "UserId").Value;
                var userId = int.Parse(userIdstr);

                var checkOldPasswordResult = Password.CheckPassword(
                    connectionString,
                    userId,
                    model.oldPassword);

                if (!checkOldPasswordResult.Item1)
                {
                    return(BadRequest(new { message = checkOldPasswordResult.Item2 }));
                }

                var setNewPasswordResult = Password.SetNewPassword(
                    connectionString,
                    userId,
                    model.newPassword);

                if (setNewPasswordResult)
                {
                    return(Ok(new { message = "Password changed" }));
                }
                else
                {
                    return(BadRequest(new { message = "Password was not changed" }));
                }
            }
            catch (Exception exception)
            {
                return(StatusCode(
                           StatusCodes.Status500InternalServerError,
                           new { message = exception.Message }));
            }
        }
Exemplo n.º 15
0
        public async Task <AuthResult> LoginAsync(string email, string password)
        {
            var existUser = await Task.Run(() => userRepository.FindByEmail(email));

            if (existUser == null)
            {
                return(new AuthResult
                {
                    Errors = new[] { "No such user" }
                });
            }

            if (Password.CheckPassword(password, existUser.Salt, existUser.Password))
            {
                var authClaims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, existUser.Name),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, existUser.Email)
                };

                var token = new JwtSecurityToken(
                    _authOptions.Issuer,
                    _authOptions.Audience,
                    expires: DateTime.Now.AddMinutes(_authOptions.ExpiresInMinutes),
                    claims: authClaims,
                    signingCredentials: new SigningCredentials(
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authOptions.Securekey)), SecurityAlgorithms.HmacSha256Signature)
                    );
                return(new AuthResult
                {
                    Success = true,
                    Token = new JwtSecurityTokenHandler().WriteToken(token)
                });
            }
            return(new AuthResult
            {
                Errors = new[] { "Wrong password" }
            });
        }
Exemplo n.º 16
0
 private void loginButton_Click(object sender, EventArgs e)
 {
     if (usernameTextBox.Text == "" || passwordTextBox.Text == "")
     {
         MessageBox.Show("Username/Password cannot be empty.");
         return;
     }
     user = Reusable.CheckUserModel(_myContext, usernameTextBox.Text);
     if (user == null)
     {
         MessageBox.Show("Wrong username/password.");
         return;
     }
     if (Password.CheckPassword(passwordTextBox.Text, user.Password))
     {
         MessageBox.Show("Successfully Logged in as " + user.UserName + "!");
         DialogResult = DialogResult.OK;
     }
     else
     {
         MessageBox.Show("Wrong username/password.");
     }
 }
Exemplo n.º 17
0
 IServerAdmin IServerBase.GetServerAdmin(Password password)
 {
     Password serverPassword;
     try
     {
         serverPassword = new Password(Config.Instance.GetIntegerList("Server.AdminPassword").ToArray());
     }
     catch(ArgumentOutOfRangeException)
     {
         serverPassword = new Password("");
     }
     if(!serverPassword.CheckPassword(password))
         throw new BadServerPasswordException();
     return admin;
 }
Exemplo n.º 18
0
        public static async Task Login(HttpContext httpContext, LoginData loginData)
        {
            var captchaResponse = await Captcha.ValidateCaptcha(loginData.Captcha, httpContext.Connection.RemoteIpAddress.ToString());

            if (!captchaResponse.Success)
            {
                await httpContext.Response.SendRequestErrorAsync(403, "Invalid captcha.", captchaResponse.ErrorMessage);

                return;
            }

            await using var context = new DatabaseContext();

            var account = await(from a in context.Accounts where a.Email.Equals(loginData.Email) select a).FirstOrDefaultAsync();

            if (account == null)
            {
                await httpContext.Response.SendRequestErrorAsync(4, "There is no account registered with this email.");

                return;
            }

            /*
             * if (!account.Active) {
             *  await httpContext.Response.SendRequestErrorAsync(5, "You need to confirm your email before logging in.");
             *  return;
             * }
             *
             * if (account.Banned) {
             *  var accountBan = await (from a in context.AccountBans where a.AccountId.Equals(account.Id) select a).FirstOrDefaultAsync();
             *  if (accountBan == null) {
             *      await httpContext.Response.SendRequestErrorAsync(6, "This account is banned but it was not possible to obtain the reason, this may be a failure, please contact support.");
             *      return;
             *  }
             *  await httpContext.Response.SendRequestErrorAsync(7, $"This account is banned. Ban ID: #{accountBan.Id}, Reason: {accountBan.Reason}", new {
             *      id = accountBan.Id.ToString(),
             *      reason = accountBan.Reason
             *  });
             *  return;
             * }*/

            if (await Password.CheckPassword(account.Password, loginData.Password))
            {
                try {
                    account.LastAccess = DateTime.UtcNow;
                    context.Accounts.Update(account);
                    await context.SaveChangesAsync();

                    httpContext.Session.Set("account", account.Id);
                    await httpContext.Session.CommitAsync();

                    await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { success = true, token = httpContext.Session.Id, account = new AccountView(account) }));
                } catch (Exception ex) {
                    HtcPlugin.Logger.LogError(ex);
                    await httpContext.Response.SendInternalErrorAsync(8, "An internal failure occurred while attempting to create the account. Please try again later.");
                }
            }
            else
            {
                await httpContext.Response.SendRequestErrorAsync(9, "The password is incorrect.");
            }
        }
        public async void ChangePassowrdCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (PbxNewPassword.Password != PbxRepeatPassword.Password)
            {
                MessageBox.Show(
                    "New password and repeat password do not match",
                    "Set new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return;
            }

            if (PbxNewPassword.Password.Length < 6)
            {
                MessageBox.Show(
                    "New password should have more than 5 symbols",
                    "Set new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return;
            }

            var user        = this.LaboratoryBookUser;
            var password    = this.PbxOldPassword.Password;
            var newPassword = this.PbxNewPassword.Password;

            var checkOldPasswordTask = new Task <Tuple <bool, string> >(() => Password.CheckPassword(user.GetUserID(), password));
            var checkPasswordResult  = new Tuple <bool, string>(false, "null");

            try
            {
                checkOldPasswordTask.Start();
                checkPasswordResult = await checkOldPasswordTask;
            }
            catch (Exception exception)
            {
                MessageBox.Show(
                    exception.Message,
                    "Set new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

            if (checkPasswordResult.Item1 == false)
            {
                MessageBox.Show(
                    "Old password does not match",
                    "Ser new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return;
            }

            var setNewPasswordTask   = new Task <bool>(() => Password.SetNewPassword(user.GetUserID(), newPassword));
            var setNewPasswordResult = false;

            try
            {
                setNewPasswordTask.Start();
                setNewPasswordResult = await setNewPasswordTask;
            }
            catch (Exception exception)
            {
                MessageBox.Show(
                    exception.Message,
                    "Set new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

            if (setNewPasswordResult == true)
            {
                MessageBox.Show(
                    "Password was successfully changed!",
                    "Set new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(
                    "Password was not changed",
                    "Set new password error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
Exemplo n.º 20
0
 public void GoodPasswordTest1()
 {
     Password.SetPassword("MAMA");
     Assert.IsTrue(Password.CheckPassword("MAMA"));
 }
Exemplo n.º 21
0
 public void FalsePasswordTest2()
 {
     Password.SetPassword("MAMA");
     Assert.IsFalse(Password.CheckPassword("papa"));
 }
Exemplo n.º 22
0
        public ActionResult SignupIFrameSubmit(string email, string password, string password2, string realname, string background, string color)
        {
            if (email.IsNullOrEmpty())
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = "Email is required";
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["realname"]      = realname;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            if (!Models.User.IsValidEmail(ref email))
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = "Email is not valid";
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["realname"]      = realname;
                ViewData["email"]         = email;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            // Check that the captcha succeeded
            string error;

            if (!Captcha.Verify(Request.Form, out error) || !Password.CheckPassword(password, password2, email, null, null, out error))
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = error;
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["email"]         = email;
                ViewData["realname"]      = realname;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            var cookie = System.Web.HttpContext.Current.CookieSentOrReceived(Current.AnonymousCookieName);

            var callback = Current.GetFromCache <string>(CallbackKey(cookie));

            string token, authCode;

            if (!PendingUser.CreatePendingUser(email, password, realname, out token, out authCode, out error))
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = error;
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["email"]         = email;
                ViewData["realname"]      = realname;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            var complete =
                SafeRedirect(
                    (Func <string, string, string, string, string, string, ActionResult>)
                        (new AccountController()).CompleteAffiliateTriggeredRegistration,
                    new
            {
                email,
                affId = CurrentAffiliate.Id,
                token,
                callback,
                realname,
                authCode
            }
                    );

            var completeLink = Current.Url(complete.Url);

            string affName = CurrentAffiliate.HostFilter;
            Uri    callbackUri;

            if (Uri.TryCreate(callback, UriKind.Absolute, out callbackUri))
            {
                affName = callbackUri.Host;
            }

            var success =
                Current.Email.SendEmail(
                    email,
                    Email.Template.CompleteRegistrationViaAffiliate,
                    new {
                AffiliateName    = affName,
                RegistrationLink = completeLink.AsLink()
            });

            if (!success)
            {
                return(IrrecoverableError("An error occurred sending the email", "This has been recorded, and will be looked into shortly"));
            }

            ViewData["Background"] = background;
            ViewData["Color"]      = color;

            return(SuccessEmail("Registration Email Sent to " + email, "Check your email for the link to complete your registration."));
        }
Exemplo n.º 23
0
        public bool IsValidUser(string username, string password)
        {
            UserCredentials testUser = repo.GetUser(username);

            return(Password.CheckPassword(password, testUser.Salt, testUser.PasswordHash));
        }
Exemplo n.º 24
0
 void IServerBase.ChangePassword(Password password, Password newPassword)
 {
     Password serverPassword;
     try
     {
         serverPassword = new Password(Config.Instance.GetIntegerList("Server.AdminPassword").ToArray());
     }
     catch(ArgumentOutOfRangeException)
     {
         serverPassword = new Password("");
     }
     if(!serverPassword.CheckPassword(password))
         throw new BadServerPasswordException();
     Config.Instance.SetIntegerList("Server.AdminPassword", newPassword.LongHash.ToList());
 }
Exemplo n.º 25
0
 public bool CheckPassword(string password)
 {
     return(Password.CheckPassword(password));
 }
Exemplo n.º 26
0
        public void ThrowExceptionIfPasswordLengthIsLessThan6Chars()
        {
            var input = "alpha";

            Assert.Throws <System.ArgumentException>(() => pw.CheckPassword(input));
        }
Exemplo n.º 27
0
 static void BIO_2000_Q1()
 {
     Password.CheckPassword();
 }
Exemplo n.º 28
0
        public bool IsValidUser(string email, string password)
        {
            var user = _modelRepository.Read(email).Result;

            return(Password.CheckPassword(password, user.Salt, user.Password));
        }