← 返回列表

A Better Login System: PHP编程实现基于ACL认证过程

聚合站 SecWiki技术 发布 2009-03-26T16:41:17Z 入库 2026-11-20T02:30:53
  1. Home
  2. Code
  3. PHP

A Better Login System

Andrew Steenbuck

Andrew Steenbuck

Net.tuts+ has published several great tutorials on user login systems. Most tutorials only deal with authenticating the user, which allows for two levels of security: logged in and not logged in. For many sites, a finer degree of control is needed to control where users can go and what they can do. Creating an access control list (ACL) system will give you the flexibility for granular permissions.

Introduction

Final Product

Final Product

Final Product

Imagine you are running a great tutorial site that lets users learn about a wide variety of web development techniques. In addition to your normal readers, you have some premium subscription members, as well contributing authors and administrators.

Your problem

You want to restrict users' to only specific pages that their particular account allows access to.

[Privacy Policy.]

The solution

Implementing an access control list will allow you a great deal of control over what users can and cannot access on your site.

If you view the demo, available with the downloadable source code, you will be greeted with an index page that tests the ACL for each user. You can select different links at the bottom to view the ACL for the different users. If you click on the 'Admin Screen' link near the top, you can view a sample of the admin interface that allows you to manage the users, roles, and permissions. NOTE: The admin system will perform a database restore every 30 minutes to make sure everything stays on the up and up. The download files also implement the ACL security on the admin site, so if user number one doesn't have the 'access admin' permission, you won't be able to access the admin site.

This system will enable you to create different groups of users (i.e. guests, premium members, contributors, and admins). We will be able to set unique permissions for each group, as well as for individual users. Let's get started by setting up our MySQL database.

AI Cross Promo Banner

Step 1: Create the Database

Our ACL will be stored in a relational database using six tables (including the table for users). You should already have a database set up in your host environment. We will create the following table structure:

Database tables

Database tables

Database tables

The code to create the database is available in the source files (install.sql), and there is also another file (sampleData.sql) that will create 4 sample users, along with several roles and permissions for you to test with. Simply open the files with you favorite text editor, and copy/paste the code into the SQL panel in phpMyAdmin.

Step 2: Database Include

We need to create an include file so that we may connect to our database. Create a file called assets/php/database.php and add the following code to it (replace the variable values with the information appropriate for your hosting situation):

| 1 | |
| 2 | <?php |
| 3 | session_start(); |
| 4 | ob_start(); |
| 5 | $hasDB = false; |
| 6 | $server = 'localhost'; |
| 7 | $user = 'root'; |
| 8 | $pass = 'mysql'; |
| 9 | $db = 'acl_test'; |
| 10 | $link = mysql_connect($server,$user,$pass); |
| 11 | if (!is_resource($link)) { |
| 12 | $hasDB = false; |
| 13 | die("Could not connect to the MySQL server at localhost."); |
| 14 | } else { |
| 15 | $hasDB = true; |
| 16 | mysql_select_db($db); |
| 17 | } |
| 18 | ?> |

On the first line of the code, we call session_start(); we will not actually use the session variables but you will need it as part of the user login system. Then, we call ob_start() to create an output buffer. Typically, when PHP generates the page, it is sent to the browser as it is generating. By using ob_start(), the page and headers aren't sent to the browser until they've loaded completely, or until we call ob_end_flush(). By buffering the page, we are able to redirect using PHP at any point on the page, instead of just at the top. After the headers are sent, our only redirect option is with JavaScript. An enterprising hacker could easily turn JavaScript off, and then see our unsecured page in all it's glory. This one line allows us to deny the user access at any point in the page if needed.

Lines 4-8 set up our variables. $hasDB is a boolean used to determine if we are connected. $server, $user, $pass, and $db are the connection arguments for the server. Line 9 connects to the server, while line 10 determines if the connection was successful. If it was, we select the database to use; if it wasn't, we display an error message using die().

Step 3: Create the ACL Class

This step is fairly long, as we are creating the ACL class that will form the basis of our system. I apologize in advance for the length of this step.

ACL

ACL

ACL

Our ACL system will be object-oriented, so let's start creating the class file. We start by adding the class definition, variable definitions, and the constructor to the file /assets/php/class.acl.php:

| 1 | |
| 2 | <?php |
| 3 | class ACL |
| 4 | { |
| 5 | var $perms = array(); //Array : Stores the permissions for the user |
| 6 | var $userID = 0; //Integer : Stores the ID of the current user |
| 7 | var $userRoles = array(); //Array : Stores the roles of the current user |
| 8 | |
| 9 | function __constructor($userID = '') |
| 10 | { |
| 11 | if ($userID != '') |
| 12 | { |
| 13 | $this->userID = floatval($userID); |
| 14 | } else { |
| 15 | $this->userID = floatval($_SESSION['userID']); |
| 16 | } |
| 17 | $this->userRoles = $this->getUserRoles('ids'); |
| 18 | $this->buildACL(); |
| 19 | } |
| 20 | function ACL($userID='') |
| 21 | { |
| 22 | $this->__constructor($userID); |
| 23 | } |

Analysis

After creating the class definition, we create the three class variables to store the information that will be used in the generation of the ACL.

The Constructor Method

The __constructor() function is used to initialize the object when we want to load an ACL. It is called automatically when we call new ACL();. It is then passed a single, optional argument of the user to load the ACL for. Inside the constructor, we check to see if a user ID was passed in. If no ID was passed, we assume that we will load the ACL for the currently logged in user; so we read in the session variable for that. Alternatively, if we pass in a user ID, it allows us to read and edit the ACL for a user other than the one logged in (useful for your admin page).

After we read in the user ID, we call getUserRoles() to generate an array of the roles the user is assigned to and store it in the $userRoles class variable. At the end of the constructor, we call buildACL() to generate the actual ACL. The method named ACL() is a crutch for PHP4 installs. When you call new ACL() in PHP5, the PHP interpreter runs the __constructor() method. However, when you run the same code in PHP4, the interpreter runs ACL(). By providing a method named the same as the class, we make the class PHP4 compatible.

Any time we create a new ACL object by passing in a user ID, that object will hold the permissions for the user who was passed in.

Helper Methods

Now, lets add some more helper methods to the same class file. These methods will provide support to the other methods by performing specialized tasks:

| 1 | |
| 2 | function getUserRoles() |
| 3 | { |
| 4 | $strSQL = "SELECT * FROM `user_roles` WHERE `userID` = " . floatval($this->userID) . " ORDER BY `addDate` ASC"; |
| 5 | $data = mysql_query($strSQL); |
| 6 | $resp = array(); |
| 7 | while($row = mysql_fetch_array($data)) |
| 8 | { |
| 9 | $resp[] = $row['roleID']; |
| 10 | } |
| 11 | return $resp; |
| 12 | } |
| 13 | function getAllRoles($format='ids') |
| 14 | { |
| 15 | $format = strtolower($format); |
| 16 | $strSQL = "SELECT * FROM `roles` ORDER BY `roleName` ASC"; |
| 17 | $data = mysql_query($strSQL); |
| 18 | $resp = array(); |
| 19 | while($row = mysql_fetch_array($data)) |
| 20 | { |
| 21 | if ($format == 'full') |
| 22 | { |
| 23 | $resp[] = array("ID" => $row['ID'],"Name" => $row['roleName']); |
| 24 | } else { |
| 25 | $resp[] = $row['ID']; |
| 26 | } |
| 27 | } |
| 28 | return $resp; |
| 29 | } |
| 30 | function buildACL() |
| 31 | { |
| 32 | //first, get the rules for the user's role |
| 33 | if (count($this->userRoles) > 0) |
| 34 | { |
| 35 | $this->perms = array_merge($this->perms,$this->getRolePerms($this->userRoles)); |
| 36 | } |
| 37 | //then, get the individual user permissions |
| 38 | $this->perms = array_merge($this->perms,$this->getUserPerms($this->userID)); |
| 39 | } |
| 40 | function getPermKeyFromID($permID) |
| 41 | { |
| 42 | $strSQL = "SELECT `permKey` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1"; |
| 43 | $data = mysql_query($strSQL); |
| 44 | $row = mysql_fetch_array($data); |
| 45 | return $row[0]; |
| 46 | } |
| 47 | function getPermNameFromID($permID) |
| 48 | { |
| 49 | $strSQL = "SELECT `permName` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1"; |
| 50 | $data = mysql_query($strSQL); |
| 51 | $row = mysql_fetch_array($data); |
| 52 | return $row[0]; |
| 53 | } |
| 54 | function getRoleNameFromID($roleID) |
| 55 | { |
| 56 | $strSQL = "SELECT `roleName` FROM `roles` WHERE `ID` = " . floatval($roleID) . " LIMIT 1"; |
| 57 | $data = mysql_query($strSQL); |
| 58 | $row = mysql_fetch_array($data); |
| 59 | return $row[0]; |
| 60 | } |
| 61 | function getUsername($userID) |
| 62 | { |
| 63 | $strSQL = "SELECT `username` FROM `users` WHERE `ID` = " . floatval($userID) . " LIMIT 1"; |
| 64 | $data = mysql_query($strSQL); |
| 65 | $row = mysql_fetch_array($data); |
| 66 | return $row[0]; |
| 67 | } |

getUserRoles()

getUserRoles() will return an array of roles the current user it is assigned to. First, we will build the appropriate SQL statement and execute it. Using while(), we loop through all of the matching results, and finally return an array of the IDs. Likewise, getAllRoles() will return all of the available roles (not just the ones the user is assigned to). Based on the value of the argument, $format, it will return an array of IDs for all the roles, or an array of associative array with the ID and name of each role. This allows our function to do double duty. If we want to use the array of user roles in MySQL, we need an array of role IDs; but if we want to display the roles on our page, it would be helpful to have one array with all the info in it.

buildACL

buildACL() generates the permissions array for the user, and is the heart of the system. First, we check to see if the user is assigned to any roles. If they are, we use array_merge() to combine the existing permissions array with the new array returned from the call to getRolePerms() (which gets all the permissions for all the roles the user is assigned to). Then we do the same for the individual user permissions, this time calling getUserPerms(). It is important that we read the user perms second because array_merge() overwrites duplicate keys. Reading the user permissions second ensures that the individual permissions will override any permissions inherited from the user's roles.

All of the functions getPermKeyFromID(), getPermNameFromID(), getRoleNameFromID() and getUsername() are simply "lookup" functions. They allow us to pass in an ID and return the appropriate text value. You can see that we build the SQL statement, then execute it and return the result. Next we will add in the two functions which will pull the permissions from the database.

| 1 | |
| 2 | function getRolePerms($role) |
| 3 | { |
| 4 | if (is_array($role)) |
| 5 | { |
| 6 | $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC"; |
| 7 | } else { |
| 8 | $roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC"; |
| 9 | } |
| 10 | $data = mysql_query($roleSQL); |
| 11 | $perms = array(); |
| 12 | while($row = mysql_fetch_assoc($data)) |
| 13 | { |
| 14 | $pK = strtolower($this->getPermKeyFromID($row['permID'])); |
| 15 | if ($pK == '') { continue; } |
| 16 | if ($row['value'] === '1') { |
| 17 | $hP = true; |
| 18 | } else { |
| 19 | $hP = false; |
| 20 | } |
| 21 | $perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); |
| 22 | } |
| 23 | return $perms; |
| 24 | } |
| 25 | |
| 26 | function getUserPerms($userID) |
| 27 | { |
| 28 | $strSQL = "SELECT * FROM `user_perms` WHERE `userID` = " . floatval($userID) . " ORDER BY `addDate` ASC"; |
| 29 | $data = mysql_query($strSQL); |
| 30 | $perms = array(); |
| 31 | while($row = mysql_fetch_assoc($data)) |
| 32 | { |
| 33 | $pK = strtolower($this->getPermKeyFromID($row['permID'])); |
| 34 | if ($pK == '') { continue; } |
| 35 | if ($row['value'] == '1') { |
| 36 | $hP = true; |
| 37 | } else { |
| 38 | $hP = false; |
| 39 | } |
| 40 | $perms[$pK] = array('perm' => $pK,'inheritted' => false,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']); |
| 41 | } |
| 42 | return $perms; |
| 43 | } |
| 44 | function getAllPerms($format='ids') |
| 45 | { |
| 46 | $format = strtolower($format); |
| 47 | $strSQL = "SELECT * FROM `permissions` ORDER BY `permName` ASC"; |
| 48 | $data = mysql_query($strSQL); |
| 49 | $resp = array(); |
| 50 | while($row = mysql_fetch_assoc($data)) |
| 51 | { |
| 52 | if ($format == 'full') |
| 53 | { |
| 54 | $resp[$row['permKey']] = array('ID' => $row['ID'], 'Name' => $row['permName'], 'Key' => $row['permKey']); |
| 55 | } else { |
| 56 | $resp[] = $row['ID']; |
| 57 | } |
| 58 | } |
| 59 | return $resp; |
| 60 | } |

These functions are essentially identical except for the tables they pull from. The single argument is the ID for the roles/users you want to pull. The roles function can be passed an array or an integer, while the user function can only be passed an integer. By using is_array(), we determine how to treat the argument for the role permission function. If it is an array, we use implode() to create a comma-separated-list. In either case, we use that value in the SQL. Then, we create a new empty array called $perms - this will store the permissions locally in the function.

Inside the while() loop, we perform several functions. First we generate the variable $pK, which we will use as the name of the array key. Because we will be looking for this value to determine if the user has a specific permission, it is important that we have it in a uniform format, which is why we are using strtolower(). If the key value is blank, we skip to the next iteration using continue;. Next, we look at $row['value'] to set an implicit boolean value for the permission. This ensures that only an actual value of '1' in the table will equate with true (i.e. the user has the permission), and is important for security. Otherwise we set the permission to false. At the end of the function, we create an array with several named keys so we can get all of the information about a permission. That array is assign to a new named key in the $perms array we created earlier. Note that we use $pK to create an appropriately named index. Finally we return the array.

You can see that in the returned array, there is an index name 'inherited'. This has a special significance for the ACL. If a user receives a permission because it belongs to a role the user is assigned to, it is said to be inherited. If the permissions is assigned to the user manually, it is not inherited.

In getAllPerms(), we build a list of all available permissions. Similar to getAllRoles() we can pass in a format argument to determine how the results will be returned. Now for the last part of the class:

| 1 | |
| 2 | function userHasRole($roleID) |
| 3 | { |
| 4 | foreach($this->userRoles as $k => $v) |
| 5 | { |
| 6 | if (floatval($v) === floatval($roleID)) |
| 7 | { |
| 8 | return true; |
| 9 | } |
| 10 | } |
| 11 | return false; |
| 12 | } |
| 13 | |
| 14 | function hasPermission($permKey) |
| 15 | { |
| 16 | $permKey = strtolower($permKey); |
| 17 | if (array_key_exists($permKey,$this->perms)) |
| 18 | { |
| 19 | if ($this->perms[$permKey]['value'] === '1' || $this->perms[$permKey]['value'] === true) |
| 20 | { |
| 21 | return true; |
| 22 | } else { |
| 23 | return false; |
| 24 | } |
| 25 | } else { |
| 26 | return false; |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | ?> |

These last two methods are very important for the functionality of the ACL. userHasRole() accepts the single argument of a role ID. By looping through all the elements in the $userRoles array, we can determine if the user is assigned to that role. If they are, we return true, or false otherwise. hasPermission() is the method we use to determine if a user can access something. We pass in the key for the permission we want to check. We make it uniform by converting it to lowercase, and see if there is an index with that name in the $perms array. If there is, we check to make sure that it is set to '1' and return true, or return false otherwise. This is the function we will use if we want to figure out if a user can do something.

Step 4: User Admin

The first part of our admin section will deal with managing users. We need to create four different interfaces to deal with the aspects of managing users: List the users so we can select one to edit, viewing a detail user listing, assign users to roles, and grant users permissions.

User Forms

User Forms

User Forms

Open /admin/users.php and add the following code:

| 1 | |
| 2 | <?php |
| 3 | include("../assets/php/database.php"); |
| 4 | include("../assets/php/class.acl.php"); |
| 5 | $myACL = new ACL(); |
| 6 | if ($myACL->hasPermission('access_admin') != true)\
{\
header("location: ../index.php");\
} |
| 7 | ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| 8 | \ |
| 9 | <head> |
| 10 | \ |
| 11 | \ACL Test\ |
| 12 | \ |
| 13 | </head> |
| 14 | <body> |
| 15 | \ \ |
| 16 | \ \Main Screen\ | \Admin Home\\ |
| 17 | \ |
| 18 | <!-- PAGE CONTENT --> |
| 19 | </div> |
| 20 | </body> |
| 21 | </html> |

As always, we need to include our database and ACL files, and set up the ACL object. Then we set up the security for the page. In this case, we are ensuring that the user has the permission 'access_admin'. If they don't, they are redirected.

NOTE: If you change the ACL permissions so that user #1 no longer has the 'access_admin' permission, you won't be able to access the admin site. Also, you must first go to /index.php before you go to any of the admin pages, as index.php sets the session variable assigning you userID #1.

Right now this is just the basic layout of the page. In the next steps, we will replace \ above with some code to manage the users. We will use the querystring variable $action to determine which of the user interfaces we should display. There are four possible values that we will address: If it is null, we display a list of the current users. If it is set to 'user', we display the form for a single user. If it is set to 'roles', we display the form to assign a user. If it is set to 'perms', we display the form to give the user permissions.

List Users

Add this code inside the div with the id 'page':

| 1 | |
| 2 | \ |
| 3 | \

Select a User to Manage:\

|
| 4 | <? |
| 5 | $strSQL = "SELECT * FROM `users` ORDER BY `Username` ASC"; |
| 6 | $data = mysql_query($strSQL); |
| 7 | while ($row = mysql_fetch_assoc($data)) |
| 8 | { |
| 9 | echo "\" . $row['username'] . "\\
"; |
| 10 | } |
| 11 | } ?> |

The concept here is pretty simple. We build a SQL query, run it and loop through the results. For each user, we generate a link that will enable us to edit that particular user.

Edit Individual User

Now, add this code directly under the previous code block:

| 1 | |
| 2 | <? |
| 3 | if ($_GET['action'] == 'user' ) { |
| 4 | $userACL = new ACL($_GET['userID']); |
| 5 | ?> |
| 6 | \

Managing \getUsername($\_GET\['userID'\]); ?>:\

|
| 7 | ... Some form to edit user info ... |
| 8 | \

Roles for user: (\Manage Roles\)\

|
| 9 | <ul> |
| 10 | \<? $roles = $userACL->getUserRoles(); |
| 11 | foreach ($roles as $k => $v) |
| 12 | { |
| 13 | echo "\
  • " . $userACL->getRoleNameFromID($v) . "\
  • "; |
    | 14 | } |
    | 15 | ?> |
    | 16 | </ul> |
    | 17 | \

    Permissions for user: (\Manage Permissions\)\

    |
    | 18 | <ul> |
    | 19 | \<? $perms = $userACL->perms; |
    | 20 | foreach ($perms as $k => $v) |
    | 21 | { |
    | 22 | if ($v['value'] === false) { continue; } |
    | 23 | echo "\
  • " . $v['Name']; |
    | 24 | if ($v['inheritted']) { echo " (inheritted)"; } |
    | 25 | echo "\
  • "; |
    | 26 | } |
    | 27 | ?> |
    | 28 | </ul> |
    | 29 | \ |

    When we edit a user, we need to load the ACL for that user. This will enable us to see which roles and permissions they have. We start that by creating a new ACL object, and passing in the $userID from the querystring (this way we load that user's ACL, instead of the logged in user). After that is where your normal edit user form would go. Typical things would be text fields to edit username, password, etc. Below that we list the roles the user is assigned to, and also provide a link so we can assign the user to other roles. Lines 10-16 load all the roles that the user is assigned to, and prints them out as list items using foreach(). Then we list out the user's permissions in a similar fashion. We only print out the permissions that the user has, not ones that are set to false.

    User Detail

    User Detail

    User Detail

    Assign Roles

    Our assign roles form will end up looking like this:

    User Roles

    User Roles

    User Roles

    Add this code right below the previous code block:

    | 1 | |
    | 2 | \ |
    | 3 | \

    Manage User Roles: (\getUsername($\_GET\['userID'\]); ?>)\

    |
    | 4 | \ |
    | 5 | \ |
    \Member\Not Member\
    \" . $v['Name'] . "\\\userHasRole($v['ID'])) { echo " checked=\"checked\""; } |
    | 15 | echo " />\
    \userHasRole($v['ID'])) { echo " checked=\"checked\""; } |
    | 18 | echo " />\
    " . $v['Name'] . "\\"; |
    | 15 | echo "\Allow\"; |
    | 18 | echo "\Deny\"; |
    | 21 | echo "\{ | | 24 | echo " selected=\"selected\""; | | 25 | if ($rPerms\[$v\['Key'\]\]\['value'\] === true ) | | 26 | { | | 27 | $iVal = '(Allow)'; | | 28 | } else { | | 29 | $iVal = '(Deny)'; | | 30 | } | | 31 | } | | 32 | echo ">Inherit $iVal\"; |
    | 33 | echo "\\
    \Allow\Deny\Ignore\
    \" . $v['Name'] . "\\\\\\\\
    原文链接:https://code.tutsplus.com/tutorials/a-better-login-system--net-3461