xety / cake3-cookieauth

一个简单的 Cake3 插件,用于通过 Cookies 验证用户。

安装次数: 47,573

依赖关系: 5

建议者: 0

安全: 0

星标: 18

关注者: 4

分支: 13

公开问题: 6

类型:cakephp-plugin

v1.4 2016-10-25 06:10 UTC

This package is auto-updated.

Last update: 2024-09-04 23:54:55 UTC


README

一个简单的 Cake3 插件,用于通过 Cookies 验证用户。此插件基于出色的插件 FriendsOfCake/Authenticate,但配置不同。

Build Status Coverage Status Scrutinizer Latest Stable Version Total Downloads License

要求

  • CakePHP 3.X

安装

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

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

配置

'Xety/Cake3CookieAuth.Cookie' => [
    'cookie' => [
        'name' => 'CookieAuth'
    ]
]

所有其他配置选项可以在官方 CakePHP 文档 中找到。

用法

在你的 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')
    ]);
}

贡献

遵循此指南进行贡献