Пример #1
0
 private void FinishButton_Click_OnAuthentication(object sender, EventArgs e)
 {
     if (guestCheckBox.Checked)
     {
         MessageBox.Show(AuthenticationLocalization.GuestMessage, AuthenticationLocalization.GuestMessageHeader);
         UserLogin    = AuthenticationLocalization.GuestLogin;
         UserType     = UserTypes.Guest;
         DialogResult = DialogResult.OK;
         return;
     }
     using (var context = new UsersModel())
     {
         var user = usersComboBox.SelectedItem as Пользователи;
         if (user == null)
         {
             MessageBox.Show($@"{AuthenticationLocalization.AuthenticationError}{AuthenticationLocalization.AuthenticationLoginError}");
         }
         context.Пользователи.Attach(user);
         UserLogin = user.Логин;
         UserType  = user.Администратор ? UserTypes.Admin : UserTypes.User;
         var generatedHash = PasswordSecurity.GenerateHash(passwordTextBox.Text, user.Соль);
         if (!generatedHash.Equals(user.Хэш_пароля))
         {
             MessageBox.Show($@"{AuthenticationLocalization.AuthenticationError}
                                {AuthenticationLocalization.AuthenticationPasswordError}");
             return;
         }
         MessageBox.Show(AuthenticationLocalization.AuthenticationCompleted);
         DialogResult = DialogResult.OK;
     }
 }
Пример #2
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            AccountModel result = Db.Accounts.Where(m => m.EmailAddress == model.EmailAddress).FirstOrDefault();

            if (result != null)
            {
                return(View(model));
            }

            AccountModel Account = new AccountModel();

            Account.FirstName    = model.FirstName;
            Account.LastName     = model.LastName;
            Account.Nickname     = model.Nickname;
            Account.EmailAddress = model.EmailAddress;
            Account.Password     = PasswordSecurity.CreateHash(model.Password);
            Account.DateCreated  = DateTime.Now;

            await Db.Accounts.AddAsync(Account);

            await Db.SaveChangesAsync();

            return(RedirectToAction("Index", "Home"));
        }
Пример #3
0
        public List <UserTable> GetAllUser()
        {
            var toReturn = new List <UserTable>();

            try
            {
                using (var db = new connectionsLinqDataContext())
                {
                    var temp = db.GetAllUser().ToList();
                    foreach (var v in temp)
                    {
                        UserTable toAdd             = ConvertToUser(v);
                        var       decryptedpassword = PasswordSecurity.Decrypt("securityPassword", toAdd.password, false);

                        toAdd.password = decryptedpassword;
                        toReturn.Add(toAdd);
                    }
                    return(toReturn);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #4
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            AccountModel result = Db.Accounts.Where(m => m.EmailAddress == model.EmailAddress).FirstOrDefault();

            if (result != null)
            {
                return(View(model));
            }

            AccountModel Account = new AccountModel()
            {
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                Nickname     = model.Nickname,
                EmailAddress = model.EmailAddress,
                Password     = PasswordSecurity.CreateHash(model.Password),
                Role         = AccountRoles.Customer,
                Status       = AccountStatus.Enabled,
                DateCreated  = DateTime.Now
            };

            await Db.Accounts.AddAsync(Account);

            await Db.SaveChangesAsync();

            return(RedirectToAction("Index", "Home"));
        }
Пример #5
0
        public int Add(CustomerinfoViewModel newItem)
        {
            try
            {
                Customer_Info customer = new Customer_Info()
                {
                    name         = newItem.name,
                    dob          = newItem.dob,
                    address      = newItem.address,
                    phone        = newItem.phone,
                    email        = newItem.email,
                    active       = newItem.active,
                    username     = newItem.username,
                    password     = PasswordSecurity.Encrypt(newItem.password),
                    user_type_id = newItem.user_type_id
                };
                context.Customer_Info.Add(customer);
                context.SaveChanges();

                return(1);
            }
            catch (EntityException ex)
            {
                Debug.Write(ex.Message);
                return(0);
            }
        }
Пример #6
0
        public async Task <IActionResult> SendConfirmation([FromBody] LoginModel signup)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var id              = PasswordSecurity.HashEmail(signup.Email);
                    var code            = PasswordSecurity.HashEmail(signup.Password);
                    var callbackUrl     = Url.Action(nameof(Confirm), "Email", new { userId = id, code = code }, protocol: HttpContext.Request.Scheme);
                    var applicationUser = new ApplicationUser {
                        UserId = id, Email = signup.Email, Code = code
                    };
                    await _context.AddAsync(applicationUser);

                    await _context.SaveChangesAsync();

                    _emailManager.Send(signup.Email, "Confirm your account", $"Please confirm your account by clicking <a href='{callbackUrl}'>here</a>");
                    return(Ok());
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("Errors", "There was a problem with the email client");
                    throw(e);
                }
            }
            return(BadRequest());
        }
        public ActionResult Register(Customer cus)
        {
            if (string.IsNullOrEmpty(cus.CustomerLoginName))
            {
                ViewBag.Message2 = "請填寫帳號";
                return(View("Register", cus));
            }
            if (string.IsNullOrEmpty(cus.CustomerPassword))
            {
                ViewBag.Message3 = "請填寫密碼";
                return(View("Register", cus));
            }

            var Customer = db.Customers
                           .Where(c => c.CustomerLoginName == cus.CustomerLoginName)
                           .FirstOrDefault();

            if (Customer == null)
            {
                Guid userGuid = Guid.NewGuid();
                cus.CustomerGuid     = userGuid;
                cus.CustomerPassword = PasswordSecurity.HashSHA1(cus.CustomerPassword + userGuid);

                db.Customers.Add(cus);
                db.SaveChanges();
                return(RedirectToAction("RegisterOk", cus));
            }
            ViewBag.Message = "此帳號己有人使用,註冊失敗";
            return(View());
        }
Пример #8
0
        public ApplicationUsers LoginUser(ApplicationUsers users)
        {
            try
            {
                var user = _context.ApplicationUsers.Where(a => a.UserName == users.UserName).FirstOrDefault();
                if (user == null)
                {
                    return(null);
                }
                else
                {
                    var passwordKey   = user.Pass;
                    var password      = user.Password;
                    var resultDecrypt = PasswordSecurity.Decrypt(password, passwordKey);
                    if (resultDecrypt == users.Password)
                    {
                        return(user);
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = db.UserSys
                           .Where(u => u.Email == model.Email).SingleOrDefault();

                // check user password
                if (user != null && PasswordSecurity.IsPasswordMatch(user.Password, user.Salt, model.Password))
                {
                    UserRole userRole = db.UserRole.SingleOrDefault(r => r.Id == user.UserRoleId);
                    this.Session.Add("UserId", user.Id);
                    if (userRole.IsAdmin)
                    {
                        this.Session.Add("IsUserAdmin", 1);
                    }
                    else
                    {
                        this.Session["IsUserAdmin"] = null;
                    }

                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    return(RedirectToAction("List", "Customer"));
                }
                else
                {
                    ModelState.AddModelError("", "The e-mail and/or password entered is invalid. Please Try again.");
                }
            }

            return(View(model));
        }
        /// <summary>
        /// Verifies the provided credentials against the stored user password.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password in plaintext.</param>
        /// <returns>An awaitable task that returns the <see cref="Account"/>.</returns>
        /// <remarks>If the user does not exist, a new one will be created.</remarks>
        public async Task <Account> LoginAsync(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(nameof(username));
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            // Get user by username
            var account = await accountRepository.GetAccountAsync(username);

            if (account == null)
            {
                // Create new account
                account = await accountRepository.CreateAccountAsync(username, password);
            }
            else
            {
                // Check password
                var credentials = new SecurityCredentials
                {
                    PasswordHash = account.PasswordHash,
                    SaltValue    = account.Salt
                };
                var comparisonResult = PasswordSecurity.VerifyPassword(credentials, password);
                if (!comparisonResult)
                {
                    return(null);
                }
            }
            return(account);
        }
Пример #11
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            AccountModel result = Db.Accounts.Where(m => m.EmailAddress == model.EmailAddress).FirstOrDefault();

            if (result == null && PasswordSecurity.VerifyPassword(model.Password, result.Password))
            {
                return(View(model));
            }

            var identity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, result.getName()),
                new Claim(ClaimTypes.Email, result.EmailAddress)
            }, CookieAuthenticationDefaults.AuthenticationScheme);

            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                principal);

            return(RedirectToAction("Index", "Home"));
        }
        public async Task <ActionResult> Post([FromBody] Student student)
        {
            if (ModelState.IsValid)
            {
                if (!PasswordSecurity.CheckPasswordPolicy(student.Password))
                {
                    ModelState.AddModelError("Errors", "PASSWORD INVALID");
                    return(BadRequest(ModelState));
                }
                if (_context.EmailIsTaken(student.Email))
                {
                    ModelState.AddModelError("Errors", "Email has already been taken");
                    return(BadRequest(ModelState));
                }
                student.Password = PasswordSecurity
                                   .HashPassword(student.Password);
                student.EmailConfirmed = false;
                await _context.AddAsync(student);

                await _context.SaveChangesAsync();

                return(CreatedAtAction(nameof(Get), new { id = student.StudentId }, student));
            }
            return(BadRequest());
        }
Пример #13
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            if (HasBrokenRules())
            {
                return;
            }

            try
            {
                UserAccountItem.DisplayName = txtName.Text;
                UserAccountItem.Username    = txtUsername.Text;

                var hash = PasswordSecurity.CreateHash(txtPassword.Text);
                if (hash != UserAccountItem.Password)
                {
                    UserAccountItem.Password = hash;
                }

                UserAccountItem.SecurityLevel = chkAdmin.Checked ? "Admin" : "User";
                UserAccountItem.Active        = !chkDisabled.Checked;

                if (UserAccountItem.Save(AppSession.CurrentUser.Username))
                {
                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
        }
Пример #14
0
        private async Task <UserModel> Authenticate(LoginModel login)
        {
            // TODO this should probably be removed in favor of using the entity class instead for a User
            UserModel user = new UserModel
            {
                Name            = "Test",
                Email           = login.Email,
                IsAuthenticated = false
            };

            var matchingEmailUser = await _context
                                    .Users
                                    .Where(_ => _.Email == login.Email)
                                    .FirstOrDefaultAsync();

            if (matchingEmailUser != null)
            {
                if (PasswordSecurity.CompareHashedPasswords(login.Password, matchingEmailUser.PasswordHash))
                {
                    user.IsAuthenticated = true;
                    user.Id = matchingEmailUser.UserId;
                }
            }

            return(user);
        }
 public static void RegisterDefaultFormatExtensions()
 {
     TextFormat.AddCustomFormatHint("kv", FormatKeyValue);
     TextFormat.AddCustomFormatHint("lo", n => n?.ToString()?.ToLower());
     TextFormat.AddCustomFormatHint("hi", n => n?.ToString()?.ToUpper());
     TextFormat.AddCustomFormatHint("decrypt", n => PasswordSecurity.Decrypt(n?.ToString()));
 }
Пример #16
0
        public void EncryptTest()
        {
            var newPassword       = "******";
            var encryptedpassword = PasswordSecurity.Encrypt("securityPassword", newPassword, false);

            Assert.AreNotEqual(newPassword, encryptedpassword);
        }
        public ActionResult Login(string LoginName, string Password)
        {
            //var Customer = db.Customers
            //    .Where(c => c.CustomerLoginName == LoginName && c.CustomerPassword == Password)
            //    .FirstOrDefault();

            int customerHashCheckId = PasswordSecurity.GetUserIdByUsernameAndHashedSaltedPassword(LoginName, Password);

            var Employee = db.Employees
                           .Where(e => e.EmployeeLoginName == LoginName && e.EmployeePassword == Password)
                           .FirstOrDefault();

            if (customerHashCheckId != 1)
            {
                var Customer = db.Customers.Find(customerHashCheckId);
                //return Content(customerHashCheckId.ToString());
                Session["Welcome"]    = Customer.CustomerName + " " + "歡迎光臨";
                Session["Customer"]   = Customer;
                Session["CustomerID"] = Customer.CustomerID;
                return(RedirectToAction("Index"));
            }
            else if (Employee != null)
            {
                Session["Welcome"]    = Employee.EmployeeLoginName + " " + "管理員";
                Session["Employee"]   = Employee;
                Session["EmployeeID"] = Employee.EmployeeID;
                return(RedirectToAction("Workdistinction", "Service"));
            }
            else
            {
                ViewBag.Message = "帳密輸入錯誤";
            }

            return(View());
        }
Пример #18
0
        private void changePassword_Click(object sender, EventArgs e)
        {
            var row = usersDGV.SelectedRows[0];
            var id  = row.Cells[UserIDColumn.Name].Value as int?;

            if (!id.HasValue || id.Value == 0)
            {
                return;
            }
            using (var passwordManager = new PasswordManagerForm(true))
            {
                if (passwordManager.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }
                using (var context = new UsersModel())
                {
                    var tag = row.Tag as Пользователи;
                    context.Пользователи.Attach(tag);
                    tag.Соль       = PasswordSecurity.GenerateSalt();
                    tag.Хэш_пароля = PasswordSecurity.GenerateHash(passwordManager.Password, tag.Соль);
                    context.SaveChanges();
                    row.Cells[HashColumn.Name].Value = tag.Хэш_пароля;
                    row.Cells[SaltColumn.Name].Value = tag.Соль;
                    row.Tag = tag;
                }
            }
        }
Пример #19
0
        private void usersDGV_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            var row = usersDGV.Rows[e.RowIndex];

            using (var context = new UsersModel())
            {
                var id    = row.Cells[UserIDColumn.Name].Value as int?;
                var tag   = row.Tag as Пользователи;
                var login = row.Cells[LoginColumn.Name].Value as string;
                e.Cancel = login == null || login.Replace(" ", "") == "" || login.Length > 50;
                if (e.Cancel)
                {
                    row.Cells[LoginColumn.Name].ErrorText = ManagementLocalization.IncorrectLoginError;
                    return;
                }
                e.Cancel = context.Пользователи.Any(user => user.ID != id.Value && user.Логин == login);
                if (e.Cancel)
                {
                    row.ErrorText = ManagementLocalization.LoginExistsError;
                    return;
                }
                var isInsert = tag == null;
                if (isInsert)
                {
                    tag = new Пользователи();
                    using (var passwordManager = new PasswordManagerForm(false))
                    {
                        if (passwordManager.ShowDialog() == DialogResult.OK)
                        {
                            tag.Соль       = PasswordSecurity.GenerateSalt();
                            tag.Хэш_пароля = PasswordSecurity.GenerateHash(passwordManager.Password, tag.Соль);
                        }
                    }
                }
                else
                {
                    context.Пользователи.Attach(tag);
                }
                if (tag.Логин == AdminLogin)
                {
                    AdminLogin          = login;
                    userLoginLabel.Text = userLoginLabel.Tag as string + AdminLogin;
                }
                tag.Логин            = login;
                tag.Администратор    = (bool)row.Cells[IsAdminColumn.Name].Value;
                tag.Дата_регистрации = ((DateTime)row.Cells[RegDateColumn.Name].Value).Date;
                row.Tag = tag;
                if (isInsert)
                {
                    context.Пользователи.Add(tag);
                }
                context.SaveChanges();
            }
            row.ErrorText = "";
            foreach (DataGridViewCell cell in row.Cells)
            {
                cell.ErrorText = "";
            }
        }
Пример #20
0
        public void DecryptTest_good()
        {
            var newPassword       = "******";
            var encryptedpassword = PasswordSecurity.Encrypt("securityPassword", newPassword, false);
            var decryptedPassword = PasswordSecurity.Decrypt("securityPassword", encryptedpassword, false);

            Assert.AreEqual(newPassword, decryptedPassword);
        }
Пример #21
0
 //===============================================================================================
 public bool CheckOldPassword(string dbPassword, string enterPassword)
 {
     if (PasswordSecurity.Decrypt(dbPassword).Equals(enterPassword))
     {
         return(true);
     }
     return(false);
 }
Пример #22
0
        public void TestInlineValues()
        {
            PasswordSecurity.InitializeAes("Weneee e die Russn kommn!");
            string encrypted = "bladibla".Encrypt();
            var    decrypted = new object().FormatText($"[\"{encrypted}\":decrypt]");

            Assert.AreEqual(decrypted, "bladibla");
        }
Пример #23
0
        public ActionResult Convert()
        {
            string password  = Request.Params["password"];
            string encryptPw = PasswordSecurity.Encrypt(password);

            TempData["encrypt"] = encryptPw;
            return(RedirectToAction("ConvertPassword", TempData["encrypt"]));
        }
Пример #24
0
        public JsonResult RegisterUser([FromBody] ApplicationUsers users)
        {
            users.Pass     = Guid.NewGuid().ToString();
            users.Password = PasswordSecurity.Encrypt(users.Password, users.Pass);
            var result = _account.RegisterAccount(users);

            return(new JsonResult("Success"));
        }
Пример #25
0
        public void DecryptTest_good_enc_and_dec_dont_match()
        {
            var newPassword       = "******";
            var encryptedpassword = PasswordSecurity.Encrypt("securityPassword", newPassword, false);
            var decryptedPassword = PasswordSecurity.Decrypt("securityPassword", encryptedpassword, false);

            Assert.AreNotEqual(encryptedpassword, decryptedPassword);
        }
Пример #26
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordModel forgotPassword)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var applicationuser = await
                                          _context
                                          .ApplicationUsers
                                          .Where(_ => _.Email == forgotPassword.Email)
                                          .FirstOrDefaultAsync();

                    var studentClaim = await
                                       _context
                                       .Students
                                       .Where(_ => _.Email == forgotPassword.Email)
                                       .FirstOrDefaultAsync();

                    var instructorClaim = await
                                          _context
                                          .Instructors
                                          .Where(_ => _.Email == forgotPassword.Email)
                                          .FirstOrDefaultAsync();

                    if (applicationuser == null)
                    {
                        // Don't reveal that the user does not exist
                        return(Ok());
                    }
                    if (!studentClaim.EmailConfirmed)
                    {
                        return(Ok());
                    }
                    if (!studentClaim.EmailConfirmed)
                    {
                        return(Ok());
                    }

                    var code = PasswordSecurity.HashPassword(forgotPassword.ResetPassword);
                    applicationuser.Code          = code;
                    applicationuser.ResetPassword = PasswordSecurity
                                                    .HashPassword(forgotPassword.ResetPassword);
                    _context.ApplicationUsers.Update(applicationuser);
                    await _context.SaveChangesAsync();

                    var callbackUrl  = Url.Action(nameof(ResetPassword), "Email", new { userId = applicationuser.UserId, code = code }, protocol: HttpContext.Request.Scheme);
                    var callbackUrl2 = Url.Action(nameof(CancelReset), "Email", new { userId = applicationuser.UserId, code = code }, protocol: HttpContext.Request.Scheme);

                    _emailManager.Send(forgotPassword.Email, "Reset Password", $"Please reset your password by clicking <a href='{callbackUrl}'>here</a><br>Not you? Click <a href='{callbackUrl2}'>here</a>");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("Errors", "There was a problem with the email client");
                    throw(e);
                }
            }
            return(Ok());
        }
Пример #27
0
        public void TestEncryption()
        {
            PasswordSecurity.InitializeAes("So long and thanks for all the fish");
            var initial   = "MeinSuperGutesPasswort";
            var encrypted = PasswordSecurity.Encrypt(initial);
            var decrypted = PasswordSecurity.Decrypt(encrypted);

            Assert.AreEqual(initial, decrypted);
        }
        public void Verify_Password_Silently()
        {
            string password = "******";
            string hash     = "RyusGZUymx1tpIexmeuIK2rWO2JT+bt27WjzxSTtQ76Q77e/";

            var security = new PasswordSecurity();

            security.Verify(hash, password);
        }
        public void Throw_AuthenticationException_If_Password_Invalid()
        {
            string password = "******";
            string hash     = "RyusGZUymx1tpIexmeuIK2rWO2JT+bt27WjzxSTtQ76Q77e/";

            var security = new PasswordSecurity();

            Assert.Throws <AuthenticationException>(() => security.Verify(hash, password));
        }
        public void Hash_Password_Uniquely()
        {
            var security = new PasswordSecurity();

            string password = "******";
            string hash1    = security.Hash(password);
            string hash2    = security.Hash(password);

            Assert.NotEqual(hash1, hash2);
        }