MAMP環境に、Cakephp4を下記のサイトを参考にして、勉強してます。リンク内容
Authenticationプラグインを実装して、http://localhost/caketest/admin/users/loginログイン画面から、
ユーザーネームとパスワードを入力しますが、
ユーザー名かパスワードが正しくありません。と表示されます。
データとしていれた、どの名前と、パスワードでもエラーなので、loginのメソッドが機能をしていないようです。loginメソッドを入れた、UsersController.php
declare(strict_types=1); namespace App\Controller\Admin; use App\Controller\Admin\AdminController; class UsersController extends AdminController { public function beforeFilter(\Cake\Event\EventInterface $event) { parent::beforeFilter($event); // 認証を必要としないログインアクションを構成し、 // 無限リダイレクトループの問題を防ぎます $this->Authentication->addUnauthenticatedActions(['login']); } public function index() { $users = $this->paginate($this->Users); $this->set(compact('users')); } public function view($id = null) { $user = $this->Users->get($id, [ 'contain' => [], ]); $this->set(compact('user')); } public function add() { $user = $this->Users->newEmptyEntity(); if ($this->request->is('post')) { $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The user could not be saved. Please, try again.')); } $this->set(compact('user')); } 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->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The user could not be saved. Please, try again.')); } $this->set(compact('user')); } /** * Delete method * * @param string|null $id User id. * @return \Cake\Http\Response|null|void Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException 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() { $this->request->allowMethod(['get', 'post']); $result = $this->Authentication->getResult(); // POST, GET を問わず、ユーザーがログインしている場合はリダイレクトします if ($result->isValid()) { return $this->redirect('/admin'); } // ユーザーが submit 後、認証失敗した場合は、エラーを表示します if ($this->request->is('post') && !$result->isValid()) { $this->Flash->error('ユーザー名かパスワードが正しくありません。'); } } }
認証プラグインApplication.php
<?php declare(strict_types=1); namespace App; use Cake\Core\Configure; use Cake\Core\ContainerInterface; use Cake\Core\Exception\MissingPluginException; use Cake\Datasource\FactoryLocator; use Cake\Error\Middleware\ErrorHandlerMiddleware; use Cake\Http\BaseApplication; use Cake\Http\Middleware\BodyParserMiddleware; use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Http\MiddlewareQueue; use Cake\ORM\Locator\TableLocator; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; use Authentication\AuthenticationService; use Authentication\AuthenticationServiceInterface; use Authentication\AuthenticationServiceProviderInterface; use Authentication\Middleware\AuthenticationMiddleware; use Psr\Http\Message\ServerRequestInterface; class Application extends BaseApplication implements AuthenticationServiceProviderInterface { /** * Load all the application configuration and bootstrap logic. * * @return void */ public function bootstrap(): void { // Call parent to load bootstrap from files. parent::bootstrap(); if (PHP_SAPI === 'cli') { $this->bootstrapCli(); } else { FactoryLocator::add( 'Table', (new TableLocator())->allowFallbackClass(false) ); } /* * Only try to load DebugKit in development mode * Debug Kit should not be installed on a production system */ if (Configure::read('debug')) { $this->addPlugin('DebugKit'); } // Load more plugins here } **編集箇所** public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { $middlewareQueue // Catch any exceptions in the lower layers, // and make an error page/response ->add(new ErrorHandlerMiddleware(Configure::read('Error'))) // Handle plugin/theme assets like CakePHP normally does. ->add(new AssetMiddleware([ 'cacheTime' => Configure::read('Asset.cacheTime'), ])) // Add routing middleware. // If you have a large number of routes connected, turning on routes // caching in production could improve performance. For that when // creating the middleware instance specify the cache config name by // using it's second constructor argument: // `new RoutingMiddleware($this, '_cake_routes_')` ->add(new RoutingMiddleware($this)) // 認証機能 ->add(new AuthenticationMiddleware($this)) // Parse various types of encoded request bodies so that they are // available as array through $request->getData() // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware ->add(new BodyParserMiddleware()) // Cross Site Request Forgery (CSRF) Protection Middleware // https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware ->add(new CsrfProtectionMiddleware(['httponly' => true])); return $middlewareQueue; } public function services(ContainerInterface $container): void { } public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface { $authenticationService = new AuthenticationService([ 'unauthenticatedRedirect' => '/admin/users/login', 'queryParam' => 'redirect', ]); // identifiers を読み込み、username と password のフィールドを確認します $authenticationService->loadIdentifier('Authentication.Password', [ 'fields' => [ 'username' => 'username', 'password' => 'password', ] ]); // authenticatorsをロードしたら, 最初にセッションが必要です $authenticationService->loadAuthenticator('Authentication.Session'); // 入力した username と password をチェックする為のフォームデータを設定します $authenticationService->loadAuthenticator('Authentication.Form', [ 'fields' => [ 'username' => 'username', 'password' => 'password', ], 'loginUrl' => '/admin/users/login', ]); return $authenticationService; } /** * Bootstrapping for CLI application. * * That is when running commands. * * @return void */ protected function bootstrapCli(): void { try { $this->addPlugin('Bake'); } catch (MissingPluginException $e) { // Do not halt if the plugin is missing } $this->addPlugin('Migrations'); // Load more plugins here } }
入力したUsersSeed.php
<?php declare(strict_types=1); use Migrations\AbstractSeed; use Authentication\PasswordHasher\DefaultPasswordHasher; /** * Users seed. */ class UsersSeed extends AbstractSeed { > 編集箇所 public function run() { $data = [ [ 'username' => 'admin', 'password' => $this->_setPassword('admin'), 'created' => '2021-03-08 09:10:00', 'modified' => '2021-03-08 09:10:00' ], [ 'username' => 'yamada', 'password' => $this->_setPassword('yamada'), 'created' => '2021-03-08 09:10:00', 'modified' => '2021-03-08 09:10:00' ] ]; $table = $this->table('users'); $table->insert($data)->save(); } protected function _setPassword(string $password) : ?string { if (strlen($password) > 0) { return (new DefaultPasswordHasher())->hash($password); } } }
データベースには、入力されてます。
初心者で、どうしてよいか、止まってます。どなたか、良きアドバイスをお願いします。
あなたの回答
tips
プレビュー