CakePHP4 - How to create multiple user login with the Authentication plugin?

1.1k Views Asked by At

There are two types of users in the application I am developing. Users (table users.sql) for frontend users and AdminUsers (table admin_users.sql) for administration.

In CakePHP3, I solved this problem as follows with AuthComponent in AppController:

public function initialize()
{
    parent::initialize();

    // ...

    //user login
    if (!empty($this->request->params['prefix']) AND
        $this->request->params['prefix'] == 'admin'
    ) {
        $this->setAdminLogin();
    }else{
        $this->setUserLogin();
        $this->Auth->allow();
    }

    // ...
}
//frontend users
public function setUserLogin()
{
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'edit'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authError' => false,
        'authenticate' => [
            'Xety/Cake3CookieAuth.Cookie' => [
                'userModel' => 'Users',
                'scope' => ['Users.active' => 1],
                'fields' => ['username' => 'email','password' => 'password'],
            ],
            'Form' => [
                'userModel' => 'Users',
                'scope' => ['Users.active' => 1],
                'fields' => ['username' => 'email','password' => 'password'],
                'passwordHasher' => [
                    'className' => 'Fallback',
                    'hashers' => ['Default']
                ]
            ],
        ],
        'storage' =>  ['className' => 'Session', 'key' => 'Auth.User']
    ]);
}
//admin users
public function setAdminLogin()
{
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'loginAction' => [
            'controller' => 'AdminUsers',
            'action' => 'login',
        ],
        'loginRedirect' => [
            'controller' => 'AdminHelps',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'AdminUsers',
            'action' => 'login'
        ],
        'authError' => false,
        'authenticate' => [
            'Form' => [
                'userModel' => 'AdminUsers',
                'scope' => ['AdminUsers.active' => 1],
                'fields' => ['username' => 'email','password' => 'password'],
                'passwordHasher' => [
                    'className' => 'Fallback',
                    'hashers' => ['Default']
                ]
            ],
        ],
        'storage' =>  ['className' => 'Session', 'key' => 'Auth.AdminUser']
    ]);
}

How can I do the same thing in CakePHP4 version with Authentication plugin? How can I create multiple user login?

0

There are 0 best solutions below