我构建了一个应用程序,该应用程序使用Authentication插件进行正常登录,并在控制器中进行其他形式的登录。在cakephp3中,我们可以使用$this->Auth()->login, $this->Auth()->setUser,等等。但是在cakephp4的认证插件没有$this->Authentication->login/setUser。问题是我该怎么做?
我在控制器中获取用户,我没有任何方法登录该用户。
我想知道你们中是否有人遇到过这个问题
这是我的认证服务:
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService();
// Define where users should be redirected to when they are not authenticated
$service->setConfig([
'unauthenticatedRedirect' => Router::url([
'prefix' => false,
'plugin' => null,
'controller' => 'Users',
'action' => 'login',
]),
'queryParam' => 'redirect',
]);
$fields = [
IdentifierInterface::CREDENTIAL_USERNAME => 'email',
IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
];
// Load the authenticators. Session should be first.
$service->loadAuthenticator('Authentication.Session');
if ($request->getParam('action') == 'googleLogin') {
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => Router::url([
'prefix' => false,
'plugin' => null,
'controller' => 'Users',
'action' => 'googleLogin',
]),
]);
} else {
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => Router::url([
'prefix' => false,
'plugin' => null,
'controller' => 'Users',
'action' => 'login',
]),
]);
}
// Load identifiers
$service->loadIdentifier('Authentication.Password', compact('fields'));
return $service;
}
这是控制器
$this->Authorization->skipAuthorization();
$data = $this->request->getData();
$email = $data['email'];
$repository = new UserRepository($this->Users);
$user = $repository->findUserByEmail($email);
$response = $this->response;
if (!empty($user)) {
$response->withStatus(201);
return $response;
} else {
$user = $this->Users->newEmptyEntity();
$dataUser['username'] = $email;
$dataUser['email'] = $email;
$dataUser['password'] = 'esquemaPerfecto';
$dataUser['role'] = 'cliente';
$user = $this->Users->patchEntity($user, $dataUser);
if ($this->Users->save($user)) {
$this->Authentication->setUser($user);
$sendEmail = new EmailHelper($dataUser['email'], 'Vehiculos de Primera mano Registro', 'Usted se ha registrado con exito en la pagina de Vehiculos de Primera Mano y su contraseña es ' . $dataUser['passwords']);
$sendEmail->send();
$response->withStatus(200);
return $response;
}
}
$response->withStatus(400);
return $response;
}
欢迎大家出谋划策
根据迁移从AuthComponent文档部分
任何你调用AuthComponent::setUser()的地方,你现在应该使用setIdentity():
// Assume you need to read a user by access token
$user = $this->Users->find('byToken', ['token' => $token])->first();
// Persist the user into configured authenticators.
$this->Authentication->setIdentity($user);