cakephp5 登录

Title cakephp5 登录
Framework CakePHP5
User wy8817399@vip.qq.com
Id 5
Created 1/7/26, 7:30 AM
Modified 1/7/26, 7:38 AM
Published Yes
Content

1、建表

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    created DATETIME,
    modified DATETIME
);

 

2、在有composer.json的目录下(通常为根目录)执行

composer require cakephp/authentication

 

3、在当前cake项目的根目录下执行

bin/cake bake all users

 

4、在 src/Model/Entity/User.php 中 添加一句话和一个方法使密码加密

use Authentication\PasswordHasher\DefaultPasswordHasher;
protected function _setPassword(string $password) : ?string
{
	if (strlen($password) > 0) {
		return (new DefaultPasswordHasher())->hash($password);
	}
	return null;
}

 

5、修改src/Application.php文件

//添加导入
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
use Cake\Routing\Router;
use Psr\Http\Message\ServerRequestInterface;

 

//添加接口实现implements AuthenticationServiceProviderInterface
class Application extends BaseApplication implements AuthenticationServiceProviderInterface

 

//修改方法,在middleware方法中 找到->add(new BodyParserMiddleware())这句话 在他下面添加一句
->add(new AuthenticationMiddleware($this))

 

//添加方法
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
	$authenticationService = new AuthenticationService([
		'unauthenticatedRedirect' => Router::url('/users/login'),
		'queryParam' => 'redirect',
	]);

	// Load the authenticators, you want session first
	$authenticationService->loadAuthenticator('Authentication.Session');
	// Configure form data check to pick email and password
	$authenticationService->loadAuthenticator('Authentication.Form', [
		'fields' => [
			'username' => 'email',
			'password' => 'password',
		],
		'loginUrl' => Router::url('/users/login'),
		'identifier' => [
			'Authentication.Password' => [
				'fields' => [
					'username' => 'email',
					'password' => 'password',
				],
			],
		],
	]);

	return $authenticationService;
}

 

6、在src/Controller/AppController.php中添加

$this->loadComponent('Authentication.Authentication');

 

7、在 UsersController 中添加

public function login()
{
    $this->request->allowMethod(['get', 'post']);
    $result = $this->Authentication->getResult();
    // regardless of POST or GET, redirect if user is logged in
    if ($result && $result->isValid()) {
        // redirect to /articles after login success
        $redirect = $this->request->getQuery('redirect', [
            'controller' => 'Articles',
            'action' => 'index',
        ]);

        return $this->redirect($redirect);
    }
    // display error if user submitted and authentication failed
    if ($this->request->is('post') && !$result->isValid()) {
        $this->Flash->error(__('Invalid username or password'));
    }
}


public function beforeFilter(\Cake\Event\EventInterface $event): void
{
    parent::beforeFilter($event);
    // Configure the login action to not require authentication, preventing
    // the infinite redirect loop issue
    $this->Authentication->addUnauthenticatedActions(['login']);
}

 

8、创建/templates/Users/login.php

<div class="users form">
    <?= $this->Flash->render() ?>
    <h3>Login</h3>
    <?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username and password') ?></legend>
        <?= $this->Form->control('email', ['required' => true]) ?>
        <?= $this->Form->control('password', ['required' => true]) ?>
    </fieldset>
    <?= $this->Form->submit(__('Login')); ?>
    <?= $this->Form->end() ?>

    <?= $this->Html->link("Add User", ['action' => 'add']) ?>
</div>

 

9、在src/Controller/AppController.php中添加以下代码,以开放对应页面不用登录即可访问

public function beforeFilter(\Cake\Event\EventInterface $event): void
{
    parent::beforeFilter($event);
    // for all controllers in our application, make index and view
    // actions public, skipping the authentication check
    $this->Authentication->addUnauthenticatedActions(['index', 'view']);
}

 

10、注销,在src/Controller/UsersController.php添加

public function logout()
{
    $result = $this->Authentication->getResult();
    // regardless of POST or GET, redirect if user is logged in
    if ($result && $result->isValid()) {
        $this->Authentication->logout();

        return $this->redirect(['controller' => 'Users', 'action' => 'login']);
    }
}