Я делаю приложение с cakephp 3, и я хочу, чтобы обычный пользователь («выпускники») ограничивал просмотр и редактирование только своих профилей, поэтому я пытаюсь сравнить идентификатор зарегистрированного пользователя и значение, отправляемое запросом в URL-адресе, но оно не работает, оно отправляет следующую ошибку: «Уведомление (8): Неопределенное смещение: 0 [APP/Controller \ UsersController.php, строка 144]», переменная $ this-> request-> params ['pass'] [0] пуста. Как я могу это исправить?cakephp 3 Ошибка с переданным параметром в url
Это мой userController.php
class UsersController extends AppController{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->paginate = [
'contain' => ['Grados']
];
$this->set('users', $this->paginate($this->Users));
$this->set('_serialize', ['users']);
}
/**
* View method
*
* @param string|null $id User id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$user = $this->Users->get($id, [
'contain' => ['Grados', 'Clases', 'ConveniosUsuarios', 'Desvinculaciones', 'HistorialAlumnos', 'Pagos', 'Pedidos']
]);
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$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.'));
}
}
$grados = $this->Users->Grados->find('list', ['limit' => 200]);
$this->set(compact('user', 'grados'));
$this->set('_serialize', ['user']);
}
/**
* Edit method
*
* @param string|null $id User id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
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.'));
}
}
$grados = $this->Users->Grados->find('list', ['limit' => 200]);
$this->set(compact('user', 'grados'));
$this->set('_serialize', ['user']);
}
/**
* Delete method
*
* @param string|null $id User id.
* @return void Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
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 beforeFilter(Event $event)
{
$this->Auth->allow(['logout']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
if ($this->Auth->user('rol') == 'Alumno') {
$this->redirect('users'.DS.'view'.DS.$this->Auth->user('id'));
}else{
return $this->redirect($this->Auth->redirectUrl());
}
}else{
$this->Flash->error(__('Usario o contraseña invalidos!'));
}
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function isAuthorized($user)
{
$userid=$this->Auth->user('id');
$id= $this->request->params['pass'][0];//here is the problem!!
$action = $this->request->params['action'];
if ($user['rol']=='Instructor') {
return true;
}else if ($user['rol']!='Instructor') {
if (in_array($action, ['edit', 'view']) && $userid == $id) {
return true;
}
return false;
}
return parent::isAuthorized($user);
}
}
Когда, если пользователь правильно отладить ($ this-> request-> PARAMS) Дисплей:
[
'plugin' => null,
'controller' => 'Users',
'action' => 'view',
'_ext' => null,
'pass' => [
(int) 0 => '4'
]
]
Но если пользователь попытаться увидеть другой профиль отладки ($ this-> request-> PARAMS) дисплей:
[
'plugin' => null,
'controller' => 'Users',
'action' => 'index',
'_ext' => null,
'pass' => []
]
AppController.php
class AppController extends Controller
{
/**
* Initialization hook method.
*
* Use this method to add common initialization code like loading components.
*
* @return void
*/
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['login']);
}
public function isAuthorized($user)
{
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
}
Вы можете добавить содержимое '$ this-> request-> params' как раз перед вашей ошибки? – Jun
done !, я добавляю результат отладки ($ this-> request-> params) для 2-х случаев –
Я добавляю appController.php –