I'm trying to write my own RBAC module in Kohana. I don't want to use an existing module, I just want to do this to learn.
My tables are: users, roles, permission and users_roles, roles_permissions (because of the many to many relations between users<->roles, and roles<->permissions);
My User model:
class Model_User extends ORM {
protected $_primary_key = 'user_id';
protected $_has_many = array(
'roles' => array(
'model' => 'role',
'through' => 'users_roles',
),
);
}
My Role Model:
class Model_Role extends ORM {
protected $_primary_key = 'role_id';
protected $_has_many = array(
'users' => array(
'model' => 'user',
'through' => 'users_roles',
),
'permissions' => array(
'model' => 'permission',
'through' => 'roles_permissions',
),
);
}
and my Permission model:
class Model_Permission extends ORM {
protected $_primary_key = 'permission_id';
protected $_has_many = array(
'roles' => array(
'model' => 'role',
'through' => 'roles_permissions',
),
);
}
I create users:
$user = ORM::factory('user');
$user->username = 'johndoe';
$user->email = '[email protected]';
//etc
$user.save();
I create roles:
$author = ORM::factory('role');
$author->name = 'author';
$author->save();
I create permissions:
$read = ORM::factory('permission');
$read->name = 'read';
$read->description = 'can read posts';
$read->save();
$write = ORM::factory('permission');
$write->name = 'write';
$write->description = 'can write posts';
$write->save();
I add roles to users:
$user->add('roles', $author);
I add permissions to roles:
$author->add('permissions', $read);
$author->add('permissions', $write);
and everything is working fine.
But, my question is how to check if a user has a given permission: in this case how to check if johndoe has permission to write a post?
Thank you for your help!