DirectoryTree / LdapRecord-Laravel

Multi-domain LDAP Authentication & Management for Laravel.
https://ldaprecord.com/docs/laravel/v3
MIT License
483 stars 51 forks source link

[Bug] Database user created even after rule failure #657

Closed extraric closed 1 month ago

extraric commented 1 month ago

Environment:

Hello!

I am facing the following problem: even if authentication rules are return false (user is not in the required group), user object created in the database, and attributes synced.

rule:

class OnlyQuentinUsers extends Rule
{
    public function isValid()
    {
        return $this->user->groups()->contains([
        'Quentin_EO',
        'Quentin_kti_diszpecser',
        'QkApp_admin',
        'QkApp_betekinto'
    ]);
    }
}

auth.php:

'providers' => [
    'fkf' => [
        'driver' => 'ldap',
        'model' => App\Ldap\FKFUser::class,
        'rules' => [
            App\Ldap\Rules\OnlyQuentinUsers::class,
        ],
        'database' => [
            'model' => App\User::class,
            'sync_passwords' => true,
            'sync_attributes' => [
                'name' => 'cn',
                'username' => 'samaccountname',
                'email' => 'mail',
                \App\Ldap\GroupHandler::class,
            ],
            'sync_existing' => [
                'username' => 'samaccountname',
            ],
        ],
    ],
    ...
extraric commented 1 month ago

Ok, I may find my own mistake: in the GroupHandler class where I map AD groups to roles in application I had a $user->save(); line. I thought its required but apparently not, also I thought it never reaches attributes sync lines if auth failed by rules.

class GroupHandler
{
    public function handle(LdapUser $ldap, User $user)
    {
        $groups = $ldap->groups()
                ->orFilter(function ($q) {
                    $q->whereStartsWith('cn', 'QkApp_')
                      ->whereStartsWith('cn', 'Quentin_');
                })
                ->recursive()
                ->get()
                ->pluck('cn')->flatten()->all();

        $roles = Role::all();
        $userrole = [];
        $mainrole = '-kilépett-';
        foreach ($roles as $role) {
            if (in_array($role->name, $groups)){
                $userrole[] = $role;
            }
        }

        $user->roles()->detach();
        foreach ($userrole as $role) {
            $user->assignRole($role);
            switch ($role->name){
                case 'Quentin_EO' : $mainrole = 'Értékesítő'; break;
                case 'Quentin_kti_diszpecser' : $mainrole = 'Diszpécser'; break;
            }
        }
        $user->mainrole = $mainrole;

        //$user->save(); <-- mistake

        $user->last_login = Carbon::now();
    }
}