0

I'm trying to create login system with Permissions. I want to know how I check for the level of the user, If it's an Admin, Technician etc... I've made a simple login with a user.

This is my index.php (Form)

<html>
<head>
    <title>Log-In</title>
    <meta charset="UTF-8">
    <meta name="author" content="Augusto Mendes">
    <meta name="description" content="All">
    <link rel="stylesheet" href="styles.css">
</head>
<body id="Both">
    <form id="login" name="form" method="POST" action="/site/base/login_config.php">
        <div class="form">
            <label>Username</label>
            <input type="text" name="username">
        </div>

        <div class="form">
            <label>Password</label>
            <input type="password" name="password">
        </div>

        <div class="form">
            <input type="submit" value="Submit">
        </div>
    </form>
</body>

This is my login_config.php (Login verfication)

<?php
//Gets the Form's Variavels
$user = $_POST["username"];
$pass = $_POST["password"];

//Import "config.php"
include("config.php");

//Check the Data on the Database
$sql = "SELECT * FROM users WHERE User = '$user' AND Password = '$pass'";
$result = mysqli_query($connect, $sql);
$nreg = mysqli_num_rows($result);

if($nreg > 0){ //Check if any of the registries exist - If user exists

    $reg = mysqli_fetch_array($result);
    session_start();
    $_SESSION["User"] = $reg["User"];
    echo "Welcome ".$_SESSION['User'];

    //header('Location:../index.php');
    //I want this to redirect for User or Admin pages with their permissions
}

else{
    //header('Location:../wrong.html');
}
?>

This is my config.php (Connection and database)

<?php
// Server COSNTs (Server, User, PW, DB)
define('SERVER', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'loja');

$connect = mysqli_connect(SERVER, USERNAME, PASSWORD);

// Connection to the MySQL Server
if (!$connect){
    echo " Error: Connection to the Server FAILED! ";
    echo "<script type='text/javascript'>alert(' Error: Connection to the Server FAILED! ')</script>";
    exit;
}

$choose = mysqli_select_db($connect, DATABASE);

// Connection to the Database
if (!$choose){
    echo " Error: Connection to the Database FAILED! ";
    echo "<script type='text/javascript'>alert(' Connection to the Database FAILED! ')</script>";
    exit;       
}
?>

Image of the database

0: Windows Technician 1: Apple Technician 2: Store Manager 3: Admin 4: N/D right now

Since i've 2 folders one for users (0, 1, 2) and admin (3) i wanted to make only permissions per users. Admin has access to Users' Data but not their folders and Users can't go to Admins.

Thanks for reading. -Ryan

  • Try creating a switch, which will check the role, and send the user to the appropriate pages in your login_config.php. After that, make a check on every page what which role should see. – Rick J Apr 25 '18 at 14:30
  • 2
    Don't use an enum in the user table to determine the role, have a role table instead and link users to roles. Use the role to determine the available actions. You're also wide open to SQL injection attacks and you appear to be storing passwords in plain text... – CD001 Apr 25 '18 at 14:30
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Apr 25 '18 at 14:37
  • **Never** store plain text passwords. Instead use [`password_hash()`](http://us3.php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://us3.php.net/manual/en/function.password-verify.php). If you're using a version of PHP prior to 5.5, do **not** use MD5 or SHA1 to hash passwords. Instead you can use [this compatibility pack](https://github.com/ircmaxell/password_compat). – Alex Howansky Apr 25 '18 at 14:37
  • Thanks Rick i will try it, when i crate a Session should it be per role or name? since i seam can't have both; About the SQL Injection and blank password, I know about it, I simply made a register in myphpadmin, I haven't created an Create User form, since i want the permissions to be work so i can have an admin create the form, I appreciate the worry over it. – FlyingArowana Apr 25 '18 at 14:40

1 Answers1

0

NOTE: For the sake of knowledge I'll answer the question, but keep in mind that this code is open to severe security attacks, like SQL injection, Cross-Site Request Forgery...

I would totally advise against using any of this in a production environment

Security is a tough topic, I would suggest using some library or framework for the login and make sure it's correctly configured and (reasonably) secured

Answer: You basically have to check the value in the row for the key 'Role', and decide where to send them. You can also store the whole user information in the session instead of just the user name, so you'll be able to check the permissions on every page

const ADMIN_ROLE = 4;

if($nreg > 0){ //Check if any of the registries exist - If user exists

    $reg = mysqli_fetch_array($result);
    session_start();

    // Store the whole user information
    $_SESSION['LoggedUser'] = $reg;

    // Note: as you redirect after with the header location the user won't really see this message 
    echo "Welcome ".$_SESSION['LoggedUser']['User'];

    // Set a default page for normal users
    $page = '../index.php';

    // Check against the admin role and overwrite
    if ($_SESSION['LoggedUser']['Role'] == ADMIN_ROLE) {
        $page = '../admin/index.php';
    }

    header("Location: $page");
}

Answer to comment You can create a class with the constants

class Role
{
    const WINDOWS = 0;
    const APPLE   = 1;
    const MANAGER = 2;
    const ADMIN   = 3;
}

Now you can use this file whenever you need

// It's better to use some autoloading, look at "composer"
include "./Role.php";

session_start();
//... do checks

if (!$_SESSION['LoggedUser']['Role'] != Role::ADMIN) {
    // redirect
}

I'm not very fond of public constants, I consider a better practice to encapsulate this logic inside the class, so the constants can be hidden from the outside. I'm not going to extend it but you'll end up with something like

if (!$user->getRole()->isAdmin()) {
    // redirect
}
hmoragrega
  • 212
  • 2
  • 9
  • Since your help it's working, Wanted just to ask another question to clarify, in every page to check if the Admin or User and direct 'em to their specific page, I need to put their consts in every page? [link]https://imgur.com/a/nxalVyk – FlyingArowana Apr 29 '18 at 13:09
  • I've added a response to the comment – hmoragrega May 02 '18 at 10:39
  • I've just edit and adapted the code that way, Since I've never used OOP on PHP didn't knew i could make a Class for the Role and call it on every page when need it, I made a Class.php and call it everytime needed on the Pages (User and Admin) and the Login_config.php, Could this "$_SESSION['LoggedUser']['Role']" be a Class or Function instead of using the the pure-string line, would it look something like yours "if (!$user->getRole()->isAdmin()) {" if not user check for role? check if its admin?" Sorry if my programming isn't the best. – FlyingArowana May 03 '18 at 23:04
  • Same question of "$_SESSION['LoggedUser']['Role']" could it a apply for $page? make the variavel page always "/site/index.php" so i dont need to define it at the start, would those 2 be an const? Correct me if wrong, When i was learning programming, "If you have repeating code, make a function and call it" thats why "$_SESSION['LoggedUser']['Role']" should be in a function somehow, that would me need to figure it out, but i just want a more expericed-advised, from the help you've been giving me I've been understanding everything jsut not the last one "!$user->getRole()->isAdmin()" – FlyingArowana May 03 '18 at 23:06