Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/ffc3bc6d019330dda274c18844a6f500 to your computer and use it in GitHub Desktop.
Save code-boxx/ffc3bc6d019330dda274c18844a6f500 to your computer and use it in GitHub Desktop.
PHP MYSQL User Role Management

PHP MYSQL USER ROLE MANAGEMENT

https://code-boxx.com/php-user-role-management-system/

NOTES

  1. Create a database and import 1-database.sql.
  2. Change the database settings in 2-lib-user.php to your own.
  3. Run 3a-login.php to log in as a manager, supervisor, or log out.
  4. Then access 3b-run.php to see how the permission restrictions work.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) ROLES
CREATE TABLE `roles` (
`role_id` bigint(20) NOT NULL,
`role_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `roles`
ADD PRIMARY KEY (`role_id`),
ADD UNIQUE KEY `role_name` (`role_name`);
ALTER TABLE `roles`
MODIFY `role_id` bigint(20) NOT NULL AUTO_INCREMENT;
INSERT INTO `roles` (`role_id`, `role_name`) VALUES
(1, 'Manager'),
(2, 'Supervisor');
-- (B) PERMISSIONS
CREATE TABLE `permissions` (
`perm_id` bigint(20) NOT NULL,
`perm_mod` varchar(5) NOT NULL,
`perm_desc` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `permissions`
ADD PRIMARY KEY (`perm_id`),
ADD KEY `perm_mod` (`perm_mod`);
ALTER TABLE `permissions`
MODIFY `perm_id` bigint(20) NOT NULL AUTO_INCREMENT;
INSERT INTO `permissions` (`perm_id`, `perm_mod`, `perm_desc`) VALUES
(1, 'USR', 'Get users'),
(2, 'USR', 'Save users'),
(3, 'USR', 'Delete users');
-- (C) ROLE PERMISSIONS
CREATE TABLE `roles_permissions` (
`role_id` bigint(20) NOT NULL,
`perm_id` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `roles_permissions`
ADD PRIMARY KEY (`role_id`,`perm_id`);
INSERT INTO `roles_permissions` (`role_id`, `perm_id`) VALUES
(1, 1), (1, 2), (1, 3),
(2, 1);
-- (D) USERS
CREATE TABLE `users` (
`user_id` bigint(20) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL,
`role_id` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`),
ADD UNIQUE KEY `user_email` (`user_email`),
ADD KEY `role_id` (`role_id`);
ALTER TABLE `users`
MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT;
INSERT INTO `users` (`user_email`, `user_password`, `role_id`) VALUES
('joe@doe.com', '123456', 1),
('jon@doe.com', '123456', 2);
<?php
class User {
// (A) CONSTRUCTOR - CONNECT TO THE DATABASE
private $pdo = null;
private $stmt = null;
public $error;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) LOGIN
function login ($email, $password) {
// (D1) GET USER & CHECK PASSWORD
$this->query("SELECT * FROM `users` JOIN `roles` USING (`role_id`) WHERE `user_email`=?", [$email]);
$user = $this->stmt->fetch();
$valid = is_array($user);
if ($valid) { $valid = $password == $user["user_password"]; }
if (!$valid) {
$this->error = "Invalid email/password";
return false;
}
// (D2) GET PERMISSIONS
$user["permissions"] = [];
$this->query(
"SELECT * FROM `roles_permissions` r
LEFT JOIN `permissions` p USING (`perm_id`)
WHERE r.`role_id`=?", [$user["role_id"]]
);
while ($r = $this->stmt->fetch()) {
if (!isset($user["permissions"][$r["perm_mod"]])) {
$user["permissions"][$r["perm_mod"]] = [];
}
$user["permissions"][$r["perm_mod"]][] = $r["perm_id"];
}
// (D3) DONE
$_SESSION["user"] = $user;
unset($_SESSION["user"]["user_password"]);
return true;
}
// (E) CHECK PERMISSION
function check ($module, $perm) {
$valid = isset($_SESSION["user"]);
if ($valid) { $valid = in_array($perm, $_SESSION["user"]["permissions"][$module]); }
if ($valid) { return true; }
else { $this->error = "No permission to access."; return false; }
}
// (F) GET USER
function get ($email) {
if (!$this->check("USR", 1)) { return false; }
$this->query("SELECT * FROM `users` JOIN `roles` USING (`role_id`) WHERE `user_email`=?", [$email]);
return $this->stmt->fetch();
}
// (G) SAVE USER
function save ($email, $password, $role, $id=null) {
if (!$this->check("USR", 2)) { return false; }
$sql = $id==null
? "INSERT INTO `users` (`user_email`, `user_password`, `role_id`) VALUES (?,?,?)"
: "UPDATE `users` SET `user_email`=?, `user_password`=?, `role_id`=? WHERE `user_id`=?" ;
$data = [$email, $password, $role];
if ($id!=null) { $data[] = $id; }
$this->query($sql, $data);
return true;
}
// (H) DELETE USER
function del ($id) {
if (!$this->check("USR", 3)) { return false; }
$this->query("DELETE FROM `users` WHERE `user_id`=?", [$id]);
return true;
}
}
// (I) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (J) START!
$_USR = new User();
session_start();
<?php
// (A) LOAD LIBRARY
require "2-lib-user.php";
// (B) TRY LOGGING IN AS DIFFERENT USERS
echo $_USR->login("jon@doe.com", "123456") ? "OK" : $_USR->error;
// echo $_USR->login("joe@doe.com", "123456") ? "OK" : $_USR->error;
// (C) TO LOGOUT
// if (isset($_SESSION["user"])) { unset($_SESSION["user"]); }
// (D) WHO AM I?
print_r($_SESSION);
<?php
// (A) LOAD LIBRARY
require "2-lib-user.php";
// (B) GET USER
$user = $_USR->get("jon@doe.com");
if ($user===false) { echo $_USR->error . "\r\n"; }
print_r($user);
// (C) SAVE USER
echo $_USR->save("job@doe.com", "123456", 1) ? "OK" : $_USR->error . "\r\n" ;
// echo $_USR->save("joy@doe.com", "123456", 1) ? "OK" : $_USR->error . "\r\n" ;
// (D) DELETE USER
echo $_USR->del(123) ? "OK" : $_USR->error . "\r\n" ;
// echo $_USR->del(4) ? "OK" : $_USR->error . "\r\n" ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment