I found this great code snippet that works wonderfully during circumstances that change a user’s credentials during that user’s session. The hasCredential() method defaults to looking at the database rather than the user’s session – which meets my needs perfectly (as a user’s credentials are often changed programmatically during a user’s session). So I really need to keep this functionality.
However, for circumstances that have multiple credentials, either an OR circumstance: [[A, B]] or an AND circumstance: [A, B] the code snippet fails as it only checks for the one instance and does not read the yaml security file for AND OR instances.
I’m looking for help with how to tweak the code snippet to take into account AND OR yaml credential permissions. Here’s the code snippet:
public function hasCredential($permission_name)
{
//this overrides the default action (hasCredential) and instead of checking
//the user's session, it now checks the database directly.
if (!$this->isAuthenticated()) {
return false;
}
$gu = $this->getGuardUser();
$groups = $gu->getGroups();
$permissions = $gu->getPermissions();
$permission_names = array();
foreach($permissions as $permission) {
$permission_names[] = $permission->getName();
}
foreach($groups as $group) {
$group_permissions = $group->getPermissions();
foreach($group_permissions as $group_permission) {
$permission_names = array_merge($permission_names, array($group_permission->getName()));
}
}
$permission_names = array_unique($permission_names);
return (in_array($permission_name, $permission_names)) ? true : false;
}
EDIT:
I think I need to merge the above code with the original hasCredential() below but I’m struggling with the logic:
public function hasCredential($credentials, $useAnd = true)
{
if (null === $this->credentials)
{
return false;
}
if (!is_array($credentials))
{
return in_array($credentials, $this->credentials);
}
// now we assume that $credentials is an array
$test = false;
foreach ($credentials as $credential)
{
// recursively check the credential with a switched AND/OR mode
$test = $this->hasCredential($credential, $useAnd ? false : true);
if ($useAnd)
{
$test = $test ? false : true;
}
if ($test) // either passed one in OR mode or failed one in AND mode
{
break; // the matter is settled
}
}
if ($useAnd) // in AND mode we succeed if $test is false
{
$test = $test ? false : true;
}
return $test;
}
I think I found the correct implementation of the hasCredential method that overrides the original code found in the sfGuardSecurityUser Class. The code asks the underlying GuardUser model to reload all the permissions and groups from the database and adds theses credentials to the SecurityUser object before checking the credentials.