我正在学习 cakePHP 3 以申请实习,我目前正在学习 cakePHP.org官方食谱中的教程,但我讨厌这本书。这很令人困惑。
无论如何,我做了书签示例的步骤,它有点工作,我做了所有的事情,就像这本书告诉我的那样,直到登录和注销部分,但是当我尝试从系统中注销时,它告诉我“你没有被授权访问该位置。”
如果您需要我项目中的任何其他代码,请告诉我。
要注销,我将使用以下代码引导用户,该代码会生成指向以下内容的超链接server/users/logout
:
<?= $this->Html->link(__('Log out'), ['controller' => 'Users', 'action' => 'logout']) ?>
/rootOfProject/src/Controller/AppController.php:
namespace App\Controller;
use Cake\Controller\Controller;
class AppController extends Controller {
public function initialize() {
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'unauthorizedRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'authorize' => 'Controller'
]);
$this->Auth->allow(['display']);
}
public function isAuthorized($user) {
return false;
}
}
/rootOfProject/src/Controller/UsersController.php:
namespace App\Controller;
use App\Controller\AppController;
class UsersController extends AppController {
public function index() {
$this->set('users', $this->paginate($this->Users));
}
public function view($id = null) {
$user = $this->Users->get($id, [
'contain' => ['Bookmarks']
]);
$this->set('user', $user);
}
public function add() {
$user = $this->Users->newEntity($this->request->data);
if ($this->request->is('post')) {
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
}
public function edit($id = null) {
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
}
public function delete($id = null) {
$user = $this->Users->get($id);
$this->request->allowMethod(['post', 'delete']);
if ($this->Users->delete($user)) {
$this->Flash->success('The user has been deleted.');
} else {
$this->Flash->error('The user could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
public function login() {
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
public function logout() {
$this->Flash->success('You are now logged out.');
return $this->redirect($this->Auth->logout());
}
public function beforeFilter(\Cake\Event\Event $event) {
$this->Auth->allow(['add']);
}
}