justinatack / authenticate
CakePHP认证插件的集合
dev-master
2016-09-20 05:13 UTC
Requires
- php: >=5.4.16
- cakephp/cakephp: ~3.0
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-20 21:17:09 UTC
README
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
安装此 composer 包的推荐方式是
composer require justinatack/authenticate:dev-master
在您的 config/bootstrap.php 文件中添加以下内容
Plugin::load('JustinAtack/Authenticate');
在您的 src/Controller/AppController.php 文件中添加以下内容
$this->loadComponent('Auth', [
'authenticate' => [
'JustinAtack/Authenticate.Passwordless' => [
'fields' => [
'username' => 'email',
'token' => 'token',
'token_expiry' => 'token_expiry'
],
'token' => [
'query' => 'token',
'length' => 10, // bytes
'expires' => '+10 mins'
]
]
]
]);
说明
使用 email
、token
和 token_expiry
字段创建一个用户表。以下列可以作为一个 Users 迁移的起点。
$table->addColumn('email', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('token', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->addColumn('token_expiry', 'datetime', [
'default' => null,
'null' => true,
]);
在您的 src/Controller/UsersController.php 中添加以下登录方法
public function login($token = null)
{
/**
* Validate token and login user
*
*/
if (!empty($this->request->params['pass'][0]) || !empty($this->request->query('token'))) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid or expired token, please request new login token'));
return $this->redirect($this->Auth->redirectUrl());
}
/**
* Validate email and send login token
*
*/
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Flash->success(__('A one-time login URL has been emailed to you'));
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Email is incorrect'));
return $this->redirect($this->Auth->redirectUrl());
}
}
创建一个包含单个电子邮件表单字段和提交按钮的登录视图。现在添加一个用户,然后使用电子邮件地址提交登录表单。这将生成一个令牌并设置令牌有效期。使用此代码,您可以使用以下 URL 登录,两者效果相同。
https://www.example.com/users/login/{token_here}
https://www.example.com/users/login?token={token_here}
此时,您应该有一个可用的登录系统,每次登录电子邮件请求后都会保存 token
和 token_expiry
。此插件不处理在登录请求后发送给用户的令牌电子邮件。这部分由您决定如何处理,也许您想排队请求或直接发送电子邮件甚至短信。以下是一个起点。以下代码放置在您的 src/Controller/UsersController.php 文件中。它监听 Auth.afterIdentify 事件。您可以触发自己的方法调用,例如将带有登录链接的令牌电子邮件发送给用户。我简单地将其记录到我的调试日志中。
use Cake\Log\Log;
/**
* Initialize method
*
*/
public function initialize()
{
parent::initialize();
$this->Auth->allow(['login', 'logout', 'add']);
$this->eventManager()->on('Auth.afterIdentify', [$this, 'afterIdentify']);
}
public function afterIdentify(Event $event, array $user)
{
Log::write('debug', $user);
// Email user link with embedded token.
// See example links above to generate correct URLs
}
示例调试日志输出
2016-08-22 07:18:45 Debug: Array
(
[id] => 1
[email] => passwordless@example.com
[token] => 53af7103f12c1e9ff752
)
警告
所有令牌链接应仅通过安全的 SSL 连接使用。