0

私はcakephp3を使用しています。ユーザーを持つ単純な Web アプリケーションがあります。管理者と標準の 2 つのユーザー タイプがあります。標準ユーザーをデータの表示とインデックス作成のみに制限したいと考えています。一方、管理者タイプのユーザーは、ユーザー データを追加、編集、削除、表示、およびインデックス化できる必要があります。

基本的に、標準ユーザーをグローバルに制限して、コントローラーの追加、編集、および削除メソッドにアクセスできないようにします。

誰でも私がそれを達成するのを助けることができますか?


以下は /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 に答える