mtbrandall

Application.php

Feb 4th, 2021 (edited)
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.40 KB | None | 0 0
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. /**
  5.  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  6.  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  7.  *
  8.  * Licensed under The MIT License
  9.  * For full copyright and license information, please see the LICENSE.txt
  10.  * Redistributions of files must retain the above copyright notice.
  11.  *
  12.  * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  13.  * @link      https://cakephp.org CakePHP(tm) Project
  14.  * @since     3.3.0
  15.  * @license   https://opensource.org/licenses/mit-license.php MIT License
  16.  */
  17. namespace App;
  18.  
  19. use Cake\Core\Configure;
  20. use Cake\Core\Exception\MissingPluginException;
  21. use Cake\Error\Middleware\ErrorHandlerMiddleware;
  22. use Cake\Http\BaseApplication;
  23. use Cake\Http\Middleware\BodyParserMiddleware;
  24. use Cake\Http\MiddlewareQueue;
  25. use Cake\Routing\Middleware\AssetMiddleware;
  26. use Cake\Routing\Middleware\RoutingMiddleware;
  27.  
  28. /*
  29. # Auth
  30. */
  31. use Authentication\AuthenticationService;
  32. use Authentication\AuthenticationServiceInterface;
  33. use Authentication\AuthenticationServiceProviderInterface;
  34. use Authentication\Identifier\IdentifierInterface;
  35. use Authentication\Middleware\AuthenticationMiddleware;
  36. use Cake\Routing\Router;
  37. use Psr\Http\Message\ServerRequestInterface;
  38.  
  39. /*
  40. # Auth
  41. */
  42. use Authorization\AuthorizationService;
  43. use Authorization\AuthorizationServiceInterface;
  44. use Authorization\AuthorizationServiceProviderInterface;
  45. use Authorization\Middleware\AuthorizationMiddleware;
  46. use Authorization\Policy\OrmResolver;
  47. use Psr\Http\Message\ResponseInterface;
  48.  
  49. use App\Policy\RequestPolicy;
  50. use Authorization\Policy\MapResolver;
  51. use Cake\Http\ServerRequest;
  52.  
  53. use Authorization\Policy\ResolverCollection;
  54.  
  55. /**
  56.  * Application setup class.
  57.  *
  58.  * This defines the bootstrapping logic and middleware layers you
  59.  * want to use in your application.
  60.  */
  61. class Application extends BaseApplication implements AuthenticationServiceProviderInterface, AuthorizationServiceProviderInterface
  62. //class Application extends BaseApplication
  63. {
  64.     /**
  65.      * Load all the application configuration and bootstrap logic.
  66.      *
  67.      * @return void
  68.      */
  69.     public function bootstrap(): void
  70.     {
  71.         // Call parent to load bootstrap from files.
  72.         parent::bootstrap();
  73.  
  74.         if (PHP_SAPI === 'cli') {
  75.             $this->bootstrapCli();
  76.         }
  77.  
  78.         /*
  79.          * Only try to load DebugKit in development mode
  80.          * Debug Kit should not be installed on a production system
  81.          */
  82.         if (Configure::read('debug')) {
  83.             $this->addPlugin('DebugKit');
  84.         }
  85.  
  86.         // Load more plugins here
  87.         $this->addPlugin('Authentication');
  88.         $this->addPlugin('Authorization');
  89.     }
  90.  
  91.     /**
  92.      * Setup the middleware queue your application will use.
  93.      *
  94.      * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
  95.      * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
  96.      */
  97.     public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  98.     {
  99.         $middlewareQueue
  100.             // Catch any exceptions in the lower layers,
  101.             // and make an error page/response
  102.             ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
  103.  
  104.             // Handle plugin/theme assets like CakePHP normally does.
  105.             ->add(new AssetMiddleware([
  106.                 'cacheTime' => Configure::read('Asset.cacheTime'),
  107.             ]))
  108.  
  109.             // Add routing middleware.
  110.             // If you have a large number of routes connected, turning on routes
  111.             // caching in production could improve performance. For that when
  112.             // creating the middleware instance specify the cache config name by
  113.             // using it's second constructor argument:
  114.             // `new RoutingMiddleware($this, '_cake_routes_')`
  115.             ->add(new RoutingMiddleware($this))
  116.  
  117.             // Parse various types of encoded request bodies so that they are
  118.             // available as array through $request->getData()
  119.             // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
  120.             ->add(new BodyParserMiddleware())
  121.            
  122.             // Auth
  123.             ->add(new AuthenticationMiddleware($this))
  124.             ->add(new AuthorizationMiddleware($this));
  125.            
  126.  
  127.  
  128.         return $middlewareQueue;
  129.     }
  130.  
  131.     /**
  132.      * Bootrapping for CLI application.
  133.      *
  134.      * That is when running commands.
  135.      *
  136.      * @return void
  137.      */
  138.     protected function bootstrapCli(): void
  139.     {
  140.         try {
  141.             $this->addPlugin('Bake');
  142.         } catch (MissingPluginException $e) {
  143.             // Do not halt if the plugin is missing
  144.         }
  145.  
  146.         $this->addPlugin('Migrations');
  147.  
  148.         // Load more plugins here
  149.     }
  150.    
  151.     /**
  152.      * Returns a service provider instance.
  153.      *
  154.      * @param \Psr\Http\Message\ServerRequestInterface $request Request
  155.      * @return \Authentication\AuthenticationServiceInterface
  156.      */
  157.     public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
  158.     {
  159.         $service = new AuthenticationService();
  160.    
  161.         // Define where users should be redirected to when they are not authenticated
  162.         $service->setConfig([
  163.             'unauthenticatedRedirect' => Router::url([
  164.                     'prefix' => false,
  165.                     'plugin' => null,
  166.                     'controller' => 'Myaccount',
  167.                     'action' => 'login',
  168.             ]),
  169.             'queryParam' => 'redirect',
  170.         ]);
  171.    
  172.         $fields = [
  173.             IdentifierInterface::CREDENTIAL_USERNAME => 'email',
  174.             IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
  175.         ];
  176.         // Load the authenticators. Session should be first.
  177.         $service->loadAuthenticator('Authentication.Session');
  178.         $service->loadAuthenticator('Authentication.Form', [
  179.             'fields' => $fields,
  180.             'loginUrl' => Router::url([
  181.                 'prefix' => false,
  182.                 'plugin' => null,
  183.                 'controller' => 'Myaccount',
  184.                 'action' => 'login',
  185.             ]),
  186.         ]);
  187.    
  188.         // Load identifiers
  189.         $service->loadIdentifier('Authentication.Password', compact('fields'));
  190.    
  191.         return $service;
  192.     }
  193.    
  194.     public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
  195.     {
  196.         $mapResolver = new MapResolver();
  197.         $ormResolver = new OrmResolver();
  198.  
  199.         $mapResolver->map(ServerRequest::class, RequestPolicy::class);
  200.  
  201.         $resolver = new ResolverCollection([$mapResolver, $ormResolver]);
  202.         return new AuthorizationService($resolver);
  203.     }
  204. }
  205.  
Add Comment
Please, Sign In to add comment