我正在cakephp 4中工作。我已经为登录身份验证设置了模型('Representatives'),但它正在使用另一个带有名称users的模型进行身份验证。我已经上传了AppController.php文件以及EmployeesController.php文件,我在其中定义了方法(action)。
在控制器/应用控制器. php中
class AppController extends Controller
{
public function initialize(): void
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
"authenticate" => [
"Form" => [
"fields" => [
"username" => "email",
"password" => "password"
],
"userModel" => "Representatives"
]
],
"loginAction" => [
"controller" => "Employees",
"action" => "login"
],
"loginRedirect" => [
"controller" => "Employees",
"action" => "home"
],
"logoutRedirect" => [
"controller" => "Employees",
"action" => "login"
]
]);
}
在员工控制器中:
class EmployeesController extends AppController
{
public function initialize(): void
{
parent::initialize();
$this->loadModel("Employees");
$this->loadModel("Representatives");
$this->loadComponent('Flash');
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
// echo "<pre>"; print_r($user); die;
if ($user) {
$this->Auth->setUser($user);
echo "<pre>"; print_r($user); exit();
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'));
}
}
$this->viewBuilder()->setLayout('home');
$this->set("title", "Login");
}
在模型/实体/代表性. php中
<?php
namespace App\Model\Entity;
use Authentication\PasswordHasher\DefaultPasswordHasher;
use Cake\ORM\Entity;
class Representative extends Entity
{
protected $_accessible = [
'id' => false,
'name' => true,
'role' => true,
'email' => true,
'password' => true,
'phone' => true,
'slug' => false
];
protected function _setPassword(string $password) : ?string
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher())->hash($password);
}
}
}
在模型/表格/代表性表格. php中
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Utility\Text;
use Cake\Event\EventInterface;
class RepresentativesTable extends Table
{
public function initialize(array $config) :void
{
$this->setTable("newusers");
}
public function beforeSave(EventInterface $event, $entity, $options)
{
if ($entity->isNew() && !$entity->slug) {
$sluggedTitle = Text ::slug($entity->name);
$entity->slug = substr($sluggedTitle, 0, 191);
}
}
}
2条答案
按热度按时间vlurs2pr1#
默认情况下,cakephp使用用户模型进行身份验证。
您可以在此video中找到使用另一个路由进行身份验证的示例
在本例中,它的定义如下:
pengsaosao2#
虽然视频翻译很糟糕,但我能够按照视频中的例子操作,重要的部分是添加“解析器”,让Cakephp找到正确的表。
这确实造成了另一个问题,$this-〉Identiy-〉get失败,我希望将添加一个解析器,使其也能按预期工作。
谢谢你!