CakePHP3的Auth

基于Controller的认证

看配置代码:

        $this->loadComponent('Auth', [
            'authorize' => 'Controller',
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'unauthorizedRedirect' => $this->referer()
        ]);

需求,在登录成功后需要修改用户表的某一个字段(最后登录时间)。

基于Controller认证的基础是 Auth是在Controller初始化之前,如果在认证流程走完之前进行数据库操作,是不会成功的。如下面的代码:

    // In src/Controller/UsersController.php
    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                // update login_logined field
                $user = $this->Users->get($this->Auth->user('id'));
                $user->last_logined = date("Y-m-d H:i:s");
                $this->Users->save($user);
                // end
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error('Your username or password is incorrect.');
        }
    }

上面代码一运行就会在

$user = $this->Users->get($this->Auth->user('id'));

这儿报错,因为Controller未被初始化,里面的任何东西都无法使用。如何才知道认证流程是否走完呢?走了好些弯路,其实在redirect之前就走完了,如果执行$this->redirect($this->Auth->redirectUrl());不报错,就证明controller是初始化完了的。总结来看,就是$this->Auth->setUser($user);这句话是关键作用,他通知Auth组件认证已经完成,请接着走。

最终代码修改如下:

   // In src/Controller/UsersController.php
    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                // update login_logined field
                $user = $this->Users->get($this->Auth->user('id'));
                $user->last_logined = date("Y-m-d H:i:s");
                $this->Users->save($user);
                // end
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error('Your username or password is incorrect.');
        }
    }

总结:Auth是在beforeFilter生命周期之前。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值