[[CakePHP3めも]]

*UserController.php [#a9287d29]

usersテーブルに username と password の名前でフィールドを作っておけばそれらを使って認証してくれます。

     public function initialize()
     {
         parent::initialize();
 
         $this->loadComponent('Auth', [
             'loginAction' => [
                 'controller' => 'Users',
                 'action' => 'login'
             ],
             'loginRedirect' => [
                 'controller' => 'Pages',
                 'action' => 'index'
             ],
             'logoutRedirect' => [
                 'controller' => 'Users',
                 'action' => 'login'
             ]
         ]);
     }
 
     public function beforeFilter(Event $event)
     {
         parent::beforeFilter($event);
         
         $this->Auth->config('authenticate', [
             'Form' => [
                 'userModel' => 'Users',  // 認証に使用するテーブル
                 'finder' => 'auth'  // 認証条件の追加 UsersTable.php の findAuth() へ
                 'finder' => 'auth', // 認証条件の追加 UsersTable.php の findAuth() へ
                 'fields' => [
                     'username' => 'email', // 認証に使用するカラム(変更しない場合は省略可)
                     'password' => 'password'// 認証に使用するカラム(変更しない場合は省略可)
                 ]
             ]
         ]);
         
         $this->Auth->allow(['login']);
     }
 
     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());
     }

ログイン後のユーザーのデータは以下で取得できます。

 $user = $this->Auth->user();

idだけを取得したい場合は以下のように指定します。

 $id = $this->Auth->user('id');

*UsersTable.php [#s2c9cbe6]

username, password に加えて enabled が 1 であることを認証条件に加える場合は以下のように書きます。

     public function findAuth(Query $query)
     {
         $query->where([
             'Users.enabled' => 1
         ]);
         return $query;
     }


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS