rubyan/cake3-cookieauth

一个简单的 Cake3 插件,用于使用 Cookie 验证用户。

安装次数: 10,127

依赖关系: 0

建议者: 0

安全: 0

星标: 1

关注者: 1

分支: 0

开放问题: 0

类型:cakephp-plugin

3.7.1 2018-12-20 21:17 UTC

This package is auto-updated.

Last update: 2024-09-21 20:54:05 UTC


README

一个简单的 Cake3 插件,用于使用 Cookie 验证用户。此插件基于出色的插件 Xety/Cake3-Cookieauth,但增加了允许空密码的选项。它还针对 CakePHP 3.7 进行了修复

需求

  • CakePHP 3.X

安装

运行: composer require rubyan/cake3-cookieauth:1.* 或将其添加到您的 composer.json

"require": {
	"rubyan/cake3-cookieauth": "1.*"
},

用法

在您的 config/bootstrap.php 中添加

Plugin::load('Xety/Cake3CookieAuth');

在您的 AppController

public $components = [
	'Cookie',
	'Auth' => [
		'authenticate' => [
			'Form',
			'Xety/Cake3CookieAuth.Cookie'
		]
	]
			
];

在您的 AppController 中,在 beforeFilter 动作

public function beforeFilter(Event $event) {
	//Automaticaly Login.
	if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {

		$user = $this->Auth->identify();
		if ($user) {
			$this->Auth->setUser($user);
		} else {
			$this->Cookie->delete('CookieAuth');
		}
	}
}

//If you want to update some fields, like the last_login_date, or last_login_ip, just do :
public function beforeFilter(Event $event) {
	//Automaticaly Login.
	if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
		$this->loadModel('Users');

		$user = $this->Auth->identify();
		if ($user) {
			$this->Auth->setUser($user);

			$user = $this->Users->newEntity($user);
			$user->isNew(false);
			
			//Last login date
			$user->last_login = new Time();
			//Last login IP
			$user->last_login_ip = $this->request->clientIp();
			//etc...

			$this->Users->save($user);
		} else {
			$this->Cookie->delete('CookieAuth');
		}
	}
}

在您的 login 动作中,在 $this->Auth->setUser($user); 之后

//It will write Cookie without RememberMe checkbox
$this->Cookie->configKey('CookieAuth', [
	'expires' => '+1 year',
	'httpOnly' => true
]);
$this->Cookie->write('CookieAuth', [
	'username' => $this->request->data('username'),
	'password' => $this->request->data('password')
]);


//If you want use a RememberMe checkbox in your form :
//In your view
echo $this->Form->checkbox('remember_me');

//In the login action :
if($this->request->data('remember_me')) {
	$this->Cookie->configKey('CookieAuth', [
		'expires' => '+1 year',
		'httpOnly' => true
	]);
	$this->Cookie->write('CookieAuth', [
		'username' => $this->request->data('username'),
		'password' => $this->request->data('password')
	]);
}

如果您使用 LDAP 进行身份验证,显然不想存储密码。您可以在写入 cookie 时将密码设置为 null。

	$this->Cookie->write('CookieAuth', [
		'username' => $this->request->data('username'),
		'password' => null
	]);

贡献

遵循此指南进行贡献