I’m having trouble validating access in a system

Asked

Viewed 19 times

0

Warning: mysqli_query() expects Parameter 1 to be mysqli, string Given in Sqlfunctions.php on line 13

Login.php:

<?php

if(isset($_POST['usuario']) && isset($_POST['senha'])) {

  require_once("class/Autenticacao.php");

  $Autenticacao = new Autenticacao();
  $login        = $_POST['usuario'];
  $password     = $_POST['senha'];

  $Autenticacao->setLogin($login);
  $Autenticacao->setPassword($password);
  $Autenticacao->autenticate();

}
 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<title>Área Administrativa</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <link href="css/bootstrap.css" rel="stylesheet">
    <style type="text/css">
      body {
        padding-top: 40px;
        padding-bottom: 40px;
        background-color: #f5f5f5;
      }

      .form-signin {
        max-width: 300px;
        padding: 19px 29px 29px;
        margin: 0 auto 20px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        -webkit-border-radius: 5px;
           -moz-border-radius: 5px;
                border-radius: 5px;
        -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
           -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
                box-shadow: 0 1px 2px rgba(0,0,0,.05);
      }
      .form-signin .form-signin-heading,
      .form-signin .checkbox {
        margin-bottom: 10px;
      }
      .form-signin input[type="text"],
      .form-signin input[type="password"] {
        font-size: 16px;
        height: auto;
        margin-bottom: 15px;
        padding: 7px 9px;
      }

    </style>
    <link href="css/bootstrap-responsive.css" rel="stylesheet">

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="../assets/js/html5shiv.js"></script>
    <![endif]-->

    <!-- Fav and touch icons -->
    
</head>

    <body>

    <div class="container">

      <form class="form-signin" name="frmLogin" id="frmLogin" method="post" action="">
        <h2 class="form-signin-heading">Por favor insira</h2>
        <input type="text" name="usuario" id="usuario" class="input-block-level" placeholder="Usuario">
        <input type="password" name="senha" id="senha" class="input-block-level" placeholder="Senha">
        <!-- <label class="checkbox">
          <input type="checkbox" value="remember-me"> Remember me
        </label> -->
        <button class="btn btn-large btn-success" type="submit" name="enviar" id="enviar" value="Login">Entrar</button>
        </br>
        Seja bem vindo ao *****. Entre com suas credenciais para ter acesso ao sistema.
      </form>

    </div> <!-- /container -->

    
    </body>
</html>

Php authentication.

<?php

require_once("SQLFunctions.php");

class Autenticacao {

    private $login;
    private $password;
    private $autenticado;

    public function __construct() 

    {
        
        if(!isset($_SESSION)) 
        session_start();

    }

    public function autenticate() {

        $SQLFunctions = new SQLFunctions();

        $sql = "SELECT * FROM usuarios WHERE login_usuario = '". $this->getLogin() ."' AND senha_usuario = '". $this->getPassword() ."'";
        $SQLFunctions->setSql($sql);
        $usuario = $SQLFunctions->listAll(true);

        // Se usuário for cadastrado na base de dados       
        if(!empty($usuario)) {
            
            $_SESSION['autenticacao'] = $usuario;

            header("Location: index.php");
        
        } else {

            header("Location: login.php");

        }

    }

    public static function hasAutenticate() {

        if(isset ($_SESSION) && isset($_SESSION['autenticacao']) && !empty($_SESSION['autenticacao'])) {

            return true;

        } else {

            return false;

        }

    }

    public function logoff() {
        unset($_SESSION['autenticacao']);
        session_unset();
        session_destroy();
    }

    public function verifyPermissions($idUsuario=null, $aliasModulo=null, $aliasAcao=null) {

        $sql = "SELECT * 
                FROM 
                    permissoes 
                LEFT JOIN usuarios ON usuarios.id_usuario = permissoes.id_permissao_usuario
                LEFT JOIN acoes ON acoes.id_acao = permissoes.id_permissao_acao
                LEFT JOIN modulos ON modulos.id_modulo = acoes.id_acao_modulo
                WHERE 1=1
                ". (!is_null($idUsuario) ? " AND usuarios.id_usuario = ". $idUsuario ."" : "") ."
                ". (!is_null($aliasModulo) ? " AND modulos.alias_modulo = '". $aliasModulo ."'" : "") ."
                ". (!is_null($aliasAcao) ? " AND acoes.alias_acao = '". $aliasAcao ."'" : "") ."
                ORDER BY id_permissao ASC";

                $SQLFunctions = new SQLFunctions();
                $SQLFunctions->setSql($sql);
                $permissoes = $SQLFunctions->listAll();

            // se todos argumentos vierem nulos, retornarar uma listagem de permissão
        if(is_null($aliasModulo) && is_null($aliasAcao) && is_null($idUsuario)) {

            return $permissoes;

            //retorna TRUE se usuário tiver permissão e FALSE caso usuário nao tenha permissão
        } else {

            // Usuário não tera permissoes
            if(is_null($permissoes) || empty($permissoes)) {

                return false;
                
            //Aqui usuário tem permissao de acessar
            } else {

                return true;

            }

        }

    }

    public function setLogin($valor)            { $this->login = $valor; }
    public function setPassword($valor)         { $this->password = md5($valor); }
        
    public function getLogin()                  { return $this->login; }
    public function getPassword()               { return $this->password; }
    
}

//$teste = new Autenticacao();
//$teste->setLogin("diego.valentim");
//$teste->setPassword("123456");
//$teste->autenticate();
?>

Sqlfunctions.php:

<?php

require_once("MysqlConnect.php");


class SQLFunctions extends MysqlConnect {

    private $sql;
    
    public function listAll($oneRow=false) {

        $sql        = $this->getSql();
        $qry        = mysqli_query($sql,"") or die ("Erro ao executar consulta: " . mysqli_connect_error());
        $resultado  = array();
        
        //$qry        = mysqli_query ( mysqli $qry , string $qry [, int $resultado = MYSQLI_STORE_RESULT ] ) : mixed or die ("Erro ao executar consulta: " . mysqli_connect_error());

        //Se usuário quiser que retorne somente um registro ao invés de uma lista
        if($oneRow) {

            $row = mysqli_fetch_assoc($qry);
            $resultado = $row;

        } else {

            while($rows = mysqli_fetch_assoc($qry)) {

                $resultado[] = $rows;

            }

        }

        return $resultado;

    }

    /** Metodos GETTER'S e SETTER'S (Encapsulamento) */
    public function setSql($valor)      { $this->sql = $valor; }
    public function getSql()            {return $this->sql; }

}

//$teste = new SQLFunctions();
//$teste->setSql("SELECT * FROM usuarios ORDER BY nome_usuario ASC");
//$rows = $teste->listAll(true);

//echo "<pre>"; print_r($rows); die();
?>

MysqlConnect.php:

<?php
    
    abstract class MysqlConnect {

    private $host;
    private $user;
    private $password;
    private $database;
    private $erro;
    private $connection;

    public function __construct() {

        $this->setHost("127.0.0.1:3306");
        $this->setUser("root");
        $this->setPassword("123456");
        $this->setDatabase("eventos_rurais");

        if(!$this->connect()) {

            die("Erro ao conectar a Base de Dados:" . $this->getErro());
        }

    }

    public function __destruct() {

        $this->disconnect();

    }

    public function connect() {
        try {
        
            $con = mysqli_connect($this->getHost(), $this->getUser(), $this->getPassword());
            $bd  = mysqli_select_db($con, $this->getDatabase());

            $this->setConnection($con);
            
            return true;

        } catch (Exception $e) {

            $this->setErro($e->getMessage());

            return false;
        }
    }

    public function disconnect(){

        mysqli_close($this->getConnection());

    }

    /** Metodos GETTER'S e SETTER'S (Encapsulamento) */
    private function setHost($valor)        { $this->host = $valor; }
    private function setUser($valor)        { $this->user = $valor; }
    private function setPassword($valor)    { $this->password = $valor; }
    private function setDatabase($valor)    { $this->database = $valor; }
    private function setErro($valor)        { $this->erro = $valor; }
    private function setConnection($valor)  { $this->connection = $valor; }

    private function getHost()              {return $this->host; }
    private function getUser()              {return $this->user; }
    private function getPassword()          {return $this->password; }
    private function getDatabase()          {return $this->database; }
    private function getErro()              {return $this->erro; }
    private function getConnection()        {return $this->connection; }

}

//echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
//echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
//mysqli_close($link);
?>
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.