Example #1
0
        private bool ValidateUser(string userName, string passWord)
        {
            // Try this code for now. If it works, everything below it should be ignored
            // because of the return clause
            if ((0 == string.Compare(userName, "Admin", true)) && (0 == string.Compare(passWord, "Admin", true)))
            {
                return(true);
                // should allow login now.
            }

            // 4/3/18: Added variables cmd2(SqlCommand), lookupSalt(string)
            // and passwordPlusSalt(string)
            string            lookupSalt       = null;
            string            passwordPlusSalt = null;
            HasherOfPasswords hash             = new HasherOfPasswords();

            // Check for invalid userName.
            // userName must not be null and must be between 1 and 15 characters.
            if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
                return(false);
            }

            // Check for invalid passWord.
            // passWord must not be null and must be between 1 and 25 characters.
            if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
                return(false);
            }

            using (LacklusterEntities entity = new LacklusterEntities())
            {
                try
                {
                    employee emp = entity.employees.Where(e => e.userName == userName).SingleOrDefault();

                    if (emp == null)
                    {
                        return(false);
                    }
                    else
                    {
                        txtIsManager.Value = emp.manager.ToString();
                        lookupSalt         = emp.salt;
                        passwordPlusSalt   = passWord + lookupSalt;
                        passWord           = hash.HashPassword(passwordPlusSalt);
                        return(emp.llv_password == passWord);
                    }
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
Example #2
0
        private bool ValidateUser(string userName, string passWord)
        {
            /*
             * if((0 == string.Compare(userName, "Admin", true)) && (0 == string.Compare(passWord, "Admin", true)))
             * {
             *  return true;
             *  // should allow login now.
             * }
             */
            // 4/3/18: Added variables cmd2(SqlCommand), lookupSalt(string)
            // and passwordPlusSalt(string)

            SqlConnection conn;
            SqlCommand    cmd;
            SqlCommand    cmd2; // salt look up
            string        lookupPassword   = null;
            string        lookupSalt       = null;
            string        passwordPlusSalt = null;

            // Check for invalid userName.
            // userName must not be null and must be between 1 and 15 characters.
            if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
                return(false);
            }

            // Check for invalid passWord.
            // passWord must not be null and must be between 1 and 25 characters.
            if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
                return(false);
            }

            try
            {
                // Consult with your SQL Server administrator for an appropriate connection
                // string to use to connect to your local SQL Server.
                conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                conn = new SqlConnection();
                conn.Open();

                // Create SqlCommand to select pwd field from users table given supplied userName.
                cmd = new SqlCommand("Select llv_password from users where userName=@userName", conn);
                cmd.Parameters.Add("@userName", SqlDbType.VarChar, 25);
                cmd.Parameters["@userName"].Value = userName;

                // Execute command and fetch pwd field into lookupPassword string.
                lookupPassword = (string)cmd.ExecuteScalar();

                // Create SqlCommand to select salt field from users table given supplied username.
                // Execute command and fect salt field into lookupSalt string.
                cmd2 = new SqlCommand("Select salt from users where userName=@userName", conn);
                cmd2.Parameters.Add("@userName", SqlDbType.VarChar, 25);
                cmd2.Parameters["@username"].Value = userName;
                lookupSalt = (string)cmd2.ExecuteScalar();

                // Cleanup command and connection objects.
                cmd.Dispose();
                conn.Dispose();
                cmd2.Dispose();
            }
            catch (Exception ex)
            {
                // Add error handling here for debugging.
                // This error message should not be sent back to the caller.
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
            }

            // If no password found, return false.
            if (null == lookupPassword)
            {
                // You could write failed login attempts here to event log for additional security.
                return(false);
            }
            else
            {
                // Consult with your SQL Server administrator for an appropriate connection
                // string to use to connect to your local SQL Server.
                conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                conn = new SqlConnection();
                conn.Open();

                // Create SqlCommand to select pwd field from users table given supplied userName.
                cmd = new SqlCommand("Select manager from users where userName=@userName", conn);
                cmd.Parameters.Add("@userName", SqlDbType.VarChar, 25);
                cmd.Parameters["@userName"].Value = userName;

                // Execute command and fetch pwd field into lookupPassword string.
                txtIsManager.Value = (string)cmd.ExecuteScalar();
            }

            /* Hash input password ('passWord' + 'lookupSalt') in here
             * Use a variable to store the output of the hash. Can use the same parameter
             * 'passWord' passed into this method. Contents will be replaced with new hash value.
             * can hardcode it in here or code a function that takes an input, hashes it, then returns
             * the output.
             * Input------->Hash Function-------->Output(returned)
             */
            passwordPlusSalt = passWord + lookupSalt;
            HasherOfPasswords hasher = new HasherOfPasswords();

            passWord = hasher.HashPassword(passwordPlusSalt);



            // Compare lookupPassword and input passWord, using a case-sensitive comparison.
            // Note about this atrocious segment of code:
            // For the demo, Sidener can just enter "Admin" for both usernames and password, not case sensitive.
            // Reminder to delete the code that allows "Admin" to login
            return(0 == string.Compare(lookupPassword, passWord, false));
        }
Example #3
0
        protected void eAddEmployee_Click(object sender, EventArgs e)
        {
            /* Edited 4/16/18:
             * passwordPlusSalt is input to Hash algorithm and the output
             * is saved to the DB
             */
            string                lookupSalt       = null;
            string                passwordPlusSalt = null;
            string                passwordString   = ePassword.Text.ToString();
            SaltGenerator         salt             = new SaltGenerator();
            HasherOfPasswords     hash             = new HasherOfPasswords();
            FormValidatorClass    fv = new FormValidatorClass();
            DuplicateCheckerClass dc = new DuplicateCheckerClass();

            /* TODO
             * These variables will be used to check for validation.
             * inputs will be stored in here and checked for validation
             * before being stored as a DB entry.
             *
             */
            string firstNameStr = eFirstName.Text.ToString();
            string lastNameStr  = eLastName.Text.ToString();
            string stAddressStr = eAddress.Text.ToString();
            string stateStr     = eState.Text.ToString();
            string phoneStr     = ePhoneNumber.Text.ToString();
            string zipStr       = eZipCode.Text.ToString();
            string userNameStr  = eUsername.Text.ToString();
            bool   pageValid    = true;

            // validate if person already exists
            bool duplicatePerson = dc.AlreadyExists(firstNameStr, lastNameStr, stAddressStr, userNameStr);

            if (duplicatePerson)
            {
                // then this person already exists in the records
                // TODO: write code in here that alerts the AddEmployee.aspx page of a dulpicate
                // entry attempt. For now, NULL the values so they will not be passed to the DB
                firstNameStr          = null;
                lastNameStr           = null;
                stAddressStr          = null;
                userNameStr           = null;
                rfvFirst.ErrorMessage = "Required, Person you entered already exists";
                rfvLast.ErrorMessage  = "Required, Person you entered already exists";
                rfvFirst.ForeColor    = System.Drawing.Color.Red;
                rfvLast.ForeColor     = System.Drawing.Color.Red;
                pageValid             = false;
            }
            // No need for else, keep validating... If entry does not exist in DB, values
            // won't be nulled. Essentially, values are nulled to force the
            // ASP:RequiredFieldValidator to throw an error.

            // validate state intial
            bool validState = fv.IsValidState(stateStr);

            if (!validState)
            {
                // State is not valid.
                // TODO: write code in here that alerts the AddEmployee.aspx page of an invalid
                // state. For now, NULL the values so they will not be passed to the DB
                stateStr = null;
                rfvState.ErrorMessage = "Required, Enter a valid US state initial (CA, IL, GA)";
                rfvState.ForeColor    = System.Drawing.Color.Red;
                pageValid             = false;
            }
            // No need for else, keep validating...

            // validate phone number
            bool validPhone = fv.IsValidPhone(phoneStr);

            if (!validPhone)
            {
                // Phone number is not valid.
                // TODO: write code that alerts AddEmployee.aspx page of an invalid phone.
                // NULL the value so it will not be passed to the DB.
                phoneStr = null;
                rfvPhone.ErrorMessage = "Required, Enter a valid phone number";
                rfvPhone.ForeColor    = System.Drawing.Color.Red;
                pageValid             = false;
            }

            // validate zip
            bool validZip = fv.IsValidZip(zipStr);

            if (!validZip)
            {
                // Zip Code is not valid.
                // TODO: write code that alerts AddEmployee.aspx page of an invalid zip.
                // NULL the value so it will not be passed to the DB.
                zipStr = null;
                rfvZip.ErrorMessage = "Required, Enter a Valid Zip Code";
                rfvZip.ForeColor    = System.Drawing.Color.Red;
                pageValid           = false;
            }

            // save to DB only if entries are validated.
            if (pageValid == true)
            {
                using (LacklusterEntities entity = new LacklusterEntities())
                {
                    employee em = new employee();
                    em.firstName     = firstNameStr;
                    em.lastName      = lastNameStr;
                    em.streetAddress = stAddressStr;
                    em.city          = eCity.Text.ToString();
                    em.state         = stateStr;
                    em.phone         = phoneStr;
                    em.userName      = userNameStr;

                    lookupSalt       = salt.SaltMe(em.firstName, em.lastName);
                    passwordPlusSalt = passwordString + lookupSalt;
                    em.llv_password  = hash.HashPassword(passwordPlusSalt);
                    em.salt          = lookupSalt;

                    //em.llv_password = ePassword.Text;
                    //eUsername.Text = passwordPlusSalt;

                    em.manager = eIsManager.Checked;
                    em.active  = true;


                    int zipFromString = 0;
                    int.TryParse(zipStr, out zipFromString);

                    em.zip = zipFromString;

                    /*
                     * if (zipFromString != 0)
                     * {
                     *  em.zip = zipFromString;
                     * }
                     * else
                     * {
                     *  em.zip = 99999;
                     * }
                     */
                    entity.employees.Add(em);
                    entity.SaveChanges();
                }
            }
            else
            {
                // redirect?
            }
            Response.Redirect("~/Management/ManageEmployee.aspx");
        }
        protected void btnComplete_Click(object sender, EventArgs e)
        {
            string lookupSalt       = null;
            string passwordPlusSalt = null;
            string passwordString   = ePassword.Text.ToString();
            string stateStr         = eState.Text.ToString();
            string zipStr           = eZipCode.Text.ToString();
            string phoneStr         = ePhoneNumber.Text.ToString();
            bool   pageValid        = true;

            // TODO: Form validator code
            SaltGenerator      salt = new SaltGenerator();
            HasherOfPasswords  hash = new HasherOfPasswords();
            FormValidatorClass fv   = new FormValidatorClass();

            // validate state, zip and phone
            bool validState = fv.IsValidState(stateStr);

            if (!validState)
            {
                // invalid state
                // TODO: notify EditEmployee.aspx of invalid state
                stateStr = null;
                rfvState.ErrorMessage = "Required, enter a valid US state initial(CA, IL, GA)";
                rfvState.ForeColor    = System.Drawing.Color.Red;
                pageValid             = false;
            }

            bool validZip = fv.IsValidZip(zipStr);

            if (!validZip)
            {
                // invalid zip
                // TODO: notify EditEmployee.aspx of invalid zip
                zipStr = null;
                rfvZip.ErrorMessage = "Required, enter a valid Zip Code";
                rfvZip.ForeColor    = System.Drawing.Color.Red;
                pageValid           = false;
            }

            bool validPhone = fv.IsValidPhone(phoneStr);

            if (!validPhone)
            {
                // invalid phone
                // TODO: notify EditEmployee.aspx of invalid phone
                phoneStr = null;
                rfvPhone.ErrorMessage = "Required, enter a valid phone number";
                rfvPhone.ForeColor    = System.Drawing.Color.Red;
                pageValid             = false;
            }

            // save to DB only if entries are validated
            if (pageValid == true)
            {
                using (LacklusterEntities entity = new LacklusterEntities())
                {
                    empID = Int32.Parse(Request.QueryString["ID"]);
                    employee emp = entity.employees.Where(em => em.empID == empID).Single();
                    emp.firstName     = eFirstName.Text;
                    emp.lastName      = eLastName.Text;
                    emp.streetAddress = eAddress.Text;
                    emp.city          = eCity.Text;
                    emp.state         = stateStr;
                    int zipFromString = 0;
                    int.TryParse(zipStr, out zipFromString);
                    emp.zip = zipFromString;

                    /*
                     * if (zipFromString != 0)
                     * {
                     *  emp.zip = zipFromString;
                     * }
                     */
                    emp.phone = phoneStr;

                    // generate new salt and take new password
                    lookupSalt       = salt.SaltMe(emp.firstName, emp.lastName);
                    passwordPlusSalt = passwordString + lookupSalt;
                    emp.llv_password = hash.HashPassword(passwordPlusSalt);
                    emp.salt         = lookupSalt;

                    emp.manager = eIsManager.Checked;
                    entity.SaveChanges();
                }
            }
            else
            {
                // redirect
            }

            Response.Redirect("EditEmployee.aspx");
        }
Example #5
0
        static void Main(string[] args)
        {
            HasherOfPasswords  testHash = new HasherOfPasswords();
            SaltGenerator      testSalt = new SaltGenerator();
            FormValidatorClass testFV   = new FormValidatorClass();

            // 1. Test Hash Function, same passwords
            // Expected Result: Hashes Match
            string passwordEx1 = "TerrorBladeTheDemonMarauder";
            string passwordEx2 = "TerrorBladeTheDemonMarauder";
            string fromHasher1;
            string fromHasher2;

            fromHasher1 = testHash.HashPassword(passwordEx1);
            fromHasher2 = testHash.HashPassword(passwordEx2);
            Console.WriteLine("Test 1");
            if (0 == string.Compare(fromHasher1, fromHasher2, false))
            {
                Console.WriteLine("Hashes Match, Test Passed");
            }
            else
            {
                Console.WriteLine("Hashes Do Not Match. Test Failed");
            }
            Console.WriteLine(" ");

            // 2. Different Passwords, uncapitalize a single letter
            // Expected result: Hashes Do Not Match
            string passwordEx3 = "terrorBladeTheDemonMarauder";
            string fromHasher3 = testHash.HashPassword(passwordEx3);

            Console.WriteLine("Test 2");
            if (0 == string.Compare(fromHasher1, fromHasher3, false))
            {
                Console.WriteLine("Hashes Match, Test Failed");
            }
            else
            {
                Console.WriteLine("Hashes Do Not Match, Test Passed");
            }
            Console.WriteLine(" ");

            // Salt test
            // 3. Same person generates same salts
            // Expected result: Salts Match
            string firstName1 = "Tom";
            string lastName1  = "Riddle";
            string firstName2 = "Tom";
            string lastName2  = "Riddle";
            string fromSalt1  = testSalt.SaltMe(firstName1, lastName1);
            string fromSalt2  = testSalt.SaltMe(firstName2, lastName2);

            Console.WriteLine("Test 3");
            if (0 == string.Compare(fromSalt1, fromSalt2, false))
            {
                Console.WriteLine("Salts Match, Test Passed");
            }
            else
            {
                Console.WriteLine("Salts Do Not Match, Test Failed");
            }
            Console.WriteLine(" ");

            // 4. Different people generates different salts
            // Expected result: Salt Do Not Match
            string firstName3 = "Albus";
            string lastName3  = "Dumbledore";
            string fromSalt3  = testSalt.SaltMe(firstName3, lastName3);

            Console.WriteLine("Test 4");
            if (0 == string.Compare(fromSalt1, fromSalt3, false))
            {
                Console.WriteLine("Salts Match, Test Failed");
            }
            else
            {
                Console.WriteLine("Salts Do Not Match, Test Passed");
            }
            Console.WriteLine(" ");

            // 4b. Test password + salt combo, then hash
            // Expected result: Hashes Match
            string combo1 = testHash.HashPassword(passwordEx1 + fromSalt1);
            string combo2 = testHash.HashPassword(passwordEx2 + fromSalt2);

            Console.WriteLine("Test 4b");
            if (0 == string.Compare(combo1, combo2, false))
            {
                Console.WriteLine("Hashes Match, Test Passed");
            }
            else
            {
                Console.WriteLine("Hashes Do Not Match, Test Failed");
            }
            Console.WriteLine(" ");

            // 4c. Same password, different salts then hash
            // Expected result: Hashes Do No Match
            string combo3 = testHash.HashPassword(passwordEx1 + fromSalt3);

            Console.WriteLine("Test 4c");
            if (0 == string.Compare(combo1, combo3, false))
            {
                Console.WriteLine("Hashes Match, Test Failed");
            }
            else
            {
                Console.WriteLine("Hashes Do Not Match, Test Passed");
            }
            Console.WriteLine(" ");

            // Test the form validators

            // Zip Code Test
            // 5. Valid Zip Code
            // Expected result: Valid Zip Code
            bool validZip = testFV.IsValidZip("91325");

            Console.WriteLine("Test 5");
            if (!validZip)
            {
                Console.WriteLine("Invalid Zip, Test Failed");
            }
            else
            {
                Console.WriteLine("Valid Zip, Test Passed");
            }
            Console.WriteLine(" ");

            // 6. Invalid Zip
            // Expected result: Invalid Zip
            validZip = testFV.IsValidZip("12");
            Console.WriteLine("Test 6");
            if (!validZip)
            {
                Console.WriteLine("Invalid Zip, Test Passed");
            }
            else
            {
                Console.WriteLine("Valid Zip, Test Failed");
            }
            Console.WriteLine(" ");

            // 7. Zip Code is a name
            // Expected result: Invalid zip
            validZip = testFV.IsValidZip("Queen Of Pain");
            Console.WriteLine("Test 7");
            if (!validZip)
            {
                Console.WriteLine("Invalid Zip, Test Passed");
            }
            else
            {
                Console.WriteLine("Valid Zip, Test Failed");
            }
            Console.WriteLine(" ");

            // Phone Number Test
            // 8. Valid US Phone
            // Expected result: Valid US Phone Number
            bool validPhone = testFV.IsValidPhone("8181234567");

            Console.WriteLine("Test 8");
            if (!validPhone)
            {
                Console.WriteLine("Invalid US Phone, Test Failed");
            }
            else
            {
                Console.WriteLine("Valid US Phone, Test Passed");
            }
            Console.WriteLine(" ");

            // 9. Invalid US Phone -> 9 digits only
            // Expected result: Invalid US Phone
            validPhone = testFV.IsValidPhone("818123456");
            Console.WriteLine("Test 9");
            if (!validPhone)
            {
                Console.WriteLine("Invalid US Phone, Test Passed");
            }
            else
            {
                Console.WriteLine("Valid US Phone. Test Failed");
            }
            Console.WriteLine(" ");

            // 10. Valid US Phone with dashes
            // Expected result: Valid US Phone
            validPhone = testFV.IsValidPhone("818-123-4567");
            Console.WriteLine("Test 10");
            if (!validPhone)
            {
                Console.WriteLine("Invalid US Phone, Test Failed");
            }
            else
            {
                Console.WriteLine("Valid US Phone, Test Passed");
            }
            Console.WriteLine(" ");

            // 11. Name written as phone number
            // Expected result: Invalid US Phone
            validPhone = testFV.IsValidPhone("Sven");
            Console.WriteLine("Test 11");
            if (!validPhone)
            {
                Console.WriteLine("Invalid US Phone, Test Passed");
            }
            else
            {
                Console.WriteLine("Valid US Phone, Test Failed");
            }
            Console.WriteLine(" ");

            // US State Initial
            // 12. Valid US State Initial
            // Expected Result: Valid US Zip
            bool validState = testFV.IsValidState("CA");

            Console.WriteLine("Test 12");
            if (!validState)
            {
                Console.WriteLine("Invalid US State, Test Failed");
            }
            else
            {
                Console.WriteLine("Valid US State, Test Passed");
            }
            Console.WriteLine(" ");

            // 13. Invalid state
            // Expected result: Invalid US State
            validState = testFV.IsValidState("Afganistan");
            Console.WriteLine("Test 13");
            if (!validState)
            {
                Console.WriteLine("Invalid US State, Test Passed");
            }
            else
            {
                Console.WriteLine("Valid US State, Test Failed");
            }
            Console.WriteLine(" ");

            // 14. Valid state , 2nd letter is uncapitalized
            // Expected result: Valid US State
            validState = testFV.IsValidState("Hi");
            Console.WriteLine("Test 14");
            if (!validState)
            {
                Console.WriteLine("Invalid US State, Test Failed");
            }
            else
            {
                Console.WriteLine("Valid US State, Test Passed");
            }
            Console.WriteLine(" ");
        }