CakePHP3的Auth
来源:互联网 发布:git ignore mac 编辑:程序博客网 时间:2024/06/05 20:05
基于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生命周期之前。
0 0
- CakePHP3的Auth
- CakePHP3的部分生命周期摘录
- CakePHP的Auth组件
- svn的auth配置文件介绍
- svn的auth配置文件介绍
- thinkphp的 Auth权限认证
- laravel身份验证-Auth的使用
- ThinkPHP5的权限控制Auth
- laravel身份验证-Auth的使用
- CakePHP3.1中文手册
- cakephp3引入类
- memocache for CakePHP3.2
- django 自定义auth的中间件的验证
- Subversion服务Auth验证的配置
- 一个base auth认证的实例
- svn中的auth文件的说明
- 一个简单的auth perl程序
- 一个简单的auth shell程序
- google test 轻松编写C++单元测试
- Centos内存管理-free命令
- Android 混淆代码总结
- 服务器运维脚本记录
- 15 个 Android 通用流行框架大全
- CakePHP3的Auth
- Android利用JXL框架读取excel
- Ubuntu 12.04下fcitx安装谷歌搜狗输入法
- 百度地图方向定位
- AFNetworking3.xPost请求- “请求对象无法序列化”处理及:App Transport Security has blocked a cleartext HTTP (http://)
- iOS学习笔记-集成环信UI3.0
- jQuery 遍历 - find() 方法
- INSERT INTO t_inertupdate_tmp(a,b,c) select * 表名 where 字段名 is not null
- ubuntu下安装shadowsocks-qt5(影梭)