-
This question is somewhat related to #566 . This is my wanted setup:
In config/auth.php I have the following configuration:
My intention with Someone who has similar setup who can share how this is solved with Laravel and Spatie Permissions? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Groups can be mapped to roles by creating a handler for that. I called it RoleHandler and added it to 'providers' => [
'users' => [
'driver' => 'ldap',
'model' => \App\Ldap\User::class,
'database' => [
'model' => App\Models\User::class,
'sync_passwords' => false,
'sync_attributes' => [
'name' => 'cn',
'email' => 'mail',
'userid' => 'samaccountname',
\App\Ldap\RoleHandler::class,
],
'sync_existing' => [
'email' => 'mail',
],
],
'rules' => [ App\Ldap\Rules\OnlyAppGroupMembers::class,],
],
],
namespace App\Ldap;
use App\Models\User as DatabaseUser;
use LdapRecord\Models\ActiveDirectory\User as LdapUser;
use LdapRecord\Models\ActiveDirectory\Group;
use Spatie\Permission\Models\Role;
class RoleHandler
{
public function handle(LdapUser $ldapUser, DatabaseUser $dbUser)
{
$syncAtLogin=config('appConfig.ldap_sync_at_login');
if ($syncAtLogin) { // Sync role at each login only if this is activated in .env
$groups_postfix=config('appConfig.ldap_group_postfix');
$groups=config('appConfig.ldap_groups');
$roles=config('appConfig.local_roles');
$syncRoles=[];
$userGroups=[];
$i=0;
foreach ($groups as $group) {
$ldapGroup="CN=$group,".$groups_postfix;
$role=$roles[$i];
if ($ldapUser->groups()->exists($ldapGroup)) {
$syncRoles[$i]=$role;
$userGroups[$i]=$group;
}
$i++;
}
$dbUser->syncRoles($syncRoles);
$userGoupList=implode(', ', $userGroups);
$userRoleList=implode(', ', $syncRoles);
$userId=$ldapUser->samaccountname[0];
};
}
} Notice that I here have configured the possible groups and corresponding roles in comma separated lists in .env. They should probably rather be configured in a cached table.
namespace App\Ldap\Rules;
use Illuminate\Database\Eloquent\Model as Eloquent;
use LdapRecord\Laravel\Auth\Rule;
use LdapRecord\Models\Model as LdapRecord;
use LdapRecord\Models\ActiveDirectory\Group;
class OnlyAppGroupMembers implements Rule
{
/**
* Check if the rule passes validation.
*/
public function passes(LdapRecord $user, Eloquent $model = null): bool
{
$groups_postfix=config('appConfig.ldap_group_postfix');
$pulsGroups=config('appConfig.ldap_groups');
$appUser=false;
foreach($pulsGroups as $group) {
$ldapGroup="CN=$group,".$groups_postfix;
$appUser=$user->groups()->exists($ldapGroup);
if ($pulsUser) break;
}
return $appUser;
}
} |
Beta Was this translation helpful? Give feedback.
Groups can be mapped to roles by creating a handler for that. I called it RoleHandler and added it to
config/auth.php
: