<?php
declare(strict_types=1);
namespace App;
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
// 認証用のクラス、インターフェイスのインポート
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
use Cake\Routing\Router;
use Psr\Http\Message\ServerRequestInterface;
// インターフェイスを継承する
class Application extends BaseApplication implements AuthenticationServiceProviderInterface
{
// ルーティングのミドルウェアを読み込んだあとに
// 認証のミドルウェアを追加する
// ->add(new AuthenticationMiddleware($this)
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));
return $middlewareQueue;
}
/**
* インターフェイスの実装
*
* @param ServerRequestInterface $request
* @return AuthenticationServiceInterface
*/
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$login_url = Router::url([
'controller' => 'Pages',
'action' => 'login',
]);
$service = new AuthenticationService([
'unauthenticatedRedirect' => $login_url,
'queryParam' => 'redirect',
]);
// identifiers を読み込み、email と password のフィールドを確認します
// 認証用のモデルの設定
$service->loadIdentifier(
'Authentication.Password',
[
'resolver' => [
'className' => 'Authentication.Orm',
'userModel' => 'Managers',
],
'fields' => [
'username' => 'mail',
'password' => 'password',
],
]
);
// authenticatorsをロードしたら, 最初にセッションが必要です
$service->loadAuthenticator('Authentication.Session');
// 入力した email と password をチェックする為のフォームデータを設定します
$service->loadAuthenticator(
'Authentication.Form',
[
'fields' => [
'username' => 'mail',
'password' => 'password',
],
'loginUrl' => $login_url,
]
);
return $service;
}
}
?>