1

我正在使用 CakePHP 3.2 并编写一个只有管理员才能登录的管理面板。

有一个单独的表admins来存储管理员凭据。还有一个users表格用于用户从主应用程序注册/登录。

我必须使用admins表格登录管理面板。

我所做的是。

<?php
namespace App\Controller;

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


class AppController extends Controller
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
          'loginAction' => [
            'controller' => 'Admins',
            'action' => 'login',
            'plugin' => 'Admins'
          ],
          'loginRedirect' => [
            'controller' => 'ServiceRequests',
            'action' => 'index'
          ],
          'logoutRedirect' => [
            'controller' => 'Admins',
            'action' => 'login'
          ],
          'authenticate' => [
            'Form' => [
              'userModel' => 'Admin',
              'fields' => [
                'username' => 'email',
                'password' => 'password'
              ]
            ]
          ]
        ]);
    }

    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);
        }
    }
}

AdminsController.php

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;
use App\Controller\AuthComponent;

/**
 * Admins Controller
 *
 * @property \App\Model\Table\AdminsTable $Admins
 */
class AdminsController extends AppController
{
      public function beforeFilter(Event $event)
      {
          parent::beforeFilter($event);
          $this->Auth->allow('add');
          // Pass settings in using 'all'
          $this->Auth->config('authenticate', [
            AuthComponent::ALL => ['userModel' => 'Members'],
              'Basic',
              'Form'
          ]);
      }

    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(__('Invalid username or password, try again'));
        }
    }

    public function logout()
    {
        return $this->redirect($this->Auth->logout());
    }
}

但这不起作用。并给出Error: Class App\Controller\AuthComponent' not found

此外,我想限制对所有控制器和操作的访问,无需登录。$this->Auth->allow()这就是为什么没有AppsController.php

4

1 回答 1

2

使用 Cake\Controller\Component\AuthComponent;

于 2016-06-30T19:20:53.157 回答