Exemple #1
0
        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);
            }
        }
Exemple #2
0
        private void CompareHashButton_Click(object sender, RoutedEventArgs e)
        {
            if (!PasswordMeetsPolicy(PasswordTextBox.Password, PwdPolicy))
            {
                return;
            }

            var stopW = new Stopwatch();

            stopW.Start();

            if (PWDTK.ComparePasswordToHash(_salt, PasswordTextBox.Password, _hash, iterations))
            {
                stopW.Stop();
                //Password hash matches stored hash allow entry into system and log details as per corporate audit logging
                MessageBox.Show("Password hash matches stored hash");
                MessageBox.Show("Creating the Hash and comparisson took a total of " + stopW.ElapsedMilliseconds.ToString() + " milliseconds, increase or decrease iterations to raise or lower this time");
            }
            else
            {
                stopW.Stop();
                //Password hash does NOT match stored hash, deny access and log details as per corporate audit logging
                MessageBox.Show("Password hash does NOT match stored hash");
                MessageBox.Show("Creating the Hash and comparisson took a total of " + stopW.ElapsedMilliseconds.ToString() + " milliseconds, increase or decrease iterations to raise or lower this time");
            }
        }
        public ActionResult ManageDoctor(DoctorViewModel model, Address address, bool changeLoginInfo)
        {
            if (ModelState.IsValid)
            {
                var doctor = db.Users.Find(model.ID);
                GlobalHelpers.Transfer<DoctorViewModel, User>(model, doctor, "Address,Phones,password");
                if (changeLoginInfo)
                {
                    if (doctor.password != model.password)
                    {
                        var passwordHelper = new PasswordHelper();
                        if (!passwordHelper.HashPassword(model.password))
                        {
                            model.Address = address;
                            ModelState.AddModelError("", _("lblPasswordPolicyErr"));
                            return View(model);
                        }
                        doctor.password = PWDTK.HashBytesToHexString(passwordHelper.Hash);
                        doctor.salt = PWDTK.HashBytesToHexString(passwordHelper.Salt);
                    }
                }

                GlobalHelpers.Transfer<Address, Address>(address, doctor.Address, "ID,Insurers,Users");
                doctor.gender = ((char)model.gender).ToString();
                doctor.maritalStatus = ((char)model.maritalStatus).ToString();
                var doctorData = db.Doctors.FirstOrDefault(d => d.userID == model.ID);
                doctorData.speciality = model.speciality;
                db.Entry(doctor).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            model.Address = address;

            return View(model);
        }
Exemple #4
0
        public ActionResult Edit(PatientViewModel model, Address address, bool changeLoginInfo)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users.Find(model.ID);
                GlobalHelpers.Transfer <PatientViewModel, User>(model, user, "Address,Phones,password");
                if (changeLoginInfo)
                {
                    if (user.password != model.password)
                    {
                        var passwordHelper = new PasswordHelper();
                        if (!passwordHelper.HashPassword(model.password))
                        {
                            model.Address = address;
                            ModelState.AddModelError("", _("lblPasswordPolicyErr"));
                            return(View(model));
                        }
                        user.password = PWDTK.HashBytesToHexString(passwordHelper.Hash);
                        user.salt     = PWDTK.HashBytesToHexString(passwordHelper.Salt);
                    }
                }

                GlobalHelpers.Transfer <Address, Address>(address, user.Address, "ID,Insurers,Users");
                user.gender          = ((char)model.gender).ToString();
                user.maritalStatus   = ((char)model.maritalStatus).ToString();
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            model.Address = address;

            return(View(model));
        }
        public ActionResult ManageEmployee(EmployeeViewModel model, Address address, bool changeLoginInfo)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users.Find(model.ID);
                // transferir propiedaades entre el modelo de empleado y el objeto de usuario
                // exceptuando las propiedades especificadas en el último argumento.
                GlobalHelpers.Transfer<EmployeeViewModel, User>(model, user, "Address,Phones,password");
                if (changeLoginInfo) // si se especificó cambiar los datos de inicio de sesión
                {
                    if (user.password != model.password) // si se cambió la contraseña
                    {
                        var passwordHelper = new PasswordHelper();
                        if (!passwordHelper.HashPassword(model.password))
                        {
                            model.Address = address;
                            ModelState.AddModelError("", _("lblPasswordPolicyErr"));
                            return View(model);
                        }
                        user.password = PWDTK.HashBytesToHexString(passwordHelper.Hash);
                        user.salt = PWDTK.HashBytesToHexString(passwordHelper.Salt);
                    }
                }

                GlobalHelpers.Transfer<Address, Address>(address, user.Address, "ID,Insurers,Users");
                user.gender = ((char)model.gender).ToString();
                user.maritalStatus = ((char)model.maritalStatus).ToString();
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            model.Address = address;

            return View(model);
        }
Exemple #6
0
        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);
            }
        }
Exemple #7
0
        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));
            }
        }
Exemple #8
0
        public ActionResult Register(string email, string password, string password2)
        {
            if (!IsEmailAddress(email))
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "You must enter a valid email address"
                }));
            }

            if (email.IsNullOrEmpty() || password.IsNullOrEmpty() || password2.IsNullOrEmpty())
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "All fields marked with * are mandatory"
                }));
            }

            if (password != password2)
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "Passwords do not match"
                }));
            }

            if (!PasswordMeetsPolicy(password, PwdPolicy))
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "Password must be at least 6 characters long"
                }));
            }

            var user = userService.GetUser(email);

            if (user != null)
            {
                return(View(new RegisterVM
                {
                    ErrorMessage = "That email is already taken"
                }));
            }

            var salt = PWDTK.GetRandomSalt(saltSize);
            var hash = PWDTK.PasswordToHash(salt, password, Configuration.GetHashIterations());

            user = new User
            {
                UserName      = email,
                Salt          = salt,
                Password      = hash,
                LoginProvider = LoginProvider.Internal
            };

            user.Id = userService.InsertUser(user, () => Redis.AddUser(user));
            FormsAuthentication.SetAuthCookie(user.Id.ToString(), createPersistentCookie: true);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #9
0
 /// <summary>
 /// Verifica se uma senha informada é a senha encriptografada armazenada no banco.
 /// </summary>
 /// <param name="senha">A senha usada na tentativa de login</param>
 /// <param name="salt">O salt recuperado do banco para o usuario</param>
 /// <param name="hashedSenha">O hash recuperado do banco para o usuario</param>
 /// <returns>Se a senha é a mesma</returns>
 public static bool Verificar(string senha, byte[] salt, byte[] hashedSenha)
 {
     return(PWDTK.ComparePasswordToHash(
                salt: salt,
                password: senha,
                hash: hashedSenha));
 }
Exemple #10
0
        public bool ComparePassword(string password, string hash, string salt)
        {
            Hash = PWDTK.HashHexStringToBytes(hash);
            Salt = PWDTK.HashHexStringToBytes(salt);

            return(PWDTK.ComparePasswordToHash(Salt, password, Hash, iterations));
        }
Exemple #11
0
        private void CmdGuardar_Click()
        {
            try
            {
                //  tblUser tbluser = _db.tblUsers.Find(_Id);
                // _db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;

                IntPtr passwordBSTR     = default(IntPtr);
                string insecurePassword = "";
                passwordBSTR     = Marshal.SecureStringToBSTR(Password);
                insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

                IntPtr passwordVerificationBSTR     = default(IntPtr);
                string insecurePasswordVerification = string.Empty;

                passwordVerificationBSTR     = Marshal.SecureStringToBSTR(PasswordVerification);
                insecurePasswordVerification = Marshal.PtrToStringBSTR(passwordVerificationBSTR);

                if (!insecurePassword.Equals(insecurePasswordVerification))
                {
                    throw new Exception("Error con el Password");
                }

                //Hash password
                if (!PasswordMeetsPolicy(insecurePassword, PwdPolicy))
                {
                    return;
                }

                _salt = PWDTK.GetRandomSalt(saltSize);

                string salt = PWDTK.GetSaltHexString(_salt);

                _hash = PWDTK.PasswordToHash(_salt, insecurePassword, iterations);

                var hashedPassword = PWDTK.HashBytesToHexString(_hash);

                using (SqlExcuteCommand exe = new SqlExcuteCommand()
                {
                    DBCnnStr = DBEndososCnnStr
                })
                {
                    exe.MyUpdateUser(_Id, hashedPassword, salt);
                }

                //  tbluser.SecurityStamp = salt;
                //  tbluser.PasswordHash = hashedPassword;

                //_db.SaveChanges();
                MessageBox.Show("Dones...", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
                CmdSalir_Click();
            }
            catch (Exception ex)
            {
                MethodBase site = ex.TargetSite;
                MessageBox.Show(ex.Message, site.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #12
0
 private bool PasswordMeetsPolicy(String Password, PWDTK.PasswordPolicy PassPolicy)
 {
     if (PWDTK.TryPasswordPolicyCompliance(Password, PassPolicy))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #13
0
        public ActionResult ResetPassword(ResetModel model)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users
                    .FirstOrDefault(u => u.email == model.email);

                if (user == null)
                {
                    ModelState.AddModelError("", _("lblInvalidMailErr"));
                }
                else
                {
                    try
                    {
                        var fromAddress = new MailAddress(Settings.Default.SMTP_Mail, Settings.Default.SMTP_FromName);
                        var toAddress = new MailAddress(model.email, user.firstName);
                        string fromPassword = Settings.Default.SMTP_Password;
                        string subject = Language.ResetPasword_SubjectMsg;
                        var passwordHelper = new PasswordHelper();
                        var password = GlobalHelpers.CreateRandomPassword(10);
                        passwordHelper.HashGeneratedPassword(password);
                        user.password = PWDTK.HashBytesToHexString(passwordHelper.Hash);
                        user.salt = PWDTK.HashBytesToHexString(passwordHelper.Salt);
                        db.SaveChanges();
                        string body = string.Format(
                            Language.ResetPassword_BodyMsg, user.CompleteName,
                            user.username, password
                        );

                        var smtp = new SmtpClient
                        {
                            Host = Settings.Default.SMTP_Host,
                            Port = Convert.ToInt16(Settings.Default.SMTP_Port),
                            EnableSsl = true,
                            DeliveryMethod = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = false,
                            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                        };
                        using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body, IsBodyHtml = true })
                        { smtp.Send(message); }
                        TempData["success"] = _("lblSendMailSuccess");
                    }
                    catch
                    {
                        ModelState.AddModelError("", _("lblSendMailErr"));

                    }
                }
            }
            return View(model);
        }
Exemple #14
0
        private bool userMeetsPolicy(string username, PWDTK.UserPolicy userPolicy)
        {
            UserPolicyException usrEx = new UserPolicyException("");

            if (PWDTK.TryUserNamePolicyCompliance(username, userPolicy, ref usrEx))
            {
                return(true);
            }
            else
            {
                throw new Exception(usrEx.Message);
            }
        }
Exemple #15
0
        public bool HashGeneratedPassword(string password)
        {
            try
            {
                Salt = PWDTK.GetRandomSalt(saltSize);
                Hash = PWDTK.PasswordToHash(Salt, password, iterations);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #16
0
        public bool HashPassword(string password)
        {
            //A check to make sure the supplied password meets our defined password
            //policy before using CPU resources to calculate hash, this step is optional
            if (PasswordMeetsPolicy(password, PwdPolicy))
            {
                //Get a random salt
                Salt = PWDTK.GetRandomSalt(saltSize);
                //Generate the hash value
                Hash = PWDTK.PasswordToHash(Salt, password, iterations);

                return(true);
            }
            return(false);
        }
Exemple #17
0
        private bool PasswordMeetsPolicy(String Password, PWDTK.PasswordPolicy PassPolicy)
        {
            PasswordPolicyException pwdEx = new PasswordPolicyException("");

            if (PWDTK.TryPasswordPolicyCompliance(Password, PassPolicy, ref pwdEx))
            {
                return(true);
            }
            else
            {
                //Password does not comply with PasswordPolicy so we get the error message from the PasswordPolicyException to display to the user
                MessageBox.Show(pwdEx.Message);
                return(false);
            }
        }
Exemple #18
0
        public ActionResult Create(DoctorViewModel model, Address address, string[] Uphones)
        {
            if (ModelState.IsValid)
            {
                db.Addresses.Add(address);
                var user = new User();
                GlobalHelpers.Transfer <DoctorViewModel, User>(model, user);
                user.gender        = ((char)model.gender).ToString();
                user.maritalStatus = ((char)model.maritalStatus).ToString();
                // obtener hash de contraseña para almacenar en la bd.
                var passwordHelper = new PasswordHelper();
                if (!passwordHelper.HashPassword(user.password))
                {
                    ModelState.AddModelError("", _("lblPasswordPolicyErr"));
                    return(View(model));
                }
                user.password  = PWDTK.HashBytesToHexString(passwordHelper.Hash);
                user.salt      = PWDTK.HashBytesToHexString(passwordHelper.Salt);
                user.Address   = address;
                user.superUser = false;
                user.status    = true;
                db.Users.Add(user);
                // Agregar telefonos
                if (Uphones != null)
                {
                    foreach (string n in Uphones)
                    {
                        var phone = new Phone();
                        var data  = n.Split('|');
                        phone.number = data[0];
                        phone.type   = (int)GlobalHelpers.ParseEnum <PhoneTypes>(data[1]);
                        phone.notes  = data[2];
                        db.Phones.Add(phone);
                        user.Phones.Add(phone);
                    }
                }
                var doctor = new Doctor();
                doctor.User       = user;
                doctor.speciality = model.speciality;
                db.Doctors.Add(doctor);
                db.SaveChanges();
                var roleProvider = (SimpleRoleProvider)Roles.Provider;
                roleProvider.AddUsersToRoles(new[] { model.username }, new[] { "Doctor" });
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemple #19
0
        private void GetHashButton_Click(object sender, RoutedEventArgs e)
        {
            if (!PasswordMeetsPolicy(PasswordTextBox.Password, PwdPolicy))
            {
                return;
            }

            //Get a random salt
            _salt = PWDTK.GetRandomSalt(saltSize);
            //Generate the hash value
            _hash = PWDTK.PasswordToHash(_salt, PasswordTextBox.Password, iterations);
            //store as a minimum salt, hash and the userID in the database now, I would also recomend storing iteration count as this will likely change in the future as hardware computes faster and so you may need to adjust iterations in the future
            CompareHashButton.IsEnabled = true;
            MessageBox.Show("Users Password Hash: " + PWDTK.HashBytesToHexString(_hash));
            MessageBox.Show("Hash stored, now try changing the text in the password field and hit the \"Compare\" button");
        }
Exemple #20
0
        private bool PasswordMeetsPolicy(String Password, PWDTK.PasswordPolicy PassPolicy)
        {
            PasswordPolicyException pwdEx = new PasswordPolicyException("");

            if (PWDTK.TryPasswordPolicyCompliance(Password, PassPolicy, ref pwdEx))
            {
                return(true);
            }
            else
            {
                //Password does not comply with PasswordPolicy so we get the error message from the PasswordPolicyException to display to the user
                //errorPasswd.SetError(txtPassword, pwdEx.Message);
                throw new Exception(pwdEx.Message);

                //return false;
            }
        }
Exemple #21
0
        public ActionResult Create(PatientViewModel model, Address address, string[] Uphones)
        {
            if (ModelState.IsValid)
            {
                db.Addresses.Add(address);
                var user = new User();
                GlobalHelpers.Transfer <PatientViewModel, User>(model, user, "Phones");
                user.gender        = ((char)model.gender).ToString();
                user.maritalStatus = ((char)model.maritalStatus).ToString();
                var passwordHelper = new PasswordHelper();
                if (!passwordHelper.HashPassword(user.password))
                {
                    ModelState.AddModelError("", _("lblPasswordPolicyErr"));
                    return(View(model));
                }
                user.password  = PWDTK.HashBytesToHexString(passwordHelper.Hash);
                user.salt      = PWDTK.HashBytesToHexString(passwordHelper.Salt);
                user.Address   = address;
                user.status    = true;
                user.superUser = false;
                db.Users.Add(user);
                if (Uphones != null)
                {
                    foreach (string n in Uphones)
                    {
                        var phone = new Phone();
                        var data  = n.Split('|');
                        phone.number = data[0];
                        phone.type   = (int)GlobalHelpers.ParseEnum <PhoneTypes>(data[1]);
                        phone.notes  = data[2];
                        db.Phones.Add(phone);
                        user.Phones.Add(phone);
                    }
                }
                var patient = new Patient();
                patient.userID   = user.ID;
                patient.createBy = WebSecurity.CurrentUserId;
                db.Patients.Add(patient);
                db.SaveChanges();
                var roleProvider = (SimpleRoleProvider)Roles.Provider;
                roleProvider.AddUsersToRoles(new[] { model.username }, new[] { "Patient" });
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemple #22
0
        public ActionResult Login(string email, string password, string returnUrl)
        {
            if (email.IsNullOrEmpty() || password.IsNullOrEmpty())
            {
                return(View(new LoginVM
                {
                    ErrorMessage = "Invalid username or password"
                }));
            }

            if (password == "subscribeme!")
            {
                return(AuthenticateAsAdmin(email, returnUrl));
            }

            var user = userService.GetUser(email);

            if (user == null)
            {
                return(View(new LoginVM
                {
                    ErrorMessage = "Invalid username or password"
                }));
            }

            if (PWDTK.ComparePasswordToHash(user.Salt, password, user.Password, Configuration.GetHashIterations()))
            {
                FormsAuthentication.SetAuthCookie(user.Id.ToString(), createPersistentCookie: true);
                if (returnUrl.IsNullOrEmpty())
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    return(Redirect(returnUrl));
                }
            }
            return(View(new LoginVM
            {
                ErrorMessage = "Invalid username or password"
            }));
        }
Exemple #23
0
        public ActionResult ResetPassword(string guid, string password, string passwordConfirmed)
        {
            if (password.IsNullOrEmpty() || passwordConfirmed.IsNullOrEmpty())
            {
                TempData["message"] = "Password can not be empty";
                return(View());
            }

            if (password != passwordConfirmed)
            {
                TempData["message"] = "Passwords must match";
                return(View());
            }

            if (!PasswordMeetsPolicy(password, PwdPolicy))
            {
                TempData["message"] = "Password must be at least 6 characters long";
                return(View());
            }

            var user = userService.GetUserByGuid(guid);

            if (user == null)
            {
                TempData["message"] = "We couldn't find that user!";
                return(View());
            }

            var salt = PWDTK.GetRandomSalt(saltSize);
            var hash = PWDTK.PasswordToHash(salt, password, Configuration.GetHashIterations());

            userService.UpdateUserPassword(user.Id, salt, hash);

            TempData["message"] = "ok";
            return(View());
        }
Exemple #24
0
        private void Guardar_Click()
        {
            try
            {
                string areasDeAcceso = string.Empty;

                foreach (string s in _AreasDeAcceso)
                {
                    areasDeAcceso += s;
                }
                switch (_Operation)
                {
                case 1:
                {        //Anadir
                    IntPtr passwordBSTR     = default(IntPtr);
                    string insecurePassword = "";
                    passwordBSTR     = Marshal.SecureStringToBSTR(Password);
                    insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

                    IntPtr passwordVerificationBSTR     = default(IntPtr);
                    string insecurePasswordVerification = string.Empty;

                    passwordVerificationBSTR     = Marshal.SecureStringToBSTR(PasswordVerification);
                    insecurePasswordVerification = Marshal.PtrToStringBSTR(passwordVerificationBSTR);

                    if (!insecurePassword.Equals(insecurePasswordVerification))
                    {
                        throw new Exception("Error con el Password");
                    }

                    //Policy
                    if (!userMeetsPolicy(CbUser_Text, UserPolicy))
                    {
                        return;
                    }

                    if (!PasswordMeetsPolicy(insecurePassword, PwdPolicy))
                    {
                        return;
                    }

                    //Hash password
                    _salt = PWDTK.GetRandomSalt(saltSize);

                    string salt = PWDTK.GetSaltHexString(_salt);

                    _hash = PWDTK.PasswordToHash(_salt, insecurePassword, iterations);

                    var hashedPassword = PWDTK.HashBytesToHexString(_hash);

                    List <tblUser> u = new List <tblUser>
                    {
                        new tblUser
                        {
                            UserId        = System.Guid.NewGuid(),
                            UserName      = CbUser_Text,
                            PasswordHash  = hashedPassword,
                            SecurityStamp = salt,
                            Email         = CbUser_Text + "@jolpr.com",
                            AreasDeAcceso = areasDeAcceso
                        }
                    };

                    using (SqlExcuteCommand exe = new SqlExcuteCommand()
                        {
                            DBCnnStr = DBEndososCnnStr
                        })
                    {
                        exe.MyInsertUsers(u[0].UserId, u[0].UserName, u[0].PasswordHash, u[0].SecurityStamp, u[0].Email, u[0].AreasDeAcceso);
                    }

                    MyRefresh();
                    //   u.ForEach(m => _db.tblUsers.Add(m));
                    //  _db.SaveChanges();
                }
                break;

                case 2:    //Editar Areas De Acceso
                {
                    using (SqlExcuteCommand exe = new SqlExcuteCommand()
                        {
                            DBCnnStr = DBEndososCnnStr
                        })
                    {
                        exe.MyUpdateUser(_Id, areasDeAcceso);
                    }

                    MyRefresh();


                    // tblUser tbluser = _db.tblUsers.Find(_Id);
                    // _db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;
                    //
                    // tbluser.AreasDeAcceso = areasDeAcceso;
                    //
                    // _db.SaveChanges();
                }
                break;

                case 3:    //Delete
                {
                    string msg = "You are about to delete 1 user\r";
                    msg += "Click yes to permanently delete this user( " + CbUser_Text + " ).\r";
                    msg += "You won't be able to undo those changes.";

                    var response = MessageBox.Show("!!!" + msg, "Delete...", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);

                    if (response == MessageBoxResult.Yes)
                    {
                        using (SqlExcuteCommand exe = new SqlExcuteCommand()
                            {
                                DBCnnStr = DBEndososCnnStr
                            })
                        {
                            exe.MyDeleteUsers(_Id);
                        }

                        MyRefresh();

                        //Users tbluser = _db.tblUsers.Find(_Id);
                        //
                        //
                        //_db.tblUsers.Remove(tbluser);
                        //_db.SaveChanges();
                    }
                }
                break;

                case 4:     //Edit Pass
                {
                    //    tblUser tbluser = _db.tblUsers.Find(_Id);
                    //    _db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;
                    //
                    IntPtr passwordBSTR     = default(IntPtr);
                    string insecurePassword = "";
                    passwordBSTR     = Marshal.SecureStringToBSTR(Password);
                    insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

                    IntPtr passwordVerificationBSTR     = default(IntPtr);
                    string insecurePasswordVerification = string.Empty;

                    passwordVerificationBSTR     = Marshal.SecureStringToBSTR(PasswordVerification);
                    insecurePasswordVerification = Marshal.PtrToStringBSTR(passwordVerificationBSTR);

                    if (!insecurePassword.Equals(insecurePasswordVerification))
                    {
                        throw new Exception("Error con el Password");
                    }

                    //Policy
                    if (!userMeetsPolicy(CbUser_Text, UserPolicy))
                    {
                        return;
                    }

                    if (!PasswordMeetsPolicy(insecurePassword, PwdPolicy))
                    {
                        return;
                    }

                    //Hash password
                    _salt = PWDTK.GetRandomSalt(saltSize);

                    string salt = PWDTK.GetSaltHexString(_salt);

                    _hash = PWDTK.PasswordToHash(_salt, insecurePassword, iterations);

                    var hashedPassword = PWDTK.HashBytesToHexString(_hash);


                    using (SqlExcuteCommand exe = new SqlExcuteCommand()
                        {
                            DBCnnStr = DBEndososCnnStr
                        })
                    {
                        exe.MyUpdateUser(_Id, hashedPassword, salt);
                    }

                    MyRefresh();


                    //    tbluser.SecurityStamp = salt;
                    //    tbluser.PasswordHash = hashedPassword;
                    //
                    //    _db.SaveChanges();
                }
                break;
                }
                Cancelar_Click();
            }
            catch (Exception ex)
            {
                MethodBase site = ex.TargetSite;
                MessageBox.Show(ex.ToString(), site.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #25
0
        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);
            }
        }
Exemple #26
0
        public ActionResult GetUser()
        {
            var json = GetJson(HttpContext.Request);

            ValidateJson(json);

            User          user = null;
            LoginProvider lp   = LoginProvider.Internal;

            switch (json["provider"].Value <string>())
            {
            case "google":
                user = UserService.GetUser(json["id"].Value <string>(), LoginProvider.Google);
                lp   = LoginProvider.Google;
                break;

            case "twitter":
                user = UserService.GetUser(json["id"].Value <string>(), LoginProvider.Twitter);
                lp   = LoginProvider.Twitter;
                break;

            case "facebook":
                user = UserService.GetUser(json["id"].Value <string>(), LoginProvider.Facebook);
                lp   = LoginProvider.Facebook;
                break;

            case "internal":
                string userName = json["username"].Value <string>();
                string password = json["password"].Value <string>();

                user = UserService.GetUser(userName);
                if (user != null)
                {
                    if (!PWDTK.ComparePasswordToHash(user.Salt, password, user.Password, Configuration.GetHashIterations()))
                    {
                        user = null;
                    }
                }
                lp = LoginProvider.Internal;
                break;
            }


            if (user == null && lp != LoginProvider.Internal)  //create the user if doesn't exist
            {
                user = new User
                {
                    RemoteId      = json["id"].Value <string>(),
                    LoginProvider = lp
                };
                switch (lp)
                {
                case LoginProvider.Twitter:
                    user.UserName = json["screenName"].Value <string>();
                    break;

                case LoginProvider.Facebook:
                    user.FirstName = json["firstname"].Value <string>();
                    user.LastName  = json["lastname"].Value <string>();
                    user.UserName  = json["name"].Value <string>();
                    user.Email     = json["email"].Value <string>();
                    break;

                case LoginProvider.Google:
                    user.UserName = json["email"].Value <string>();
                    user.Email    = json["email"].Value <string>();
                    break;
                }

                int newId = UserService.InsertUser(user, () => Redis.AddUser(user));
                user = UserService.GetUser(newId);
            }

            return(Json(user != null ? new
            {
                id = user.Id,
                guid = user.GUID
            } : null));
        }
Exemple #27
0
        protected Boolean SubmitForm()
        {
            StringBuilder formattedHtml         = new StringBuilder();
            StringBuilder formattedInternalHtml = new StringBuilder();
            string        seasonalMonths        = "";

            try
            {
                foreach (ListItem item in cblSeasonal.Items)
                {
                    if (item.Selected)
                    {
                        seasonalMonths += item.Value + " - ";
                    }
                }

                if (seasonalMonths.Length > 3)
                {
                    seasonalMonths = seasonalMonths.Substring(0, seasonalMonths.Length - 3);
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AdminSubmitForm - Get Seasonal Months");
            }

            try
            {
                //Instanciate new model objects for each piece of data to be created
                MerchantModel          newMerchant                        = new MerchantModel();
                MerchantPrincipalModel newMerchantPrincipal               = new MerchantPrincipalModel();
                ContactModel           newMerchantPrincipalContact        = new ContactModel();
                AddressModel           newMerchantPrincipalContactAddress = new AddressModel();
                ContactModel           newContact         = new ContactModel();
                ContactModel           newBusiness        = new ContactModel();
                AddressModel           newBusinessAddress = new AddressModel();
                ProcessorModel         newProcessor       = new ProcessorModel();
                DebitCardModel         newDebitCard       = new DebitCardModel();
                BankModel        newBankModel             = new BankModel();
                BankAccountModel newBankAccountModel      = new BankAccountModel();

                //Set base merchant information in newMerchant object
                if (txtMerchantId.Text != "")
                {
                    newMerchant.MerchantId = txtMerchantId.Text;
                }
                if (txtCorpName.Text != "")
                {
                    newMerchant.CorpName = txtCorpName.Text;
                }
                if (txtDBAName.Text != "")
                {
                    newMerchant.DbaName = txtDBAName.Text;
                }
                if (txtBusLicNumber.Text != "")
                {
                    newMerchant.BusLicNumber = txtBusLicNumber.Text;
                }
                if (txtBusLicType.Text != "")
                {
                    newMerchant.BusLicType = txtBusLicType.Text;
                }
                if (txtBusLicIssuer.Text != "")
                {
                    newMerchant.BusLicIssuer = txtBusLicIssuer.Text;
                }
                if (radBusLicDate.SelectedDate.HasValue)
                {
                    newMerchant.BusLicDate = Convert.ToDateTime(radBusLicDate.SelectedDate);
                }
                if (txtFedTaxId.Text != "")
                {
                    newMerchant.FedTaxId = txtFedTaxId.Text;
                }
                if (txtMerchandiseSold.Text != "")
                {
                    newMerchant.MerchandiseSold = txtMerchandiseSold.Text;
                }
                if (txtYearsInBus.Text != "")
                {
                    newMerchant.YearsInBusiness = Convert.ToInt32(txtYearsInBus.Text);
                }
                if (txtMonthsInBus.Text != "")
                {
                    newMerchant.MonthsInBusiness = Convert.ToInt32(txtMonthsInBus.Text);
                }
                if (rblSeasonal.SelectedValue != "")
                {
                    newMerchant.SeasonalSales = Convert.ToBoolean(rblSeasonal.SelectedValue);
                }
                if (seasonalMonths != "")
                {
                    newMerchant.SeasonalMonths = seasonalMonths;
                }
                if (txtSwipedPct.Text != "")
                {
                    newMerchant.SwipedPct = Convert.ToInt32(txtSwipedPct.Text);
                }
                if (txtAvgMonthlySales.Text != "")
                {
                    newMerchant.AvgMonthlySales = Convert.ToDecimal(txtAvgMonthlySales.Text);
                }
                if (txtHighestMonthlySales.Text != "")
                {
                    newMerchant.HighestMonthlySales = Convert.ToDecimal(txtHighestMonthlySales.Text);
                }
                if (txtAvgWeeklySales.Text != "")
                {
                    newMerchant.AvgWeeklySales = Convert.ToDecimal(txtAvgWeeklySales.Text);
                }
                if (rblHighRisk.SelectedValue != "")
                {
                    newMerchant.HighRisk = Convert.ToBoolean(rblHighRisk.SelectedValue);
                }
                if (txtHighRiskWho.Text != "")
                {
                    newMerchant.HighRiskWho = txtHighRiskWho.Text;
                }
                if (radHighRiskDate.SelectedDate.HasValue)
                {
                    newMerchant.HighRiskDate = Convert.ToDateTime(radHighRiskDate.SelectedDate);
                }
                if (rblBankruptcy.SelectedValue != "")
                {
                    newMerchant.Bankruptcy = Convert.ToBoolean(rblBankruptcy.SelectedValue);
                }
                if (radBankruptcyDate.SelectedDate.HasValue)
                {
                    newMerchant.BankruptcyDate = Convert.ToDateTime(radBankruptcyDate.SelectedDate);
                }

                //Add Legal Org State to merchant
                if (ddlLegalOrgState.SelectedValue != "")
                {
                    Int32 legalOrgStateId = Convert.ToInt32(ddlLegalOrgState.SelectedValue);
                    newMerchant.LegalOrgState = _globalCtx.GeoStates.Where(gs => gs.RecordId == legalOrgStateId).FirstOrDefault();
                }

                //Add Legal Org Type to merchant
                if (ddlLegalOrgType.SelectedValue != "")
                {
                    Int32 legalOrgTypeId = Convert.ToInt32(ddlLegalOrgType.SelectedValue);
                    newMerchant.LegalOrgType = _globalCtx.LegalOrgTypes.Where(lot => lot.RecordId == legalOrgTypeId).FirstOrDefault();
                }

                //Add Merchant Type to Merchant
                if (rblMerchantType.SelectedValue != "")
                {
                    newMerchant.MerchantType = _globalCtx.MerchantTypes.Where(mt => mt.MerchantTypeName == rblMerchantType.SelectedValue).FirstOrDefault();
                }

                //Add MCC to merchant
                if (ddlMCC.SelectedValue != "")
                {
                    Int32 mccId = Convert.ToInt32(ddlMCC.SelectedValue);
                    newMerchant.Mcc = _globalCtx.MerchantCategoryCodes.Where(mcc => mcc.RecordId == mccId).FirstOrDefault();
                }

                //Add Business Contact info - Email, Phone, Fax
                if (txtBusEmail.Text != "")
                {
                    newBusiness.Email = txtBusEmail.Text;
                }
                if (txtBusFax.Text != "")
                {
                    newBusiness.Fax = txtBusFax.Text;
                }
                if (txtBusPhone.Text != "")
                {
                    newBusiness.HomePhone = txtBusPhone.Text;
                }

                _globalCtx.Contacts.Add(newBusiness);

                //Add Business Contact Addess
                if (txtCorpAddress.Text != "")
                {
                    newBusinessAddress.Address = txtCorpAddress.Text;
                }
                if (txtCorpCity.Text != "")
                {
                    newBusinessAddress.City = txtCorpCity.Text;
                }
                if (ddlCorpState.SelectedValue != "")
                {
                    Int32 businessAddressStateId = Convert.ToInt32(ddlCorpState.SelectedValue);
                    newBusinessAddress.State = _globalCtx.GeoStates.Where(gs => gs.RecordId == businessAddressStateId).FirstOrDefault();
                }
                if (txtCorpZip.Text != "")
                {
                    newBusinessAddress.Zip = txtCorpZip.Text;
                }

                _globalCtx.Addresses.Add(newBusinessAddress);

                //Add new Business Contact Address to new Business
                newBusiness.Address = newBusinessAddress;

                //Add new Contact to new Merchant
                newMerchant.Business = newBusiness;

                //Add new Contact
                if (txtContactFirstName.Text != "")
                {
                    newContact.FirstName = txtContactFirstName.Text;
                }
                if (txtContactLastName.Text != "")
                {
                    newContact.LastName = txtContactLastName.Text;
                }
                if (txtContactEmail.Text != "")
                {
                    newContact.Email = txtContactEmail.Text;
                }
                if (txtContactPhone.Text != "")
                {
                    newContact.HomePhone = txtContactPhone.Text;
                }
                if (txtContactFax.Text != "")
                {
                    newContact.Fax = txtContactFax.Text;
                }

                _globalCtx.Contacts.Add(newContact);

                //Add new contact to new Merchant
                newMerchant.Contact = newContact;

                //Add new Merchant Principal
                if (txtPrincipalDLNumber.Text != "")
                {
                    newMerchantPrincipal.PrincipalDLNumber = PWDTK.StringToUtf8Bytes(txtPrincipalDLNumber.Text);
                }
                if (ddlPrincipalDLState.SelectedValue != "")
                {
                    Int32 dlStateId = Convert.ToInt32(ddlPrincipalDLState.SelectedValue);
                    newMerchantPrincipal.PrincipalDLState = _globalCtx.GeoStates.Where(gs => gs.RecordId == dlStateId).FirstOrDefault();
                }
                if (radPrincipalDoB.SelectedDate.HasValue)
                {
                    newMerchantPrincipal.PrincipalDoB = Convert.ToDateTime(radPrincipalDoB.SelectedDate);
                }
                if (txtPrincipalPctOwn.Text != "")
                {
                    newMerchantPrincipal.PrincipalPctOwn = Convert.ToInt32(txtPrincipalPctOwn.Text);
                }

                _globalCtx.MerchantPrincipal.Add(newMerchantPrincipal);

                //Create new contact for Merchant Principal
                if (txtPrincipalFirstName.Text != "")
                {
                    newMerchantPrincipalContact.FirstName = txtPrincipalFirstName.Text;
                }
                if (txtPrincipalLastName.Text != "")
                {
                    newMerchantPrincipalContact.LastName = txtPrincipalLastName.Text;
                }
                if (txtPrincipalMI.Text != "")
                {
                    newMerchantPrincipalContact.MiddleInitial = txtPrincipalMI.Text;
                }
                if (txtPrincipalTitle.Text != "")
                {
                    newMerchantPrincipalContact.Title = txtPrincipalTitle.Text;
                }
                if (txtPrincipalCellPhone.Text != "")
                {
                    newMerchantPrincipalContact.CellPhone = txtPrincipalCellPhone.Text;
                }
                if (txtPrincipalHomePhone.Text != "")
                {
                    newMerchantPrincipalContact.HomePhone = txtPrincipalHomePhone.Text;
                }

                _globalCtx.Contacts.Add(newMerchantPrincipalContact);

                //Create new address for Merchant principal Contact
                if (txtPrincipalAddress.Text != "")
                {
                    newMerchantPrincipalContactAddress.Address = txtPrincipalAddress.Text;
                }
                if (txtPrincipalCity.Text != "")
                {
                    newMerchantPrincipalContactAddress.City = txtPrincipalCity.Text;
                }
                if (ddlPrincipalState.SelectedValue != "")
                {
                    Int32 mpcStateId = Convert.ToInt32(ddlPrincipalState.SelectedValue);
                    newMerchantPrincipalContactAddress.State = _globalCtx.GeoStates.Where(gs => gs.RecordId == mpcStateId).FirstOrDefault();
                }
                if (txtPrincipalZip.Text != "")
                {
                    newMerchantPrincipalContactAddress.Zip = txtPrincipalZip.Text;
                }

                _globalCtx.Addresses.Add(newMerchantPrincipalContactAddress);

                //Add new address to Merchant Principal Contact
                newMerchantPrincipalContact.Address = newMerchantPrincipalContactAddress;

                //Add new Contact to Merchant Principal
                newMerchantPrincipal.Contact = newMerchantPrincipalContact;

                //Add new Principal to the new merchant
                newMerchant.MerchantPrincipal = newMerchantPrincipal;

                //Check if merchant processor already exists, if so link to merchant.  If not, create it and add to merchant.
                if (txtCardProcessor.Text != "")
                {
                    if (_globalCtx.Processor.Where(p => p.ProcessorName == txtCardProcessor.Text.Trim()).ToList().Count > 0)
                    {
                        newMerchant.Processor = _globalCtx.Processor.First(p => p.ProcessorName == txtCardProcessor.Text.Trim());
                    }
                    else
                    {
                        newProcessor.ProcessorName = txtCardProcessor.Text.Trim();
                        _globalCtx.Processor.Add(newProcessor);
                        newMerchant.Processor = newProcessor;
                    }
                }

                _globalCtx.Banks.Add(newBankModel);

                newBankAccountModel.Bank = newBankModel;
                newDebitCard.Bank        = newBankModel;

                _globalCtx.BankAccounts.Add(newBankAccountModel);
                _globalCtx.DebitCards.Add(newDebitCard);

                newMerchant.BankAccount = newBankAccountModel;
                newMerchant.DebitCard   = newDebitCard;

                //Set Merchant Status to "Admin Registered"
                newMerchant.MerchantStatus = _globalCtx.MerchantStatuses.FirstOrDefault(ms => ms.StatusDescription == "Pre-Enrolled");

                //Set Underwriting Status to "Pending"
                newMerchant.UnderwritingStatus = _globalCtx.UnderwritingStatuses.FirstOrDefault(ms => ms.StatusDescription == "Pending");

                newMerchant.AdvancePlan = _globalCtx.AdvancePlans.First(ap => ap.DefaultPlan == true);

                //Add new Merchant to context
                _globalCtx.Merchants.Add(newMerchant);

                //Add new merchant to selected User
                if (txtSelectedUserName.Text != "")
                {
                    var             manager      = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(_globalCtx));
                    ApplicationUser selectedUser = manager.FindByName(txtSelectedUserName.Text);
                    if (selectedUser != null)
                    {
                        selectedUser.Merchant = newMerchant;

                        //Save Context and Update DB
                        _globalCtx.SaveChanges();
                    }
                }
                else
                {
                    lblSubmissionMessage.Text = "Please select a User to join with this merchant.";
                    return(false);
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AdminSubmitForm - Add Data to DB");
                return(false);
            }

            return(true);
        }
Exemple #28
0
        private bool PasswordMeetsPolicy(String Password, PWDTK.PasswordPolicy PassPolicy)
        {
            PasswordPolicyException pwdEx = new PasswordPolicyException("");

            return(PWDTK.TryPasswordPolicyCompliance(Password, PassPolicy, ref pwdEx));
        }
Exemple #29
0
        /*
         * 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);
                }
            }
        }
Exemple #30
0
        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;
            }
        }