Different sessions for each level of access. Is it possible?

Asked

Viewed 39 times

1

I am creating a CRUD for the service, where I will have 3 levels of access.

Levels:

  1. Administrator (Register and delete and edit information)
  2. Collaborator (Registration only information)
  3. User (Only reads information)

I added a script where when logging in, the system redirects according to the level.

Part of the code that redirects:

// O usuário está logado
        $_SESSION['logado']       = true;
        $_SESSION['nome_usuario'] = $fetch_usuario['user_name'];
        $_SESSION['usuario']      = $fetch_usuario['user'];
        $_SESSION['user_id']      = $fetch_usuario['user_id'];
        $_SESSION['nivel']      = $fetch_usuario['nivel'];
          if($_SESSION['nivel'] == "1"){
                header("Location: administrador.php");
            }elseif($_SESSION['nivel'] == "2"){
                header("Location: colaborador.php");
                }elseif($_SESSION['nivel'] == "3"){
                header("Location: usuario.php");
            }

Below follows the complete code:

 VERIFICA_LOGIN.php
    
    <?php
    // Verifica se estamos conectados ao BD
    if ( ! isset( $conexao_pdo ) || ! is_object( $conexao_pdo ) ) {
        exit('Erro na conexão com o banco de dados.');
    }
    
    // Une $_SESSION e $POST para verificação
    if ( isset( $_POST ) && ! empty( $_POST ) ) {
        $dados_usuario = $_POST;
    } else {
        $dados_usuario = $_SESSION;
    }
    
    // Verifica se os campos de usuário e senha existem
    // E se não estão em branco
    if ( 
        isset ( $dados_usuario['usuario'] ) && 
        isset ( $dados_usuario['senha'] )   &&
      ! empty ( $dados_usuario['usuario'] ) &&
      ! empty ( $dados_usuario['senha'] ) 
    ) {
        // Faz a consulta do nome de usuário na base de dados
        $pdo_checa_user = $conexao_pdo->prepare('SELECT * FROM usuarios WHERE user = ? LIMIT 1');
        $verifica_pdo = $pdo_checa_user->execute( array( $dados_usuario['usuario'] ) );
        
        // Verifica se a consulta foi realizada com sucesso
        if ( ! $verifica_pdo ) {
            $erro = $pdo_checa_user->errorInfo();
            exit( $erro[2] );
        }
          // Busca os dados da linha encontrada
        $fetch_usuario = $pdo_checa_user->fetch();
       // Verifica se a senha do usuário está correta
        if ( crypt( $dados_usuario['senha'], $fetch_usuario['user_password'] ) === $fetch_usuario['user_password'] ) {
            // O usuário está logado
            $_SESSION['logado']       = true;
            $_SESSION['nome_usuario'] = $fetch_usuario['user_name'];
            $_SESSION['usuario']      = $fetch_usuario['user'];
            $_SESSION['user_id']      = $fetch_usuario['user_id'];
            $_SESSION['nivel']      = $fetch_usuario['nivel'];
              if($_SESSION['nivel'] == "1"){
                    header("Location: administrador.php");
                }elseif($_SESSION['nivel'] == "2"){
                    header("Location: colaborador.php");
                    }elseif($_SESSION['nivel'] == "3"){
                    header("Location: usuario.php");
                }     
    
        } else {
            // Continua deslogado
            $_SESSION['logado']     = false;
            // Preenche o erro para o usuário
            $_SESSION['login_erro'] = 'Usuário ou senha inválidos';
        }
    }
    ?>

The problem is that when I soon eat, for example, as level 3 (usuario.php), if I delete the usuario.php after the bar and place administrador.php or colaborador.php, the system accepted.

There would be a way to bar this where the user would only have access on the respective page at his level of access?

  • 1

    If the access information is in the session, can’t you put a validation in each file? For example, in the file administrador.php put something like if ($_SESSION['nivel'] != 1) die("Você não deveria estar aqui")

  • As Woss said, you’d better check each file case by case and validate from there, you might even pass everything you need in the session, but you’d need to treat case by case the same way at the end, and from personal experience, the leaner you leave this level system, but safe and easy to maintain will be in the future.

  • Woss, I put as you guided me in the header of the respective pages, according to the level. It worked. Now each user can only view the pages according to their level of access. Thank you very much for the guidance.

No answers

Browser other questions tagged

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