0

我正在使用 cakephp3。我有一个拥有用户的简单 Web 应用程序。我有两种用户类型,管理员和标准。我想限制标准用户只能查看和索引数据。而管理员类型的用户应该能够添加、编辑、删除、查看和索引用户数据。

基本上,我想全局限制标准用户,使他们无法访问控制器的添加、编辑和删除方法。

那么任何人都可以帮助我实现它吗?


下面是/src/Controller/UsersController.php

            <?php
            namespace App\Controller;

            use App\Controller\AppController;

            /**
             * Users Controller
             *
             * @property \App\Model\Table\UsersTable $Users
             */
            class UsersController extends AppController
            {

                /**
                 * Index method
                 *
                 * @return void
                 */
                public function index()
                {
                    $this->paginate = [
                        'contain' => ['Countries', 'Cities', 'UserGroups', 'UserLevels']
                    ];
                    $this->set('users', $this->paginate($this->Users));
                    $this->set('_serialize', ['users']);
                }

                public function dashboard()
                {

                }
                /**
                 * 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' => ['Countries', 'Cities', 'UserGroups', 'UserLevels', 'Alerts', 'DeviceLogs', 'Devices']
                    ]);
                    $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.'));
                        }
                    }
                    $countries = $this->Users->Countries->find('list', ['limit' => 200]);
                    $cities = $this->Users->Cities->find('list', ['limit' => 200]);
                    $userGroups = $this->Users->UserGroups->find('list', ['limit' => 200]);
                    $userLevels = $this->Users->UserLevels->find('list', ['limit' => 200]);
                    $this->set(compact('user', 'countries', 'cities', 'userGroups', 'userLevels'));
                    $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.'));
                        }
                    }
                    $countries = $this->Users->Countries->find('list', ['limit' => 200]);
                    $cities = $this->Users->Cities->find('list', ['limit' => 200]);
                    $userGroups = $this->Users->UserGroups->find('list', ['limit' => 200]);
                    $userLevels = $this->Users->UserLevels->find('list', ['limit' => 200]);
                    $this->set(compact('user', 'countries', 'cities', 'userGroups', 'userLevels'));
                    $this->set('_serialize', ['user']);
                }

                /**
                 * Delete method
                 *
                 * @param string|null $id User id.
                 * @return \Cake\Network\Response|null 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 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 resetPassword() {

                }

                public function changepassword() {

                }

            }

            Below is AppController.php

            <?php

            namespace App\Controller;

            use Cake\Controller\Controller;
            use Cake\Event\Event;

            class AppController extends Controller
            {
                use \Crud\Controller\ControllerTrait;

                public $components = [
                    'RequestHandler',
                    'Crud.Crud' => [
                        'actions' => [
                            'Crud.Index',
                            'Crud.View',
                            'Crud.Add',
                            'Crud.Edit',
                            'Crud.Delete'
                        ],
                        'listeners' => [
                            'Crud.Api',
                            'Crud.ApiPagination',
                            'Crud.ApiQueryLog'
                        ]
                    ]
                ];
                /**
                 * Initialization hook method.
                 *
                 * Use this method to add common initialization code like loading components.
                 *
                 * e.g. `$this->loadComponent('Security');`
                 *
                 * @return void
                 */
                public function initialize()
                {
                    parent::initialize();

                    $this->loadComponent('RequestHandler');
                    $this->loadComponent('Flash');
                    $this->loadComponent('Auth', [
                        'authenticate' => [
                            'Form' => [
                                'fields' => [
                                    'username' => 'email',
                                    'password' => 'password'
                                ]
                            ]
                        ],
                        'loginAction' => [
                            'controller' => 'Users',
                            'action' => 'login'
                        ],
                        // default is referer and in case of no referer loginRedirect (after login)
                        'loginRedirect' => [
                            'controller' => 'Users',
                            'action' => 'dashboard'
                        ],
                        'logoutRedirect' => '/',
                        'authError' => "Y"
                    ]);

                    // Allow the display action so our pages controller
                    // continues to work.
                    $this->Auth->allow(['resetPassword','add','changePassword','display']);
                }
                /**
                 * Before render callback.
                 *
                 * @param \Cake\Event\Event $event The beforeRender event.
                 * @return void
                 */
                public function beforeRender(Event $event)
                {
                    if (!array_key_exists('_serialize', $this->viewVars) &&
                        in_array($this->response->type(), ['application/json', 'application/xml'])
                    ) {
                        $this->set('_serialize', true);
                    }
                }
            }

问候,

4

1 回答 1

0

正确的方法是使用ControllerAuthorize

如文档中所述,您必须添加AppController以下内容:

public function isAuthorized($user = null)
{
    // Any registered user can access public functions
    if (empty($this->request->params['prefix'])) {
        return true;
    }

    // Only admins can access admin functions
    if ($this->request->params['prefix'] === 'admin') {
        return (bool)($user['role'] === 'admin');
    }

    // Default deny
    return false;
}

然后,您必须将 admin 定义为前缀路由的有效键,并将您的添加、编辑和删除操作移动到新控制器

src/Controller/Admin/UsersController.php
于 2015-12-12T18:38:11.803 回答