class MY_Controller extends MX_Controller{ //presumes you use hmvc
// this is the main controller, it feeds data to its child(extended) controllers
// use the protected keyword over the private keyword for methods and vars
protected $user, $permissions=array(), $group;
// define some permission constants to check with MY_Controller scope including
// children(extended)
const PERM_READ = 'read';
const PERM_EDIT = 'edit';
const PERM_DELETE = 'delete';
// an alternative is to use bit and bitewise operations
// tutorial here http://codingrecipes.com/how-to-write-a-permission-system-using-bits-and-bitwise-operations-in-php
public function __construct(){
parent::__construct();
//check the session data and assign a user to the user var
$this->user = ($this->session->userdata('user_id'))
? User::find($this->session->userdata('user_id'))
: NULL;
if($this->user !== NULL)
{
$this->_assign_group();
$this->_assign_permissions();
}
}
public function _assign_group(){
return $this->group = $this->user->group;
}
public function _assign_permissions(){
// permissions are stored as json object in the database
// this works fine as we dont need to do a serach on the object
// we simply store and return
// {["read", "update", "delete"]}
return $this->permissions = (array)json_decode($this->user->permissions);
}
public function _can_read(){
return (bool) (in_array(self::PERM_READ, $this->permissions));
}
public function _can_edit(){
return (bool) (in_array(self::PERM_EDIT, $this->permissions));
}
public function _can_delete(){
return (bool) (in_array(self::PERM_DELETE, $this->permissions));
}
}
-
class some_module extends MY_Controller{
public function __construct(){
parent::__construct();
}
public function module_method(){
if($this->group === 'AUTHOR' AND $this->can_edit())
{
// you have access to edit this modules's content
}
}
}
В основном проверяется вход в сеанс и назначается пользователю $this->user
Затем, когда пользователь назначен, он назначает его группу и разрешения.Теперь вы можете легко проверить эти переменные на соответствие строк / массивов
Если вам нужно выполнить проверку внутри своего представления, вы можете сделать следующее
<?php if(Modules::run('class/has_permissions_to_run_this')): ?>
<p>Good to load a view or print a form</p>
<?php else: ?>
<p>You need the correct credentials to view/edit this</p>
<?php endif;?>
Для администраторов
class Admin extends MY_Controller{
public function __construct() {
parent::__construct();
if( ! $this->_check_admin_credentials())
{
redirect('login');
}
}
public function _check_admin_credentials(){
return (bool)(
$this->_can_read()
AND $this->_can_edit()
AND $this->_can_delete()
AND $this->group === 'admin'
);
}
-
public function for_super_user_only(){
// if you need to block specific sections such as
// global settings or accounting from other admins
// run the check inside the method itself
if($this->group == 'super')
{
//continue;
}
else
{
show_404();
//or display error view
}
}
Ваша структура таблицы может выглядеть следующим образом
create table `users`(
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
`group` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`firstname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`alias` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`last_ip` varchar(16) COLLATE utf8_unicode_ci NOT NULL,
`permissions` varchar(250) NOT NULL DEFAULT '["read", "update", "delete"]',
`active` boolean NOT NULL DEFAULT 0,
`activation_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`password_token` text COLLATE utf8_unicode_ci DEFAULT NULL,
`last_login` datetime NOT NULL,
`created_at` datetime NOT NULL,
UNIQUE( `email` ),
UNIQUE( `alias` )
) ENGINE=InnoDB CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registered Users';
- добавить индексы в строки, которые будутискать, например, идентификатор, адрес электронной почты, псевдоним
ALTER TABLE `users` ADD INDEX( `id` );
ALTER TABLE `users` ADD INDEX( `email` );
ALTER TABLE `users` ADD INDEX( `alias` );