You are on page 1of 26

BAN CƠ YẾU CHÍNH PHỦ

HỌC VIỆN KỸ THUẬT MẬT MÃ


¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

HỌC PHẦN
An toàn ứng dụng Web

BÀI THỰC HÀNH


Phân quyền người dùng trong ứng dụng Web

Hà Nội, 2019
MỤC LỤC
1. Điều kiện tiên quyết............................................................................................. 1
2. Giới thiệu .............................................................................................................. 1
3. Kịch bản thực hành ............................................................................................. 1
4. Mục tiêu bài thực hành ....................................................................................... 1
5. Tổ chức thực hành............................................................................................... 1
6. Môi trường thực hành......................................................................................... 2
7. Sơ đồ thực hành ................................................................................................... 2
8. Các nhiệm vụ cần thực hiện ............................................................................... 2
Nhiệm vụ 1. Xây dựng Database ............................................................................ 2
Nhiệm vụ 2. Xây dựng module phân quyền.......................................................... 3
Nhiệm vụ 3. Thực hiện phân quyền người dùng theo vai trò ........................... 22
9. Đánh giá bài thực hành......................................... Error! Bookmark not defined.
DANH MỤC HÌNH ẢNH

Hình 1. Sơ đồ database .............................................................................................. 2


Hình 2. Form login .................................................................................................... 4
Hình 3. Menu bar ...................................................................................................... 5
Hình 4. Form thêm mới quyền .................................................................................. 7
Hình 5. Bảng hiển thị danh sách quyền .................................................................... 8
Hình 6. Tạo form thêm mới quyền ............................................................................ 9
Hình 7. Bảng hiển thị danh sách vai trò .................................................................. 11
Hình 8. Form thêm mới user ................................................................................... 15
Hình 9. Bảng hiển thị danh sách user...................................................................... 17
Hình 10. Form gán vai trò cho user......................................................................... 18
Hình 11. Kiểm tra vai trò và quyền của user .......................................................... 21

ii
1. Điều kiện tiên quyết
Bài thực hành xác thực người dùng trong ứng dụng Web

2. Giới thiệu
Bất kể hệ thống website nào cũng có người dùng và đi kèm với nó là việc
xác thực (authentication) và phân quyền (authorization) với từng người dùng. Sau
khi người dùng đăng nhập thành công, nhiệm vụ tiếp theo của ứng dụng web là xác
định những tài nguyên mà người dùng được phép truy cập. Thao tác này được gọi
là phân quyền người dùng (users authorization). Có 3 mô hình phân quyền truy cập
điển hình là: phân quyền truy cập tùy quyền (discretionary access control), phân
quyền truy cập bắt buộc (mandatory access control) và phân quyền dựa vào vai trò
(role – based access control). Đối với ứng dụng web, mô hình phân quyền thường
được dùng là phân quyền dựa vào vai trò.
Trong bài thực hành này, chúng ta sẽ thực hiện phân quyền người dùng dựa
vào vai trò trong ứng dụng web.

3. Kịch bản thực hành


3.1. Xây dựng database:
Xây dựng database với các bảng sau: users, roles, permission, user_has_roles,
roles_has_permissions
3.2. Xây dựng module phân quyền
Tạo các form thêm mới quyền, vai trò và người dùng và các bảng hiển thị thông
tin. Sau đó thực hiện việc kiểm tra phân quyền
3.3. Thực hiện việc phân quyền
Trong một hệ thống sẽ có một người dùng duy nhất có quyền thiết lập mô hình
phân quyền cho hệ thống. Sau khi đăng nhập thành công, người quản trị ứng
dụng web sẽ :
- Thiết lập vai trò của người dùng
- Thiết lập các quyền theo vai trò
- Mỗi một user sẽ có một hoặc nhiều vai trò trong hệ thống

4. Mục tiêu bài thực hành


Bài thực hành giúp chúng ta hiểu rõ:
- Hiểu rõ về cơ chế phân quyền thường dùng trong ứng dụng web
- Biết cách xây dựng chức năng phân quyền đối với một ứng dụng web

5. Tổ chức thực hành


Yêu cầu thực hành: độc lập
Thời gian: 45 phút

1
6. Môi trường thực hành
- Yêu cầu phần cứng:
+ Số lượng máy tính cần chuẩn bị : 1
+ Cấu hình tối thiểu của Intel Core i3, 4GB RAM
- Yêu cầu phần mềm trên máy:
+ Hệ điều hành trên máy tính : Window
+ Phần mềm : Sublime Text 3, Xampp
- Yêu cầu kết nối mạng Internet: có

7. Sơ đồ thực hành
Không có

8. Các nhiệm vụ cần thực hiện


Nhiệm vụ 1. Xây dựng Database
Xây dựng database với các bảng và mối quan hệ giữa các bảng như sau:

Hình 1. Sơ đồ database
Tạo bảng users như sau:
CREATE TABLE users
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100),
password VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP,
updated_at TIMESTAMP
)
ALTER TABLE users
ADD PRIMARY KEY (id);
Tạo bảng user_has_roles:
CREATE TABLE `user_has_roles`
(
id int(10) UNSIGNED NOT NULL,

2
role_id int(10) UNSIGNED NOT NULL,
user_id int(10) UNSIGNED NOT NULL
)
Tạo khóa ngoại cho các bảng user_has_roles:
ALTER TABLE role_has_permissions
ADD PRIMARY KEY (id),
ADD KEY role_has_permissions_permission_id_foreign (permission_id),
ADD KEY role_has_permissions_role_id_foreign (role_id);
Tạo ràng buộc giữa bảng users và bảng user_has_roles:
ALTER TABLE user_has_roles
ADD CONSTRAINT user_has_roles_ibfk_1 FOREIGN KEY (user_id)
REFERENCES users (id)
Tương tự tạo và liên kết các bảng còn lại như sơ đồ trên.
Nhiệm vụ 2. Xây dựng module phân quyền
 Bước 1: Tạo thư mục phanquyen trong thư mục htdocs
Tạo thư mục phanquyen/includes để chứa các file thư viện kết nối database
 Bước 2: Tạo kết nối đến mysql để lấy dữ liệu:
- Tạo file database.php trong thư mục phanquyen/includes:
<?php
$database['host'] = 'localhost'; //Tên Hosting
$database['dbname'] = 'tech_php'; //Tên của Database
$database['username'] = 'root'; //Tên sử dụng Database
$database['password'] = ''; //Mật khẩu sử dụng Database
$connect=mysqli_connect("{$database['host']}","{$database['userna
me']}","{$database['password']}"); // Tạo kết nối
mysqli_select_db($connect, "{$database['dbname']}") or die("Không
thể chọn database"); // chọn bảng
mysqli_set_charset($connect, 'UTF8'); // set ngôn ngữ
?>
Sau khi tạo xong file kết nối database, khi tạo thẻ <?php ?> ở phần đầu các
file .php cần thêm dòng code sau để kết nối đến database:
include 'includes/database.php';
 Bước 3: Tạo liên kết tới các file css,bootstrap
Khi tạo các file .php, các thẻ liên kết này thường được đặt ở phần đầu và để
trong thẻ <head></head>.
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
// tạo title
<title> Danh sách thành viên - Hệ Thống Quản Trị </title>
// sử dụng bootstrap
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
// sử dụng font
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
// sử dụng javasscript
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></scri
pt>

3
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js">
</script>
 Bước 4: Tạo file login.php trong thư mục phanquyen để thực hiện đăng
nhập:
- Tạo form login như sau:

Hình 2. Form login


- Thực hiện tạo form login:
<div class="container">
<div class="row">
<div id="formContent" style="max-width:350px;margin:0 auto;">
<h1 style="font-size: 25px;font-weight: 500; margin: 30px 0 20px; text-align:
center;"> Đăng Nhập Hệ Thống </h1>
<form method="POST">
<div class="form-group">
<label for="email"> Email: </label>
<input type="email" class="form-control" id="login" name="email"
placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password"
placeholder="Password">
</div>
<div class="form-group">
<input type="submit" class="btn btn-sm btn-success" value="Đăng Nhập">
</div>
</form>
</div>
</div>
</div>
Thực hiện đoạn code sau trong thẻ <?php ?> ở phần đầu file để kiểm tra khi
người dùng click vào button Đăng nhập:
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);

4
$password = md5($password); // Mã hóa md5 mật khẩu
$query = mysqli_query($connect, "SELECT
users.email, users.id as user_id, users.name as user_name,
GROUP_CONCAT(permissions.name) as permission_name,
user_has_roles.user_id,
roles.name as role_name,
roles.id as role_id
FROM users
LEFT JOIN user_has_roles ON users.id = user_has_roles.user_id
LEFT JOIN roles ON roles.id = user_has_roles.role_id
LEFT JOIN role_has_permissions ON role_has_permissions.role_id = roles.id
LEFT JOIN permissions ON role_has_permissions.permission_id = permissions.id
WHERE email = '$email' AND password = '$password'
GROUP BY roles.id");
if (mysqli_num_rows($query) > 0) { $permissions = '';
while ($row = mysqli_fetch_array($query)) {
$permissions .= $row['permission_name'];
$_SESSION['auth_user'] = [
'id' => $row['user_id'],
'name' => $row['user_name'],
'email' => $row['email']
];
}
$_SESSION['auth_user']['permission_name'] = explode(',', $permissions);
header('Location: ' . 'index.php'); // return redirect về login
exit();
}
else {
header('Location: ' . $_SERVER['HTTP_REFERER']); // return back
exit;
}
}
 Bước 5: Tạo file logout.php trong thư mục phanquyen để thực hiện đăng
xuất:
Sử dụng đoạn code dưới đây để thực hiện đăng xuất: Khi user đăng xuất sẽ
quay trở về trang login.
<?php
session_start();// khởi tạo session
session_destroy();
header('Location: ' . 'login.php');
?>
 Bước 6: Tạo file nav.php trong thư mục phanquyen/includes để tạo
menubar:
Tạo menu với thông tin sau: Trang chủ, Quản lý user, Quản lý vai trò, Quản
lý quyền, Đăng xuất.

Hình 3. Menu bar


Thực hiện đoạn code sau để tạo menu:
<nav class="navbar navbar-default">

5
<div class="container">
<ul class="nav navbar-nav">
<li>
<a href="index.php">Trang chủ</a>
</li>
<li class="active">
<a href="users.php">Quản lý User</a>
</li>
<li>
<a href="roles.php">Quản lý vai trò</a>
</li>
<li>
<a href="permission.php">Quản lý quyền</a>
</li>

<li>
<a href="logout.php">Đăng Xuất</a>
</li>
</ul>
</div>
</nav>
Kiểm tra khi user login vào sẽ có vai trò và quyền hạn nào với website, từ đó
sẽ có quyền được truy cập vào các tab menu nào bên trên, thêm dòng code sau để
thực hiện kiểm tra:
<?php if(in_array('Phân quyền',$_SESSION['auth_user']['permission_name'])) {
?> // dòng này ở dưới dòng code tạo tab Trang chủ
<?php } ?> // dòng này ở dưới dòng code tạo tab Quản lý quyền
Sau khi tạo xong, khi tạo các file .php thêm dòng code vào phần
<body><body> để thực hiện kết nối tới file nav.php để hiển thị menu:
<?php include 'includes/nav.php'; ?>
 Bước 7: Tạo file permissions.php trong thư mục phanquyen để thực hiện
tạo và hiển thị các quyền trong hệ thống
- Tạo form thêm mới quyền như sau:

6
Hình 4. Form thêm mới quyền
Thực hiện đoạn code sau để tạo form thêm mới:
<h2> Quyền </h2>
<div class="col-md-6">
<h3> Thêm mới </h3>
<div class="panel">
<form method="post">
<div class="form-group">
<label for="name"> Tên: </label>
<input type="text" name="name" required class="form-control">
</div>
<div class="form-group">
<label for="description"> Mô tả: </label>
<textarea name="description" cols="30" rows="10" class="form-
control"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="add-permission" value="1">
<input type="submit" class="btn btn-sm btn-warning"
value="Thêm mới">
</div>
</form>
</div>
</div>
<div class="col-md-6">
<table class="table table-bordered" style="margin-top: 60px;border:1px
solid #eee">
<thead>
<tr>
<th>ID</th>
<th>Tên</th>
<th>Mô tả</th>
</tr>

7
</thead>
<tbody>
<?php foreach ($permissions as $item) { ?>
<tr>
<td><?= $item['id']; ?></td>
<td><?= $item['name']; ?></td>
<td><?= $item['description']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
Tiếp theo, thực hiện câu lệnh SQL trong thẻ <?php ?> ở phần đầu file để
truy vấn insert dữ liệu vào bảng trong database:
if (isset($_POST['add-permission-groups'])) {
$name = $_POST['name'];
$description = $_POST['description'];
$created_at = date("Y-m-d H:i:s");
$sql_insert = "INSERT INTO permission_groups(name, description, created_at)
VALUES ('{$name}','{$description}','{$created_at}')";
$query_insert = mysqli_query($connect, $sql_insert);
if ($query_insert) // nếu lưu thành công
{
header('Location: ' . '?page=dang-nhap'); // trở về login
exit;
}
else // nếu thất bại
{
header('Location: ' . $_SERVER['HTTP_REFERER']);// back
exit;
}
}
- Tạo bảng hiển thị danh sách quyền như sau:

Hình 5. Bảng hiển thị danh sách quyền


Thực hiện đoạn code dưới đây để tạo bảng hiển thị danh sách nhóm quyền:
<div class="col-md-6">
<table class="table table-bordered" style="margin-top: 60px;border:1px
solid #eee">
<thead>
<tr>
<th>ID</th>
<th>Tên</th>
<th>Mô tả</th>
</tr>
</thead>
<tbody>

8
</tbody>
</table>
</div>
Tiếp theo, thực hiện câu lệnh SQL trong thẻ <?php ?> ở phần đầu file để
truy vấn lấy dữ liệu từ bảng trong database để hiển thị danh sách quyền:
$sql = "SELECT * FROM permissions";
$query = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($query);
$permissions = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($query)) {
$permissions[] = [
'id' => $row['id'],
'name' => $row['name'],
'description' => $row['description']
];
}
}
Sau khi thực hiện truy vấn, thêm đoạn code sau vào thẻ <tbody></tbody> để
hiển thị danh sách các quyền:
<?php foreach ($permission_groups as $item) { ?>
<tr>
<td><?= $item['id']; ?></td>
<td><?= $item['name']; ?></td>
<td><?= $item['description']; ?></td>
</tr>
<?php } ?>
 Bước 8: Tạo file add-role.php trong thư mục phanquyen để thực hiện việc
thêm vai trò cho người dùng:
- Tạo form thêm mới vai trò như sau:

Hình 6. Tạo form thêm mới quyền


Thực hiện đoạn code sau để tạo form thêm mới:
<div class="row">
<div class="col-md-6">
<h2> Thêm mới vai trò </h2>
</div>

9
<div class="col-md-6">
<h2> Chọn quyền cho vai trò </h2>
</div>
</div>
<form method="post">
<div class="col-md-12" style="margin-top:30px;">
<div class="col-md-6" style="max-width:500px;border:1px solid
#eee;padding:20px;">
<div class="form-group">
<label for="name">Tên:</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label for="description">Mô tả:</label>
<textarea class="form-control" name="description" cols="30"
rows="10"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
<div class="panel panel-info">
<div class="panel-heading"> Chọn quyền: </div>
<div class="panel-body">
// vòng lặp lấy tất cả tất các quyền trong hệ thống
<?php foreach ($permissions as $group) { ?>
<div class="form-group">
<label><input name="permissions[]"
type="checkbox" value="<?= $group['id'] ?>">
<?= $group['name'] ?></label>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-info" value="Thêm mới">
<a class="btn btn-default" href="roles.php"> Hủy </a>
</div>
</form>
Tiếp theo thực hiện câu lệnh sau trong thẻ <?php ?> ở phần đầu file để lấy
dữ liệu từ bảng permissions, lấy tất cả các quyền có trong hệ thống để chọn quyền
cho vai trò:
$sql_pms = "SELECT * FROM permissions";
$query_pms = mysqli_query($connect, $sql_pms);
$num_rows_pms = mysqli_num_rows($query_pms);
$permissions = array();
if ($num_rows_pms > 0) {
while ($row_pms = mysqli_fetch_array($query_pms)) {
$permission_groups = $row_pms['permission_group'];
$permissions[$permission_groups][] = [
'id' => $row_pms['id'], 'name' => $row_pms['name']
];
}

10
}
Sau khi lấy tất cả các quyền có trong database, sử dụng đoạn code sau để
thực hiện việc insert dữ liệu vào bảng roles khi người dùng click button “Thêm
mới”:
$role_id = false; // tạo biến role_id
$sql = "INSERT INTO roles(name,description,created_at) VALUE
('{$name}','{$description}','{$created_at}')";
$insert = mysqli_query($connect, $sql);
if ($insert == true) {
$role_id = mysqli_insert_id($connect
if (count($in_permissions) > 0 && $role_id != false) {
foreach ($in_permissions as $pms_id) {
mysqli_query($connect,"INSERT INTO
role_has_permissions (permission_id,role_id)
VALUE('{$pms_id}','{$role_id}')");
}
}
header('Location: ' . 'roles.php');
exit;
}
else {
header('Location: ' . $_SERVER['HTTP_REFERER']);// return back
exit;
}
}
 Bước 9: Tạo file roles.php trong thư mục phanquyen để hiển thị danh
sách vai trò:
Tạo danh sách vai trò như sau:

Hình 7. Bảng hiển thị danh sách vai trò


Thực hiện đoạn code dưới đây để tạo danh sách vai trò:
<h2> Quản lý vai trò </h2>
<a href="add-role.php" class="btn btn-sm btn-info"> Thêm mới vai trò
</a>
<table class="table table-bordered" style="margin-top:
60px;border:1px solid #eee">
<thead>
<tr>

11
<th>ID</th>
<th>Tên</th>
<th>Mô tả</th>
<th style="width:200px"></th>
</tr>
</thead>
<tbody>
//sử dụng vòng lặp để lấy tất cả các vai trò trong hệ thống
<?php foreach ($roles as $item) { ?>
<tr>
<td><?= $item['id']; ?></td>
<td><?= $item['name']; ?></td>
<td><?= $item['description']; ?></td>
<td style="width:200px;text-align:center">
<a href="edit-role.php?id=<?= $item['id']; ?>"
class="btn btn-success btn-sm"> Sửa vai trò </a>
<a onclick="return confirm('Bạn có chắc xóa không
?')" href="delete-role.php?id=<?= $item['id']; ?>"
class="btn btn-warning btn-sm"> Xóa vai trò </a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
}
Sau khi tạo form, thực hiện câu lệnh SQL sau trong thẻ <?php ?> ở phần đầu
file để lấy dữ liệu từ database:
$sql = "SELECT * FROM roles WHERE deleted_at IS NULL";
$query = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($query);

$roles = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($query)) {
$roles[] = [
'id' => $row['id'],
'name' => $row['name'],
'description' => $row['description']
];
}
}
 Bước 10: Tạo file edit-role.php trong thư mục phanquyen để thực hiện
chỉnh sửa các vai trò:
Lưu ý: form chỉnh chửa giống form tạo mới vai trò, có thể copy bên file add-
role.php:
<h2> Chỉnh sửa vai trò </h2>
<form method="post">
<div class="col-md-12" style="margin-top:30px;">
<div class="col-md-6" style="max-width:500px;border:1px solid
#eee;padding:20px;">
<div class="form-group">
<label for="name">Tên:</label>

12
<input type="text" value="<?= $role_data['name']; ?>"
class="form-control" name="name">
</div>
<div class="form-group">
<label for="description">Mô tả:</label>
<textarea class="form-control" name="description"
cols="30" rows="10"><?= $role_data['description']; ?></textarea>
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
<div class="panel panel-info">
<div class="panel-heading"> Chọn quyền </div>
<div class="panel-body">
<?php foreach ($permissions as $group) { ?>
<div class="form-group">
<label>
<input name="permissions[]" <?php
if(in_array($group['id'], $role_data['permission'])) echo "checked"; ?>
type="checkbox" value="<?= $group['id'] ?>">
<?= $group['name'] ?>
</label>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-info" value="Cập nhật">
<a class="btn btn-default" href="roles.php"> Hủy </a>
</div>
</form>
Tiếp theo thực hiện câu lệnh truy vấn sau trong thẻ <?php ?> ở phần đầu file
để lấy dữ liệu từ bảng permissions:
// Lấy tất cả quyền đổ ra checkbox
$sql_pms = "SELECT * FROM permissions";
$query_pms = mysqli_query($connect, $sql_pms);
$num_rows_pms = mysqli_num_rows($query_pms);
$permissions = array();
if ($num_rows_pms > 0) {
while ($row_pms = mysqli_fetch_array($query_pms)) {
$permissions[] = [
'id' => $row_pms['id'], 'name' => $row_pms['name']
];
}
}
Sau khi lấy tất cả các quyền, thực hiện câu lệnh truy vấn sau để lấy thông tin
cũ vai trò để chỉnh sửa:
if (isset($_GET['id'])) {
$id = $_GET['id'];

13
$query_role = mysqli_query($connect, "SELECT * FROM
roles LEFT JOIN role_has_permissions ON roles.id =
role_has_permissions.role_id WHERE roles.id = '$id'");
$role_data = array();
while ( $data = mysqli_fetch_array($query_role) ) {
$role_data['name'] = $data['name'];
$role_data['description'] = $data['description'];
$role_data['permission'][] = $data['permission_id'];
}
}
Tiếp theo, thực hiện kiểm tra khi người dùng click button “Cập nhật”:
if (isset($_POST['name'])) {
$name = $_POST['name'];
$description = isset($_POST['description']) ?
$_POST['description'] : null;
$in_permissions = isset($_POST['permissions']) ?
$_POST['permissions'] : [];

$name = trim($name);
$description = trim($description);

// Kiểm tra Vai trò đã có hay chưa?


if (mysqli_num_rows(mysqli_query($connect, "SELECT name FROM roles
WHERE name = '$name' AND id <> '$id'")) > 0) {
header('Location: ' . $_SERVER['HTTP_REFERER']); // return
exit;
}

$role_id = false;// tạo biến role_id


$sql = "UPDATE roles SET name = '{$name}', description =
'{$description}', updated_at = '{$date}' WHERE id = '$id'";
$update = mysqli_query($connect, $sql);

if ($update) {
$role_id = $id;
if (count($in_permissions) > 0) {
$remove = mysqli_query($connect, "DELETE FROM
role_has_permissions WHERE role_id = '$role_id'");
foreach ($in_permissions as $pms_id) {
$update_rl_has_pms = mysqli_query($connect, "INSERT INTO
role_has_permissions(permission_id,role_id) VALUE
('{$pms_id}','{$role_id}')");
}
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
else {
header('Location: ' . $_SERVER['HTTP_REFERER']); //return back
exit;
}
}
 Bước 11: Tạo file delete-role.php để thực hiện xóa vai trò

14
Sử dụng đoạn code sau để thực hiện xóa vai trò khi người dùng click vào
button “Xóa vai trò”:
if (isset($_GET['id']))
{
$id = $_GET['id'];
$query = mysqli_query($connect, $sql);
if ($query) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
else {
header('Location: ' . $_SERVER['HTTP_REFERER']); //
return back
exit;
}
}
 Bước 12: Tạo file add-user.php để thêm mới user
Tạo form thêm user như sau:

Hình 8. Form thêm mới user


Thực hiện đoạn code sau để tạo form thêm mới:
<div class="panel" style="box-shadow: none;">
<h2 style="text-align: center;"> Thêm mới thành viên </h2>
<form class="form_add_user" method="post" action="?page=dang-ky">
<div class="form-group">
<input type="text" id="login" class="form-control"
name="name" placeholder="Tên tài khoản">
</div>
<div class="form-group">
<input type="email" id="login" class="form-control"
name="email" placeholder="Email">
</div>

15
<div class="form-group">
<input type="password" id="password" class="form-
control" name="password" placeholder="Mật khẩu">
</div>
<div class="form-group">
<input type="submit" class="btn btn-sm btn-warning"
value="Thêm thành viên">
</div>
</form>
</div>
<style>
.form_add_user {
max-width: 500px;
margin: 0 auto;
border: 1px solid #eee;
border-radius: 3px;
padding: 20px;
margin-top: 50px;
}
</style>
Thực hiện câu lệnh sau trong thẻ <?php ?> ở phần đầu file để kiểm tra khi
người dùng click button “Thêm thành viên” và truy vấn insert dữ liệu:
if (isset($_POST['name']) && isset($_POST['email']) &&
isset($_POST['password'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$password = md5($password); // Mã hóa md5 mật khẩu
$sql = "INSERT INTO users(name, email, password, created_at) VALUE
('{$name}','{$email}','{$password}','{$created_at}')"; // Tạo
Query SQL
$insert = mysqli_query($connect, $sql); // Lưu Thông tin đăng ký
vào bảng users
if ($insert) // nếu lưu thành công
{
header('Location: ' . '?page=dang-nhap'); // return redirect về
login
exit;
}
else // nếu thất bại
{
header('Location: ' . $_SERVER['HTTP_REFERER']); // return back
exit;
}
}
 Bước 13: Tạo file users.php trong thư mục phanquyen để thực hiện hiển
thị danh sách các user có trong database:
Tạo danh sách hiển thị user như sau:

16
Hình 9. Bảng hiển thị danh sách user
Thực hiện đoạn code sau để tạo danh sách user:
<div class="panel" style="box-shadow: none;">
<h2> Quản lý thành viên </h2>
<a class="btn btn-sm btn-primary" href="add-user.php"> Thêm thành viên
</a>
<table class="table table-bordered" style="margin-top:
60px;border:1px solid #eee; width: 800px">
<thead>
<tr>
<th>ID</th>
<th>Tên</th>
<th>Email</th>
<th>Vai trò</th>
<th style="width:50px">Chọn</th>
</tr>
</thead>
<tbody>
<?php foreach ($list_user as $item) { ?>
<tr class="item__user" data-name="<?=
$item['name']; ?>">
<td><?= $item['id']; ?></td>
<td><?= $item['name']; ?></td>
<td><?= $item['email']; ?></td>
<td><?= $item['role_name']; ?></td>
<td style="text-align:center">
<form action="user-role.php" method="post">
<input type="hidden"
name="role_group" value="<?= $item['role_id']; ?>">
<input type="hidden"
name="user_name" value="<?=
$item['name'].'+'.$item['id'];; ?>">
<button class="btn btn-sm btn-
info"> Chọn vai trò </button>
</form>
</td>
</tr>

17
</tbody>
</table>
</div>
Thực hiện câu lệnh sau trong thẻ <?php ?> ở phần đầu file để lấy dữ liệu từ
trong database:
$sql = "SELECT
GROUP_CONCAT(roles.name) as name,
GROUP_CONCAT(roles.id) as role_id,users.id AS user_id,
email,users.NAME AS user_name
FROM users
LEFT JOIN user_has_roles ON users.id =
user_has_roles.user_id
LEFT JOIN roles ON roles.id = user_has_roles.role_id
GROUP BY users.id";
$query = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($query); // đếm số bản ghi
$list_user = array(); // tạo mảng chứa dữ liệu trả về
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($query)) {
$list_user[] = [
'id' => $row['user_id'],
'name' => $row['user_name'],
'email' => $row['email'],
'role_id' => $row['role_id'],
'role_name' => ($row['name']) ? $row['name'] : 'Chưa có vai
trò'
];
}
}
 Bước 14: Tạo file user-role.php để thực hiện gán quyền cho user:
Tạo form gán quyền như sau:

Hình 10. Form gán vai trò cho user


Thực hiện tạo form:
18
<div class="panel" style="box-shadow: none;">
<h2> Chọn vai trò </h2>
<div style="padding:20px;border:1px solid #eee" class="col-md-12">
<form action="user-role.php" method="post" class="col-md-12">
<input type="hidden" name="change_role" value="1">
<input type="hidden" name="us_id" value="<?= $us_id ?>">
<div class="col-md-3">
<div class="panel panel-info">
<div class="panel-heading">Thành viên</div>
<div class="panel-body">
<ul style="padding: 10px 20px;">
<li style="line-height: 25px;">
<p><?= $us_name; ?></p>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-info">
<div class="panel-heading">Vai trò</div>
<div class="panel-body">
<?php foreach ($roles as $item) { ?>
<div class="form-group">
<input name="role[]" <?php
if(in_array($item['id'], $role_group)) echo
'checked'; ?> value="<?= $item['id']; ?>"
type="checkbox"> <?= $item['name'] ?>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="clearfix"></div>
<a class="btn btn-sm btn-default" href="users.php"> Hủy
</a>
<button class="btn btn-sm btn-warning"> Lưu </button>
</form>
</div>
</div>
Thực hiện truy vấn sau trong thẻ <?php ?> ở phần đầu file lấy dữ liệu trong
các vai trò trong database:
$sql_roles = "SELECT * FROM roles WHERE deleted_at IS NULL";
$query_roles = mysqli_query($connect, $sql_roles);
$num_rows_roles = mysqli_num_rows($query_roles);
$roles = array();
if ($num_rows_roles > 0) {
while ($row = mysqli_fetch_array($query_roles)) {
$roles[] = [
'id' => $row['id'],
'name' => $row['name'],
];
}
}

19
Sau đó, thực hiện kiểm tra khi người dùng click button “Lưu”:
if (isset($_POST['user_name'])) {
$user_name = explode('+',$_POST['user_name']);
$us_name = $user_name[0];
$us_id = $user_name[1];
}

if (isset($_POST['change_role']) && $_POST['change_role'] == 1) {


$us_id = $_POST['us_id'];
$role_checked = $_POST['role'];
$remove = mysqli_query($connect, "DELETE FROM
user_has_roles WHERE user_id = '$us_id'");
foreach ($role_checked as $rl_checked) {
mysqli_query($connect, "INSERT INTO
user_has_roles(role_id,user_id) VALUE
('{$rl_checked}','{$us_id}')");
}
header('Location: ' . 'users.php');
}
else {
if (isset($_POST['role_group'])) {
$role_group = explode(',',$_POST['role_group']);
}
else {
header('Location: ' . 'users.php'); // quay về trang
users
exit;
}
}
 Bước 15: Tạo file index.php trong thư mục phanquyen để thực hiện kiểm
tra việc phân quyền:
Thực hiện câu lệnh truy vấn sau trong thẻ <?php ?> ở phần đầu file lấy dữ
liệu từ bảng user_has_role để kiểm tra:
$auth_id = $_SESSION['auth_user']['id']; // lấy session về
$sql = "SELECT
GROUP_CONCAT(permissions.name) as permission_name,
user_has_roles.user_id,
roles.name as role_name,
roles.id as role_id
FROM user_has_roles
LEFT JOIN roles ON roles.id = user_has_roles.role_id
LEFT JOIN role_has_permissions ON role_has_permissions.role_id =
roles.id
LEFT JOIN permissions ON role_has_permissions.permission_id =
permissions.id
WHERE user_has_roles.user_id = '$auth_id'
GROUP BY roles.id";
$query = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($query);

$data = array();
if ($num_rows > 0) {
while ($row = mysqli_fetch_array($query)) {

20
$data[] = [
'role_name' => $row['role_name'],
'permissions' => explode(',',
$row['permission_name'])
];
}
}
Tạo giao diện kiểm tra:

Hình 11. . Kiểm tra vai trò và quyền của user


Thực hiện giao diện và kiểm tra vai trò:
<h1 style="font-size: 20px;">Xin chào <?= $_SESSION['auth_user']['name']
?>!</h1> // hiển thị tên người dùng
<div class="panel" style="box-shadow: none;">
<h2> Bạn có thể thực hiện: </h2>
<div class="box__role_permission col-md-12" style="padding-top:30px;">
<?php if(count($data) > 0) { ?>
<?php foreach ($data['role_name'] as $key => $item) { ?>
<div class="col-md-12">
<div class="panel panel-info">
<div class="panel-heading"> <?= $key; ?> </div>
<div class="panel-body">
<?php foreach ($item['permission_group'] as $item_pms) { ?>
<div class="col-md-3">
<h4><?= $item_pms['type']; ?>:</h4>
<ul>
<?php foreach ($item_pms['permissions'] as $pe) { ?>

21
<li><?= $pe; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php } else { ?>
<p> Bạn không có vai trò nào trong hệ thống </p>
<?php } ?>
</div>
Nhiệm vụ 3. Thực hiện phân quyền người dùng theo vai trò
 Bước 1: Tạo danh sách quyền
Tạo danh sách các quyền như dưới đây:
- Thêm mới sản phẩm
- Xem danh sách sản phẩm
- Sửa sản phẩm
- Xóa sản phẩm
- Đăng tin tức
- Xem danh sách tin tức
- Xóa tin tức
- Sửa tin tức
- Xem danh sách user
- Xóa user
- Sửa user
- Thêm user
- Phân quyền theo vai trò
- Xem danh sách đơn hàng
- Xóa đơn hàng
- Tạo đơn hàng
 Bước 2: Tạo vai trò
- Tạo vai trò Admin: Admin có tất cả các quyền trong hệ thống
- Tạo vai trò Biên tập viên với tất cả các quyền sau:
+ Đăng tin tức
+ Xem danh sách tin tức
+ Xóa tin tức
+ Sửa tin tức
- Tạo vai trò Nhân viên bán hàng với các quyền sau:
+ Thêm mới sản phẩm
+ Xem danh sách sản phẩm
+ Sửa sản phẩm
22
+Xóa sản phẩm
 Bước 3: Tạo danh sách user
- Tạo user1 với vai trò là Admin
- Tạo user2 với vai trò là Biên tập viên
- Tạo user3 với vai trò là Nhân viên bán hàng
- Tạo user4 với vai trò là Biên tập viên, Nhân viên bán hàng
- Tạo user5 không có vai trò nào trong hệ thống
 Bước 4: Kiểm tra phân quyền
Đăng nhập tài khoản mỗi user và kiểm tra vai trò với các quyền tương ứng
với vai trò đó

23

You might also like