Ejemplo n.º 1
0
        public void CreateSalt_CreatesSalt()
        {
            var passwordHash = new PasswordHash();
            var salt         = passwordHash.CreateSalt();

            Assert.Less(0, salt.Length);
        }
    public static void Intialize()
    {
        if (initialized == false)
        {
            Presto.Sequence.Add <User>();

            Presto.Define <User>(x => {
                var passwordHash = new PasswordHash();
                x.ID             = Presto.Sequence.Next <User>();
                x.UserName       = "******";
                x.Salt           = passwordHash.CreateSalt();
                x.Password       = passwordHash.CreatePasswordHash("Password", x.Salt);
                x.FirstName      = "First Name";
                x.LastName       = "Last Name";
                x.Role           = Role.Admin;
                x.CreatedDate    = DateTime.Now;
            });

            Presto.PersistAction = entity => {
                var addEntityMethod       = typeof(IClarityDB).GetMethod("AddEntity");
                var addEntityOfTypeMethod = addEntityMethod.MakeGenericMethod(new[] { entity.GetType() });

                addEntityOfTypeMethod.Invoke(ClarityDB.Instance, new object[] { entity });
            };
        }

        initialized = true;
    }
Ejemplo n.º 3
0
        public ActionResult SignUp(User user)
        {
            if (ModelState.IsValid)
            {
                var isExist = db.Users.Where(x => x.Username == user.Username).SingleOrDefault();

                if (isExist != null)
                {
                    ViewBag.message = "This username already used..";
                    return(View());
                }
                var    salt        = PasswordHash.CreateSalt(4);
                String pw          = user.Password + salt;
                var    hashAndSalt = PasswordHash.GetPasswordHashAndSalt(pw);

                user.Password = hashAndSalt;
                user.Salt     = salt;

                db.Users.Add(user);
                db.SaveChanges();
                Session["Username"] = user.Username;
                return(RedirectToAction("Index", "Home"));
            }
            return(View("Signup", user));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Apenas reseta a senha de acesso do usuário para a senha padrão.
        /// </summary>
        /// <param name="id">Código do usuário que terá a senha resetada</param>
        /// <returns></returns>
        public Usuario ResetarSenha(int id)
        {
            using (var context = new DatabaseContext())
            {
                var entity = context.Usuario.FirstOrDefault(a => a.IdUsuario == id);
                if (entity == null)
                {
                    throw new BusinessException("Usuário não encontrado");
                }

                entity.Senha              = PasswordHash.CreateHash(DEFAULT_PASSWORD);
                entity.SenhaSalt          = PasswordHash.CreateSalt();
                entity.DataHoraAlteracao  = DateTime.Now;
                entity.IdUsuarioAlteracao = GetLoggedUser().IdUsuario;
                entity.PrimeiroAcesso     = true;

                context.Entry(entity).State = EntityState.Modified;

                var result = context.SaveChanges() > 0;
                if (result)
                {
                    RegistrarLogAtividade(entity, RESETAR_SENHA);
                }

                return(entity);
            }
        }
Ejemplo n.º 5
0
        public UserCreateResult RegisterUser(ApiUserEntity user)
        {
            if (user == null)
            {
                return(UserCreateResult.Failed);
            }

            // check if the username doesnt exist already
            if (_userRepository.UserNameExists(user.Username))
            {
                return(UserCreateResult.NameAlreadyExists);
            }

            // create password for this user.
            user.Salt     = PasswordHash.CreateSalt(user.Username, NumberExtension.GetRandomUniqueCodeWithLength(10));
            user.Password = PasswordHash.HashPassword(user.Salt, user.Password);

            // add the user.
            _userRepository.Add(user);

            // save changes.
            _uow.SaveChanges();

            return(UserCreateResult.Success);
        }
Ejemplo n.º 6
0
        public ActionResult Create(FormCollection frm)
        {
            Sys_User saveUser = new Sys_User();

            saveUser.FullName = frm["FullName"];
            saveUser.Email    = frm["Email"];
            string password = frm["Password"];

            saveUser.DepartmentId = Convert.ToInt32(frm["DepartmentId"]);
            saveUser.UserType     = Convert.ToInt32(frm["UserTypeId"]);

            string passwordSalt = CryptoService.CreateSalt(10);
            string passwordHash = CryptoService.GenerateSHA256Hash(password, passwordSalt);

            saveUser.PasswordSalt = Convert.ToString(passwordSalt);
            saveUser.Password     = Convert.ToString(passwordHash);

            if (frm["IsActive"] == "Y")
            {
                saveUser.IsActive = true;
            }
            else
            {
                saveUser.IsActive = false;
            }

            saveUser.EnteredDate = DateTime.Now;
            saveUser.EnteredBy   = Convert.ToInt32(Session["UserId"]);

            db.AddUsers(saveUser);
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 7
0
        public void CreatePasswordHash_CreatesHash()
        {
            var passwordHash = new PasswordHash();
            var salt         = passwordHash.CreateSalt();
            var hash         = passwordHash.CreatePasswordHash("abc123@X", salt);

            Assert.Less(0, hash.Length);
        }
Ejemplo n.º 8
0
        protected void ChangeProfile_Click(object sender, EventArgs e)
        {
            String       OrigPassword       = Request.Form["ctl00$MainContent$CurrentPassword"].ToString().Trim();
            Regex        regex              = new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}");
            Match        matchOrig          = regex.Match(OrigPassword);
            PasswordHash PasswordHasher     = new PasswordHash();
            String       Salt               = PasswordHasher.CreateSalt(SessionVariables.UserName.ToLower());
            String       OrigHashedPassword = PasswordHasher.HashPassword(Salt, OrigPassword);

            if (OrigHashedPassword == HashedPasswordFromDB)
            {
                String NewHashedPassword = HashedPasswordFromDB;
                // Set our variables to the new inputs
                Email         = Request.Form["ctl00$MainContent$emailInput"].ToString();
                Sponsor       = Request.Form["ctl00$MainContent$sponsorText"].ToString();
                SteamHandle   = Request.Form["ctl00$MainContent$SteamHandleTB"].ToString();
                BattleHandle  = Request.Form["ctl00$MainContent$BattleHandleTB"].ToString();
                OriginHandle  = Request.Form["ctl00$MainContent$OriginHandleTB"].ToString();
                TwitterHandle = Request.Form["ctl00$MainContent$TwitterHandleTB"].ToString();

                if (Request.Form["ctl00$MainContent$ActiveCheckbox"] == "on")
                {
                    isActive = true;
                }
                else
                {
                    isActive = false;
                }

                UpdateFields();

                if (Request.Form["ctl00$MainContent$NewPassword"].ToString() != "" && Request.Form["ctl00$MainContent$NewPasswordConfirm"].ToString() != "")
                {
                    String NewPassword = Request.Form["ctl00$MainContent$NewPassword"].ToString().Trim();
                    Match  matchNew    = regex.Match(NewPassword);
                    NewHashedPassword = PasswordHasher.HashPassword(Salt, NewPassword);
                }

                using (MySqlCommand cmd = new MySqlCommand("UPDATE useraccount SET Email = \'" + Email + "\', Cerner = \'" + Sponsor + "\', Active = " + isActive + ", Password = \'" + NewHashedPassword + "\', SteamHandle = \'" + SteamHandle + "\', BattleHandle = \'" + BattleHandle + "\', OriginHandle = \'" + OriginHandle + "\', TwitterHandle = \'" + TwitterHandle + "\' WHERE useraccount.Username = \'" + SessionVariables.UserName + "\'", new MySqlConnection(ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString)))
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    ProfileUpdateMessage.Text = "Profile Successfully Updated!";
                }
            }
            else
            {
                ProfileUpdateMessage.Text = "Original Password Does Not Match!";
            }
        }
Ejemplo n.º 9
0
        private bool Insert(UsuarioForm model)
        {
            using (var context = new DatabaseContext())
            {
                var emailExistente = context.Usuario.FirstOrDefault(a => a.Email == model.Email);
                if (emailExistente != null)
                {
                    throw new BusinessException($"O e-mail {model.Email} já está sendo utilizado, escolha outro e-mail para continuar");
                }

                var entity = new Usuario();

                entity.DataHoraCadastro   = CurrentDateTime;
                entity.DataHoraAlteracao  = CurrentDateTime;
                entity.IdUsuarioCadastro  = IdUsuarioLogado;
                entity.IdUsuarioAlteracao = IdUsuarioLogado;
                entity.Status             = (int)DefaultStatusEnum.Ativo;
                entity.Nome           = model.Nome;
                entity.Email          = model.Email;
                entity.Senha          = PasswordHash.CreateHash(DEFAULT_PASSWORD);
                entity.SenhaSalt      = PasswordHash.CreateSalt();
                entity.PrimeiroAcesso = true;

                context.Set <Usuario>().Add(entity);

                foreach (var item in model.Clinicas)
                {
                    var clinica = new Clinica_Usuario();
                    clinica.DataHoraCadastro   = CurrentDateTime;
                    clinica.DataHoraAlteracao  = CurrentDateTime;
                    clinica.IdUsuarioCadastro  = IdUsuarioLogado;
                    clinica.IdUsuarioAlteracao = IdUsuarioLogado;
                    clinica.Status             = (int)DefaultStatusEnum.Ativo;
                    clinica.IdUsuario          = entity.IdUsuario;
                    clinica.IdClinica          = item.IdClinica;
                    clinica.IdUsuarioGrupo     = item.IdUsuarioGrupo;

                    context.Set <Clinica_Usuario>().Add(clinica);
                }

                var result = context.SaveChanges() > 0;
                if (result)
                {
                    RegistrarLogAtividade(entity, PERMISSAO_CADASTRO);
                }
                return(result);
            }
        }
Ejemplo n.º 10
0
        public ActionResult ChangePassword(FormCollection frm)
        {
            Sys_User changeUserPass = new Sys_User();

            int      userId = Convert.ToInt32(Session["UserId"]);
            Sys_User detail = db.getUesrDetailByUserId(userId);

            string dbOldPassword   = detail.Password;
            string dbpasswordSalt  = detail.PasswordSalt;
            string OldpasswordHash = CryptoService.GenerateSHA256Hash(frm["OldPassword"], dbpasswordSalt);

            var checkOldPass = db.CheckOldPassword(OldpasswordHash);

            if (frm["NewPassword"] == frm["RePassword"])
            {
                if (dbOldPassword == OldpasswordHash && checkOldPass != null)
                {
                    string password = frm["NewPassword"];

                    string passwordSalt = CryptoService.CreateSalt(10);
                    string passwordHash = CryptoService.GenerateSHA256Hash(password, passwordSalt);
                    changeUserPass.PasswordSalt    = Convert.ToString(passwordSalt);
                    changeUserPass.Password        = Convert.ToString(passwordHash);
                    changeUserPass.LastUpdatedBy   = userId;
                    changeUserPass.LastUpdatedDate = DateTime.Now;
                    db.ChangePassword(changeUserPass, userId);
                    ViewBag.Message = "Password Changed";
                }
            }
            else
            {
                ViewBag.Message = "Password MissMatch!!!";
            }


            return(View());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Apenas altera a senha de acesso do usuário. Somente o usuário logado poderá alterar sua senha.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AlterarSenha(AlterarSenhaModel model)
        {
            if (model.IdUsuario != GetLoggedUser().IdUsuario)
            {
                throw new BusinessException("Não é permitido alterar a senha de outro usuário");
            }
            if (model.Senha != model.Confirmar)
            {
                throw new BusinessException("As senhas informadas não conferem");
            }

            using (var context = new DatabaseContext())
            {
                var entity = context.Usuario.FirstOrDefault(a => a.IdUsuario == model.IdUsuario);
                if (entity == null)
                {
                    throw new BusinessException("Usuário não encontrado");
                }

                entity.Senha              = PasswordHash.CreateHash(model.Senha);
                entity.SenhaSalt          = PasswordHash.CreateSalt();
                entity.DataHoraAlteracao  = DateTime.Now;
                entity.IdUsuarioAlteracao = GetLoggedUser().IdUsuario;
                entity.PrimeiroAcesso     = false;

                context.Entry(entity).State = EntityState.Modified;

                var result = context.SaveChanges() > 0;
                if (result)
                {
                    RegistrarLogAtividade(entity, ALTERAR_SENHA);
                }

                return(result);
            }
        }
Ejemplo n.º 12
0
        protected void PasswordChange_Click(object sender, EventArgs e)
        {
            string Password           = Request.Form["ctl00$MainContent$inputCurrentPassword"].ToString().Trim();
            string NewPassword        = Request.Form["ctl00$MainContent$inputNewPassword"].ToString().Trim();
            string ConfirmNewPassword = Request.Form["ctl00$MainContent$inputConfirmNewPassword"].ToString().Trim();
            // Check for NewPassword for length requirements.
            Regex Passregex = new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}");
            Match match     = Passregex.Match(NewPassword);

            // This is where we change the password.

            if (!String.IsNullOrEmpty(Password) && !String.IsNullOrEmpty(NewPassword) &&
                !String.IsNullOrEmpty(ConfirmNewPassword) &&
                !String.IsNullOrEmpty(NewPassword) && match.Success && NewPassword == ConfirmNewPassword)
            {
                //Hash Users Password.
                PasswordHash PasswordHasher    = new PasswordHash();
                string       Salt              = PasswordHasher.CreateSalt(SessionVariables.UserName.ToLower());
                string       HashedPassword    = PasswordHasher.HashPassword(Salt, Password);
                string       HashedNewPassword = PasswordHasher.HashPassword(Salt, NewPassword);


                // Update the Database.
                MySqlCommand cmd           = null;
                string       SqlConnection = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;
                try
                {
                    cmd             = new MySqlCommand("spChangePassword", new MySqlConnection(SqlConnection));
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                    cmd.Parameters.AddWithValue("UserName", SessionVariables.UserName);
                    cmd.Parameters.AddWithValue("CurrentPassword", HashedPassword);
                    cmd.Parameters.AddWithValue("NewPassword", HashedNewPassword);

                    cmd.Connection.Open();
                    int ID = Convert.ToInt32(cmd.ExecuteScalar());

                    switch (ID)
                    {
                    case -1:
                        AccountManagements   = "changepassword";
                        changePasswordSucess = true;
                        // Password Changed Sucessfully.
                        break;

                    case -2:
                        AccountManagements        = "changepassword";
                        ChangePasswordErrorString = "Your Input Sucks!";
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    // Redirect to Error Page.
                }
                finally
                {
                    if (cmd.Connection != null)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
            else
            {
                AccountManagements        = "changepassword";
                ChangePasswordErrorString = "Don’t worry, we have server side Validations! \n Check missing fields, and Password must contain at least 6 characters, including UPPER/lowercase and numbers";
            }
        }
Ejemplo n.º 13
0
        protected void Recovery_Click(object sender, EventArgs e)
        {
            AccountManagements = "recovery";

            string RadioRecovery = Request.Form["RadioRecovery"].ToString().Trim();

            if (RadioRecovery.Equals("1"))
            {
                if (Request.Form["sequence"].ToString().Trim().Equals("1"))
                {
                    string RecoveryEmail = Request.Form["ctl00$MainContent$Email"].ToString().Trim();
                    if (RecoveryEmail.Length != 0)
                    {
                        MySqlCommand cmd      = null;
                        String       UserInfo = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;
                        try
                        {
                            cmd             = new MySqlCommand("spValidateUserEmail", new MySqlConnection(UserInfo));
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;

                            cmd.Parameters.AddWithValue("email", RecoveryEmail);

                            cmd.Connection.Open();
                            int userID = Convert.ToInt32(cmd.ExecuteScalar());
                            switch (userID)
                            {
                            case -1:
                                SessionVariables.recoveryCode = Guid.NewGuid().ToString();
                                string subject = "KcGameOn Account: Password change request";
                                string body    = "Behold,";
                                body += "<br /><br />This is an automated message generated by KcGameOn administration to help you reset your KcGameOn password.";
                                body += "<br /><br />Please enter the following code into the Verification Code field.";
                                body += "<br /><br /><b>" + SessionVariables.recoveryCode + "</b>";
                                body += "<br /><br />Thanks,";
                                body += "<br />KcGameOn Team!";
                                MailClient Mailsender = new MailClient();
                                Mailsender.SendEmail(body, subject, RecoveryEmail);
                                SessionVariables.iSeq = 2;
                                break;

                            case -2:
                                // UserNot Found
                                SessionVariables.iSeq = 1;
                                recoveryError.Text    = "Unable to validate an Email!";
                                break;

                            default:
                                break;
                            }
                        }
                        catch
                        {
                            Response.Redirect("/ErrorPage/Error.aspx");
                        }
                        finally
                        {
                            if (cmd.Connection != null)
                            {
                                cmd.Connection.Close();
                            }
                        }
                    }
                }
                else if (Request.Form["sequence"].ToString().Trim().Equals("2"))
                {
                    if (Request.Form["ctl00$MainContent$inputCode"].ToString().Trim().Equals(SessionVariables.recoveryCode))
                    {
                        string recoveryNewPass       = Request.Form["ctl00$MainContent$inputRecoveryNewPass"].ToString().Trim();
                        string recoveryConfirmedPass = Request.Form["ctl00$MainContent$inputConfirmRecoverNewPass"].ToString().Trim();
                        string RecoveryEmail         = Request.Form["RecoveryEmail"].ToString().Trim();

                        string username = null;
                        Regex  regex    = new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}");
                        Match  match    = regex.Match(recoveryNewPass);

                        if (match.Success && recoveryNewPass == recoveryConfirmedPass && !string.IsNullOrEmpty(RecoveryEmail))
                        {
                            //Hash Users Password.
                            PasswordHash PasswordHasher = new PasswordHash();
                            // Get Username inorder to Salt the password.
                            MySqlCommand    cmd           = null;
                            MySqlDataReader Reader        = null;
                            string          SqlConnection = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;

                            try
                            {
                                cmd             = new MySqlCommand("spGetUserInfo", new MySqlConnection(SqlConnection));
                                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                                cmd.Parameters.AddWithValue("UserName", "");
                                // Add Email Variable.
                                cmd.Parameters.AddWithValue("Email", RecoveryEmail);

                                cmd.Connection.Open();
                                Reader = cmd.ExecuteReader();
                                while (Reader.Read())
                                {
                                    username = Reader.GetString("Username").ToString().ToLower();
                                }
                            }
                            finally
                            {
                                if (cmd.Connection != null)
                                {
                                    cmd.Connection.Close();
                                }
                                if (Reader != null)
                                {
                                    Reader.Close();
                                }
                            }

                            if (!string.IsNullOrEmpty(username))
                            {
                                string Salt = PasswordHasher.CreateSalt(username.ToLower());
                                string HashedNewPassword = PasswordHasher.HashPassword(Salt, recoveryNewPass);
                                cmd = null;

                                try
                                {
                                    cmd             = new MySqlCommand("spChangePasswordAccountRecovery", new MySqlConnection(SqlConnection));
                                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                                    cmd.Parameters.AddWithValue("UserName", username);
                                    cmd.Parameters.AddWithValue("NewPassword", HashedNewPassword);
                                    cmd.Parameters.AddWithValue("Email", RecoveryEmail);

                                    cmd.Connection.Open();
                                    int ID = Convert.ToInt32(cmd.ExecuteScalar());

                                    switch (ID)
                                    {
                                    case -1:
                                        SessionVariables.iSeq = 3;
                                        // Password Changed Sucessfully.
                                        break;

                                    case -2:
                                        //There was an error while updating password.
                                        break;

                                    default:
                                        break;
                                    }
                                }
                                finally
                                {
                                    if (cmd.Connection != null)
                                    {
                                        cmd.Connection.Close();
                                    }
                                }
                            }
                            // If password update successful, only then set the iSeq to 3.
                        }
                        else
                        {
                            recoveryError1.Text   = "Error Validating Password!";
                            SessionVariables.iSeq = 2;
                            // Password Must match.
                        }
                        // All Golden
                    }
                    else // Wrong Code.
                    {
                        recoveryError1.Text   = "Please check the Verification Code!";
                        SessionVariables.iSeq = 2;
                    }
                }
            }
            // Send User an Email with UserID.
            else if (RadioRecovery.Equals("2"))
            {
                string RecoveryEmail = Request.Form["ctl00$MainContent$UserNameEmail"].ToString().Trim();
                if (RecoveryEmail.Length != 0)
                {
                    MySqlCommand cmd      = null;
                    String       UserInfo = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;
                    try
                    {
                        cmd             = new MySqlCommand("spValidateUserEmail", new MySqlConnection(UserInfo));
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("email", RecoveryEmail);

                        cmd.Connection.Open();
                        int userID = Convert.ToInt32(cmd.ExecuteScalar());
                        cmd.Connection.Close();
                        switch (userID)
                        {
                        case -1:
                            cmd             = new MySqlCommand("spGetUsername", new MySqlConnection(UserInfo));
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;

                            cmd.Parameters.AddWithValue("email", RecoveryEmail);
                            cmd.Connection.Open();
                            String username = Convert.ToString(cmd.ExecuteScalar());
                            cmd.Connection.Close();
                            if (!username.Equals("-2"))
                            {
                                SessionVariables.recoveryCode = Guid.NewGuid().ToString();
                                string subject = "KcGameOn Account: Forgotten username request";
                                string body    = "Behold,";
                                body += "<br /><br />This is an automated message generated by the KCGameOn database Gods to remind you of your username.";
                                body += "<br /><br />Your puny mortal username is:";
                                body += "<br /><br /><b>" + username + "</b>";
                                body += "<br /><br />Remember to bring a worthy offering to us.";
                                body += "<br /><br />Thanks,";
                                body += "<br />KcGameOn Team!";
                                MailClient Mailsender = new MailClient();
                                Mailsender.SendEmail(body, subject, RecoveryEmail);
                                SessionVariables.iSeq = 2;
                            }
                            else
                            {
                                // If this gets hit something is really jacked up, spValidateEmail and spGetUsername validate user email address independently.
                                // This only occurs if spValidateEmail successfully found the email address but spGetUsername could not find the email... should be impossible.
                                SessionVariables.iSeq = 1;
                                recoveryError.Text    = "Unable to validate an Email!";
                            }
                            break;

                        case -2:
                            // UserNot Found
                            SessionVariables.iSeq = 1;
                            recoveryError.Text    = "Unable to validate an Email!";
                            break;

                        default:
                            break;
                        }
                    }
                    catch
                    {
                        Response.Redirect("/ErrorPage/Error.aspx");
                    }
                    finally
                    {
                        if (cmd.Connection != null)
                        {
                            cmd.Connection.Close();
                        }
                    }
                }
                // Send User an Email with UserName.
            }
            else
            {
                Response.Redirect("/ErrorPage/error.aspx");
            }
        }
Ejemplo n.º 14
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            String UserName = Request.Form["ctl00$MainContent$UserName"];
            String Password = Request.Form["ctl00$MainContent$Password"];

            //Set Connection String to MySql.
            String UserInfo = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;

            if (UserName != null && Password != null)
            {
                //Hash Users Password.
                PasswordHash PasswordHasher = new PasswordHash();
                String       Salt           = PasswordHasher.CreateSalt(UserName.ToLower());
                String       HashedPassword = PasswordHasher.HashPassword(Salt, Password);
                MySqlCommand cmd            = null;
                int          Authentication = 0;

                try
                {
                    cmd             = new MySqlCommand("checkUser", new MySqlConnection(UserInfo));
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                    cmd.Parameters.AddWithValue("Username", UserName);
                    cmd.Parameters.AddWithValue("UserPass", HashedPassword);

                    cmd.Connection.Open();
                    //Reader = cmd.ExecuteReader();
                    Authentication = Convert.ToInt32(cmd.ExecuteScalar());

                    switch (Authentication)
                    {
                    case -1:
                        ErrorString = "Please Activate your account.";
                        break;

                    case -2:     // UserActivated, User Is Admin and UserAuthenticated.
                        SessionVariables.UserName  = UserName;
                        SessionVariables.UserAdmin = 1;
                        // Set Cookies if Remember was checked.
                        CookiesANDRememberMe();
                        break;

                    case -3:     // UserActivatd, UseAuthenticated and User isn't Admin.
                        SessionVariables.UserName  = UserName;
                        SessionVariables.UserAdmin = 0;
                        // Set Cookies if Remember was checked.
                        CookiesANDRememberMe();
                        break;

                    case -4:
                        ErrorString = "Your Input Sucks!";
                        break;

                    default:
                        break;
                    }
                }
                finally
                {
                    if (cmd != null)
                    {
                        cmd.Connection.Close();
                    }
                }

                try
                {
                    cmd = new MySqlCommand("SELECT BlockPayments FROM AdminProperties", new MySqlConnection(UserInfo));
                    cmd.Connection.Open();
                    cmd.CommandType = System.Data.CommandType.Text;
                    string blocked = cmd.ExecuteScalar().ToString();
                    if (blocked.Equals("TRUE"))
                    {
                        if (SessionVariables.UserAdmin == 0 && !SessionVariables.UserName.ToLower().Equals("kctestaccount"))
                        {
                            SessionVariables.registrationBlocked = true;
                        }
                        else
                        {
                            SessionVariables.registrationBlocked = false;
                        }
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (cmd.Connection != null)
                    {
                        cmd.Connection.Close();
                    }
                }

                if (SessionVariables.UserName != null)
                {
                    try
                    {
                        cmd             = new MySqlCommand("SELECT pay.idpaytable, pay.username, pay.EventID, sea.checkedin, pay.verifiedPaid, pay.paymentKey FROM payTable AS pay LEFT JOIN (SELECT username, checkedin FROM seatingchart WHERE username = \"" + SessionVariables.UserName + "\" AND ActiveIndicator = \"TRUE\") sea on pay.username = sea.username WHERE pay.username = \"" + SessionVariables.UserName + "\" AND pay.EventID = (SELECT EventID FROM kcgameon.schedule WHERE Active = 1 order by ID LIMIT 1) AND pay.verifiedPaid = \'Y\'", new MySqlConnection(UserInfo));
                        cmd.CommandType = System.Data.CommandType.Text;
                        cmd.Connection.Open();
                        IAsyncResult result = cmd.BeginExecuteReader();
                        reader = cmd.EndExecuteReader(result);
                        result = cmd.BeginExecuteReader();
                        if (reader == null || !reader.HasRows)
                        {
                            SessionVariables.verifiedPaid = "N";
                        }
                        else
                        {
                            while (reader.Read())
                            {
                                SessionVariables.paymentKey   = reader["paymentKey"].ToString();
                                SessionVariables.verifiedPaid = reader["verifiedPaid"].ToString();
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                        if (cmd != null)
                        {
                            cmd.Connection.Close();
                        }
                    }
                    if (String.IsNullOrEmpty(redirect))
                    {
                        Response.Redirect("/Default.aspx");
                    }
                    else if (redirect.Contains("/AccountManagement.aspx"))
                    {
                        Response.Redirect("/Default.aspx");
                    }
                    else
                    {
                        Response.Redirect(redirect);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        protected void SignButton_Click(object sender, EventArgs e)
        {
            //if(Recaptcha.IsValid)
            String FirstName       = Request.Form["ctl00$MainContent$inputFirst"].ToString().Trim();
            String LastName        = Request.Form["ctl00$MainContent$inputLast"].ToString().Trim();
            String Email           = Request.Form["ctl00$MainContent$inputEmail"].ToString().Trim();
            String ConfirmEmail    = Request.Form["ctl00$MainContent$inputEmail1"].ToString().Trim();
            String UserName        = Request.Form["ctl00$MainContent$inputUser"].ToString().Trim();
            String Sponsor         = Request.Form["ctl00$MainContent$inputCerner"].ToString().Trim();
            String Password        = Request.Form["ctl00$MainContent$Password"].ToString().Trim();
            String ConfirmPassword = Request.Form["ctl00$MainContent$Password1"].ToString().Trim();
            String SecretQuestion  = Request.Form["ctl00$MainContent$DropDownList1"].ToString().Trim();
            String SecretAnswer    = Request.Form["ctl00$MainContent$SecretAnswer"].ToString().Trim();
            Regex  regex           = new Regex(@"(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}");
            Match  match           = regex.Match(Password);

            //No spaces allowed :).
            Regex.Replace(UserName, @"\s+", "");

            int userID = 0;

            String UserInfo = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;

            //if (Validate())
            if (int.Parse(Request.Form["ctl00$MainContent$HumanValidation"].ToString().Trim()) == 8)
            {
                if (!String.IsNullOrEmpty(UserName) && !String.IsNullOrEmpty(Password) &&
                    !String.IsNullOrEmpty(Email) && !String.IsNullOrEmpty(SecretAnswer) &&
                    !String.IsNullOrEmpty(SecretAnswer) && match.Success && Password == ConfirmPassword && Email == ConfirmEmail)
                {
                    //Hash Users Password.
                    PasswordHash PasswordHasher     = new PasswordHash();
                    String       Salt               = PasswordHasher.CreateSalt(UserName.ToLower());
                    String       HashedPassword     = PasswordHasher.HashPassword(Salt, Password);
                    String       HashedSecretAnswer = PasswordHasher.HashPassword(Salt, SecretAnswer.ToLower());
                    MySqlCommand cmd = null;

                    try
                    {
                        cmd             = new MySqlCommand("spAddUsers", new MySqlConnection(UserInfo));
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("UserName", UserName);
                        cmd.Parameters.AddWithValue("Pass", HashedPassword);
                        cmd.Parameters.AddWithValue("First", FirstName);
                        cmd.Parameters.AddWithValue("Last", LastName);
                        cmd.Parameters.AddWithValue("Email", Email);
                        cmd.Parameters.AddWithValue("Cerner", Sponsor);
                        cmd.Parameters.AddWithValue("Admin", 0);
                        cmd.Parameters.AddWithValue("SecretQuestion", SecretQuestion);
                        cmd.Parameters.AddWithValue("SecretAnswer", HashedSecretAnswer);

                        cmd.Connection.Open();
                        userID = Convert.ToInt32(cmd.ExecuteScalar());

                        switch (userID)
                        {
                        case -1:
                            RegisterErrorString = "Username already exists.";
                            break;

                        case -2:
                            RegisterErrorString = "Email address has already been used.";
                            break;

                        default:
                            SendActivationEmail(userID, UserName);
                            RegistrationSucess = true;
                            //SessionVariables.UserName = UserName;
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        // Redirect to Error Page.
                    }
                    finally
                    {
                        cmd.Connection.Close();
                    }
                }
                else
                {
                    RegisterErrorString = "Don’t worry, we have server side Validations! \n Check missing fields, and Password must contain at least 6 characters, including UPPER/lowercase and numbers";
                }
            }
            else
            {
                RegisterErrorString = "We've indicated that you're not a Human.";
                //"Dont worry we do server side Validations!"
            }
        }