Sometimes we need to have permission from database.
Suppose that uor tables look like this:
guard_permission:
_attributes: { phpName: GuardPermission }
code: { type: char, size: 150, required: true, primaryKey: true }
name: { type: varchar, size: 100, required: true }
guard_group:
_attributes: { phpName: GuardGroup }
code: { type: char, size: 150, required: true, primaryKey: true }
name: { type: varchar, size: 100, required: true }
description: { type: longvarchar, required: false }
is_default: { type: boolean, required: true, default: false }
guard_group_permission:
_attributes: { phpName: GuardGroupPermission }
id: ~
group_code: { type: char, size: 150, required: true, foreignTable: guard_group, foreignReference: code, onDelete: cascade }
permission_code: { type: char, size: 150, required: true, foreignTable: guard_permission, foreignReference: code, onDelete: cascade }
guard_user:
_attributes: { phpName: GuardUser }
id: ~
is_email_verified: { type: boolean, required: true, default: false }
guard_user_group:
_attributes: { phpName: GuardUserGroup }
id: ~
user_id: { type: integer, required: true, foreignTable: guard_user, foreignReference: id, onDelete: cascade }
group_code: { type: char, size: 150, required: true, foreignTable: guard_group, foreignReference: code, onDelete: cascade }
To check permissions from database, we just need to override hasCredential method in apps/app_name/lib/MyUser.php. My data in database were 'module_name-action_name' e.g (permisssion_code: home-index), so i have overwritten parmission name to look like data from database.
/**
* Overridden method to use data from DB
*
* @param string permission name
*
* @return boolean true if the user has credential
*/
public function hasCredential($permission_name)
{
if(!$this->isAuthenticated())
{
return false;
}
$GuardUser = $this->getGuardUser();
$c = new Criteria();
$c->add(GuardUserGroupPeer::USER_ID, $GuardUser->getId());
$UserGroup = GuardUserGroupPeer::doSelectOne($c);
$Group = $UserGroup->getGuardGroup();
$permissions = $Group->getGuardGroupPermissions();
$permission_names = array();
foreach($permissions as $permission)
{
$permission_names[] = $permission->getPermissionCode();
}
$moduleName = sfContext::getInstance()->getModuleName();
$actionName = sfContext::getInstance()->getActionName();
$permission_name = $moduleName . '-' . $actionName;
return (in_array($permission_name, $permission_names)) ? true : false;
}
Now all we need is to fill out the data in database, and this should work.