CakePHP3 Authコンポーネントでログイン・ログアウト機能のサンプルコード。
● 使用例のテーブル定義(usersテーブル)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // ユーザーテーブル // status 0:仮登録 1:本登録 2:退会 CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `status` char(1) DEFAULT 0, `created` DATETIME DEFAULT NULL, `modified` DATETIME DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; // テストデータ INSERT INTO `users` (`id`, `email`, `password`, `status`, `created`, `modified`) VALUES (NULL, '001@cakephp3.com', '001', '0', NULL, NULL), (NULL, '002@cakephp3.com', '002', '1', NULL, NULL); |
◯「AppController.php」にAuth定義実装【サンプル】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | class AppController extends Controller { public function initialize() { parent::initialize(); // ・・・ $this->loadComponent('Auth', [ 'authenticate' => [ // ユーザー認証に使用するカラム(email, password) 'Form' => [ 'fields' => [ 'username' => 'email', 'password' => 'password' ] ] // ユーザー認証に使用するカラム(email, password, status[1のみ]) // 'Form' => [ // 'fields' => [ // 'username' => 'email', // 'password' => 'password' // ], // 'scope' => ['status' => 1] // ], // // 認証テーブル users -> admins切替(デフォルト:Users) // 'userModel' => 'Admins' ], // ログインを扱うコントローラーとアクション(デフォルト:/users/login) 'loginAction' => [ 'controller' => 'Users', 'action' => 'login' ], // ログイン後のリダイレクト先(コントローラーとアクション) 'loginRedirect' => [ 'controller' => 'Users', 'action' => 'index' ], // ログアウト後のリダイレクト先(コントローラーとアクション) 'logoutRedirect' => [ 'controller' => 'Users', 'action' => 'index' ], // 未ログイン時にログイン必須ページを閲覧した際のMSG 'authError' => __('ログインしてください。') ]); // ・・・ } } |
◯「UsersController.php」にログイン・ログアウト実装【サンプル】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | ・・・ use Cake\Event\Event; ・・・ class UsersController extends AppController { public function beforeFilter(Event $event) { parent::beforeFilter($event); // 未ログイン時にすべてのアクションを許可 $this->Auth->allow(); } public function index() { } // ログイン public function login() { if ($this->request->is('post')) { // ユーザー認証 // usersテーブルのusernameとpasswordが一致したレコード取得 $user = $this->Auth->identify(); if ($user) { // メソッドに渡されたデータを持つユーザーとしてログイン $this->Auth->setUser($user); // $this->Auth->redirectUrl(): ログイン後のリダイレクト先URLを返す(loginRedirect) return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error(__('emailまたはpasswordが間違っています。')); } } } // ログアウト public function logout() { // $this->Auth->logout(): ユーザー認証を解除し、ログアウト後のリダイレクト先URLを返す(logoutRedirect) return $this->redirect($this->Auth->logout()); } } |