From bc1380ca89b157e9721608be8e707e9809124ea0 Mon Sep 17 00:00:00 2001 From: Alex Tselegidis Date: Sat, 23 Oct 2021 19:19:21 +0200 Subject: [PATCH] Added helper file with permission related functions. --- application/helpers/permission_helper.php | 77 +++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 application/helpers/permission_helper.php diff --git a/application/helpers/permission_helper.php b/application/helpers/permission_helper.php new file mode 100644 index 00000000..2ed025b1 --- /dev/null +++ b/application/helpers/permission_helper.php @@ -0,0 +1,77 @@ + + * @copyright Copyright (c) 2013 - 2020, Alex Tselegidis + * @license http://opensource.org/licenses/GPL-3.0 - GPLv3 + * @link http://easyappointments.org + * @since v1.5.0 + * ---------------------------------------------------------------------------- */ + +if ( ! function_exists('can')) +{ + /** + * Check if the currently logged-in user can perform an action + * + * Example: + * + * if (can('edit', 'appointments') === FALSE) abort(403); + * + * @param string $action + * @param string $resource + * @param int|null $user_id + * + * @return bool + */ + function can(string $action, string $resource, int $user_id = NULL): bool + { + /** @var EA_Controller $CI */ + $CI = &get_instance(); + + $CI->load->model('roles_model'); + $CI->load->model('user_model'); + + if (empty($user_id)) + { + $role_slug = session('role_slug'); + } + else + { + $user = $CI->user_model->get_user($user_id); + $role_slug = $CI->roles_model->value('slug', $user['id_roles']); + } + + if (empty($role_slug)) + { + return FALSE; + } + + $permissions = $CI->roles_model->get_privileges($role_slug); + + return $permissions[$resource][$action]; + } +} + +if ( ! function_exists('cannot')) +{ + /** + * Check if the currently logged-in user can perform an action + * + * Example: + * + * if (cannot('edit', 'appointments')) abort(403); + * + * @param string $action + * @param string $resource + * @param int|null $user_id + * + * @return bool + */ + function cannot(string $action, string $resource, int $user_id = NULL): bool + { + return ! can($action, $resource, $user_id); + } +}