I took my first stab at a user authentication function. I invented my own way of doing this. Is this a safe and efficient way of giving a user Read/Edit/Delete permission on tables in a MySQL database?
The Class
class Personnel {
//set tables that will need permissions and actions
protected static $actions = array("read", "edit", "delete");
protected static $table_names = array("species", "users", "news");
//this will generate a form with checkbox for each position in the permissions array
public static function set_permissions_form($current_permissions) {
for($i=0; $i<count(self::$table_names); $i++) {
$table_name = self::$table_names[$i];
$form .= $table_name . ":<br />";
for($z=0; $z<count(self::$actions); $z++) {
$action = self::$actions[$z];
$form .= $action . ": <input type='checkbox' name='permissions[" . $table_name . "][" . $action . "]'";
if($current_permissions) {
$form .= ($current_permissions[$table_name][$action] == "1" ? " checked =\"checked\"" : "");
}
$form .= " value=1 />";
$form .= "<br />";
}
}
return $form;
}
}
The Form
If this is a new user or an existing user with no permissions set then $current_permissions
will be NULL
. If a permissions array does exist in the database unserialize it and check any checkbox when name = array key.
$current_permissions = unserialize($personnel->permissions);
$form = "<form action='save_personnel.php' method='post'>";
$form .= Personnel::set_permissions_form($current_permissions);
$form .= "<input type='submit' value='Save Changes' />";
$form .= "</form>";
echo $form;
Save
Once the form is submitted each box checked will be a "1" in the permissions array. This next snippet serializes the array and stores it in the database. I did not include code for $personnel->save() but you know what it does. Create user if does not exist, update user if it does.
$personnel = new Personnel();
$personnel->permissions = serialize($_POST['permissions']);
if($personnel->save()) {
redirect_to("manage_personnel.php");
}
Check for Permission
The next steps I haven't completed yet but basically it will pull $personnel->permissions
from database and unserialize it. Then say it is on a page where user is trying to edit species, $permissions["species"]["read"] == '1' ? you shall pass : you shall not pass;
.
Am I heading in the right direction with this or am I over complicating?