Login system with permission

Asked

Viewed 491 times

1

I have a login system that, if the user is an administrator, will be redirected to one page and if common, to another.

The table:

For this, I have a column in the table that stores active call users, where 0 is common user and 1 is administrator.

The login:

    <!--A parte do formulário-->
    <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="login-panel panel panel-default">
                    <div class="panel-heading" style="
    margin-top: 14px;">
                        <h3 class="panel-title">Login</h3>
                    </div>
                    <div class="panel-body" style="background: rgba(32, 40, 76, 0.59);">
                        <?php 
                        if(isset($erro)) 
                            if(count($erro) > 0){ ?>
                                <div class="alert alert-danger">
                                    <?php foreach($erro as $msg) echo "$msg <br>"; ?>
                                </div>
                            <?php 
                            }
                            ?>
                        <form method="post" action="" role="form">
                            <fieldset style="background: #9498a9;">
                                <div class="form-group">
                                    <input  class="form-control" placeholder="Identifiant" name="identifiant">
                                </div>
                                <div class="form-group">
                                    <input class="form-control" required placeholder="Senha" name="senha" type="password" value="">
                                </div>
                                <div class="checkbox">
                                    <label>
                                        <input name="remember" type="checkbox" value="Remember Me">Lembrar-me
                                    </label>
                                </div>

                                <button type="submit" name="login" value="true" class="btn btn-success btn-block" style="background: #232b4f; border-color: #e2e2e2;">Login</button>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>


<!--A lógica-->
    <?php
        session_start();

        //Login de Usários
    if($_POST){

    include('class/conexao.php');

    $erro = array();

    // Captação de dados
    $senha = mysqli->escape_string($_POST[senha]);
    $_SESSION['identifiant'] = $mysqli->escape_string($_POST['identifiant']);

    // Validação de dados
    if(strlen($identifiant) < 7 || strlen($identifiant) > 7){
        $erro[] = "Preencha sua <strong>identifiant</strong> corretamente.";
    }else if(strlen($senha) < 5 || strlen($senha) > 16){
        $erro[] = "Preencha sua <strong>senha</strong> corretamente.";
    }else{
    //Até aqui, se não tiver nenhum erro nessa lista de erros aí, prossegue.

        $sql = "SELECT senha as senha, identifiant as valor
        FROM usuarios
        WHERE identifiant = '$_SESSION[identifiant]'";
        $que = $mysqli->query($sql) or die($mysqli->error);
        $dado = $que->fetch_assoc();

        if($que->num_rows == 0){
            $erro[] = "Usuário ou senha inválidos.";

        }else{

            if($_SESSION['identifiant'] == 0){
                echo "<script>location.href='http://127.0.0.1/formacao/principal.php';</script>";
                exit();
            }
            if($_SESSION['identifiant'] == 1){
                echo "<script>location.href='http://127.0.0.1/formacao/principalUSU.php';</script>";
                    exit();
            }
        }
    }
    }
?>

The validation page:

<?php
if (!empty($_POST) AND (empty($_POST['id']) OR empty($_POST['senha']) AND (`ativo` = 1)) {
  header("Location: principal.php");
   exit;
} else {
    if (!empty($_POST) AND (empty($_POST['id']) OR empty($_POST['senha']) AND (`ativo` = 0){
        header("Location: principalUSU.php");
         exit;
}

// Tenta se conectar ao servidor MySQL
mysql_connect('localhost', 'root', '', 'db_formacao') or trigger_error(mysql_error());
// Tenta se conectar a um banco de dados MySQL
$identifiant = mysql_real_escape_string($_POST['identifiant']);
$senha = mysql_real_escape_string($_POST['senha']);
$ativo = mysql_real_escape_string($_POST['ativo']);

$sql = "SELECT `id`, `identifiant`, `senha`, `ativo`  FROM `usuarios` WHERE (`identifiant` = '". $identifiant ."') AND (`senha` = '". $senha ."') AND (`ativo` = '". $ativo ."')";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 1) {
  // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
  echo "Login inválido!"; exit;
} else {
  // Salva os dados encontados na variável $resultado
  $resultado = mysql_fetch_assoc($query);
}
?>

This page is not yet being redirected to validation because the action is empty and the action is empty because the validation page does not work.

Every user registered in the table can enter if their identifiant and password are right, but the permission part, which redirects the admin to one page and the user to another, no.

I don’t quite know how I can do that, so I accept help.

2 answers

3

I did not understand very well where the code reference enters in the validation page. I believe it is within connection. If it is, you don’t need to use the validation on this page, just the connection. Try the following:

   <?php
  session_start();

        //Login de Usários
if($_POST){

  include('class/conexao.php');

  $erro = array();

  // Captação de dados
  $senha = mysqli->escape_string($_POST[senha]);
  $_SESSION['identifiant'] = $mysqli->escape_string($_POST['identifiant']);

  // Validação de dados
  if(strlen($identifiant) < 7 || strlen($identifiant) > 7){
      $erro[] = "Preencha sua <strong>identifiant</strong> corretamente.";
}else if(strlen($senha) < 5 || strlen($senha) > 16){
      $erro[] = "Preencha sua <strong>senha</strong> corretamente.";
}else{
  //Até aqui, se não tiver nenhum erro nessa lista de erros aí, prossegue.

      $sql = "SELECT senha as senha, identifiant as valor
      FROM usuarios
      WHERE identifiant = '$_SESSION[identifiant]'";
      $que = $mysqli->query($sql) or die($mysqli->error);
      $dado = $que->fetch_assoc();

      if($que->num_rows == 0){
          $erro[] = "Usuário ou senha inválidos.";

      }else{

                  if($_SESSION['identifiant'] == 0){
                                  echo "<script>location.href='http://127.0.0.1/formacao/principal.php';</script>";
                                  exit();
                  }
                  if($_SESSION['identifiant'] == 1){
                                  echo "<script>location.href='http://127.0.0.1/formacao/principalUSU.php';</script>";
                                  exit();
                  }



  }

}
}
    ?>


     <div class="container">
            <div class="row">
                <div class="col-md-4 col-md-offset-4">
                    <div class="login-panel panel panel-default">
                        <div class="panel-heading" style="
        margin-top: 14px;">
                            <h3 class="panel-title">Login</h3>
                        </div>
                        <div class="panel-body" style="background: rgba(32, 40, 76, 0.59);">
                            <?php 
                            if(isset($erro)) 
                                if(count($erro) > 0){ ?>
                                    <div class="alert alert-danger">
                                        <?php foreach($erro as $msg) echo "$msg <br>"; ?>
                                    </div>
                                <?php 
                                }
                                ?>
                            <form method="post" action="" role="form">
                                <fieldset style="background: #9498a9;">
                                    <div class="form-group">
                                        <input  class="form-control" placeholder="Identifiant" name="identifiant">
                                    </div>
                                    <div class="form-group">
                                        <input class="form-control" required placeholder="Senha" name="senha" type="password" value="">
                                    </div>
                                    <div class="checkbox">
                                        <label>
                                            <input name="remember" type="checkbox" value="Remember Me">Lembrar-me
                                        </label>
                                    </div>

                                    <button type="submit" name="login" value="true" class="btn btn-success btn-block" style="background: #232b4f; border-color: #e2e2e2;">Login</button>
                                </fieldset>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
  • So, I copied your code only that where is ID I put identifiant and where is identifiant I put active because the name of the column that is stored the 0 or 1 is this.

  • I changed all mysql to mysqli as recommended, by the way thanks for that. But the validation page still doesn’t work, gives that error 500. :/

  • I changed the code... see if you can now.

  • Hi Mariana. I made a new adjustment. See if you can now.

  • So I tried to use your code, but the page stopped working. I’ll see if it’s not some error of mine identation or something.

  • I’ll edit my question so you can see how it turned out

Show 1 more comment

0


So was the validation page:

<?php
//Esse login ficou meio complicadinho, então vou deixar comentado: 
ini_set('display_errors', true);
error_reporting(E_ALL);
// Primeiro verifica se o post não está vazio
if (!empty($_POST) AND !empty($_POST['identifiant']) OR !empty($_POST['senha'])) {
    $link = mysql_connect('localhost', 'root', '');
    mysql_select_db('db_formacao');
    // Tenta se conectar a um banco de dados MySQL
    $identifiant = mysql_real_escape_string($_POST['identifiant']);
    $senha = mysql_real_escape_string($_POST['senha']);
    $ativo = mysql_real_escape_string($_POST['ativo']);

    $sql = "SELECT `id`, `identifiant`, `senha`, `ativo`  FROM `usuarios` WHERE (`identifiant` = '". $identifiant ."') AND (`senha` = '". $senha ."')";
    $query = mysql_query($sql);
    if (mysql_num_rows($query) != 1) {
      // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
      echo "Login inválido!"; exit;
    } else {
      $resultado = mysql_fetch_assoc($query);
      // Verifica se o usuário é 0 ou 1

      if ($resultado['ativo'] == 0) { header("Location: principalUSU.php"); } 
      else { header("Location: principal.php"); }

      exit;
    }
}
?>

The login form:

<div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4" style="
    align-content: center;
    margin-left: 160px;">
                <div class="login-panel panel panel-default">
                    <div class="panel-heading" style="
    margin-top: 14px;">
                        <h3 class="panel-title">Login</h3>
                    </div>
                    <div class="panel-body" style="background: rgba(32, 40, 76, 0.59);">
                        <?php 
                        if(isset($erro)) 
                            if(count($erro) > 0){ ?>
                                <div class="alert alert-danger">
                                    <?php foreach($erro as $msg) echo "$msg <br>"; ?>
                                </div>
                            <?php 
                            }
                            ?>
                        <form method="post" action="validacao.php" role="form">
                            <fieldset style="background: #9498a9;">
                                <div class="form-group">
                                    <input  class="form-control" placeholder="Identifiant" name="identifiant">
                                </div>
                                <div class="form-group">
                                    <input class="form-control" required placeholder="Senha" name="senha" type="password" value="">
                                </div>
                                <div class="checkbox">
                                    <label>
                                        <input name="remember" type="checkbox" value="Remember Me">Lembrar-me
                                    </label>
                                </div>

                                <button type="submit" name="login" value="true" class="btn btn-success btn-block" style="background: #232b4f; border-color: #e2e2e2;">Login</button>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>

Browser other questions tagged

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