mtbrandall

Application.php

Feb 4th, 2021
1,022
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.92 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\Middleware\RequestAuthorizationMiddleware;
  47. use Authorization\Policy\OrmResolver;
  48. use Psr\Http\Message\ResponseInterface;
  49.  
  50. use App\Policy\RequestPolicy;
  51. use Authorization\Policy\MapResolver;
  52. use Cake\Http\ServerRequest;
  53.  
  54. use App\Controller\ManageController;
  55. use App\Policy\ManagePolicy;
  56.  
  57. use Authorization\Policy\ResolverCollection;
  58.  
  59. /**
  60.  * Application setup class.
  61.  *
  62.  * This defines the bootstrapping logic and middleware layers you
  63.  * want to use in your application.
  64.  */
  65. class Application extends BaseApplication implements AuthenticationServiceProviderInterface, AuthorizationServiceProviderInterface
  66. //class Application extends BaseApplication
  67. {
  68.     /**
  69.      * Load all the application configuration and bootstrap logic.
  70.      *
  71.      * @return void
  72.      */
  73.     public function bootstrap(): void
  74.     {
  75.         // Call parent to load bootstrap from files.
  76.         parent::bootstrap();
  77.  
  78.         if (PHP_SAPI === 'cli') {
  79.             $this->bootstrapCli();
  80.         }
  81.  
  82.         /*
  83.          * Only try to load DebugKit in development mode
  84.          * Debug Kit should not be installed on a production system
  85.          */
  86.         if (Configure::read('debug')) {
  87.             $this->addPlugin('DebugKit');
  88.         }
  89.  
  90.         // Load more plugins here
  91.         $this->addPlugin('Authentication');
  92.         $this->addPlugin('Authorization');
  93.     }
  94.  
  95.     /**
  96.      * Setup the middleware queue your application will use.
  97.      *
  98.      * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
  99.      * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
  100.      */
  101.     public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  102.     {
  103.         $authorizationService = new AuthorizationService(new OrmResolver());
  104.        
  105.        
  106.         $middlewareQueue
  107.             // Catch any exceptions in the lower layers,
  108.             // and make an error page/response
  109.             ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
  110.  
  111.             // Handle plugin/theme assets like CakePHP normally does.
  112.             ->add(new AssetMiddleware([
  113.                 'cacheTime' => Configure::read('Asset.cacheTime'),
  114.             ]))
  115.  
  116.             // Add routing middleware.
  117.             // If you have a large number of routes connected, turning on routes
  118.             // caching in production could improve performance. For that when
  119.             // creating the middleware instance specify the cache config name by
  120.             // using it's second constructor argument:
  121.             // `new RoutingMiddleware($this, '_cake_routes_')`
  122.             ->add(new RoutingMiddleware($this))
  123.  
  124.             // Parse various types of encoded request bodies so that they are
  125.             // available as array through $request->getData()
  126.             // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
  127.             ->add(new BodyParserMiddleware())
  128.            
  129.             // Auth
  130.             ->add(new AuthenticationMiddleware($this))
  131.             ->add(new AuthorizationMiddleware($this, [
  132.  
  133.                 'unauthorizedHandler' => [
  134.  
  135.                     'className' => 'Authorization.Redirect',
  136.  
  137.                     'url' => '/users/login',
  138.  
  139.                     'queryParam' => 'redirectUrl',
  140.  
  141.                 ],
  142.  
  143.             ]));
  144.  
  145.            
  146.         return $middlewareQueue;
  147.     }
  148.  
  149.     /**
  150.      * Bootrapping for CLI application.
  151.      *
  152.      * That is when running commands.
  153.      *
  154.      * @return void
  155.      */
  156.     protected function bootstrapCli(): void
  157.     {
  158.         try {
  159.             $this->addPlugin('Bake');
  160.         } catch (MissingPluginException $e) {
  161.             // Do not halt if the plugin is missing
  162.         }
  163.  
  164.         $this->addPlugin('Migrations');
  165.  
  166.         // Load more plugins here
  167.     }
  168.    
  169.     /**
  170.      * Returns a service provider instance.
  171.      *
  172.      * @param \Psr\Http\Message\ServerRequestInterface $request Request
  173.      * @return \Authentication\AuthenticationServiceInterface
  174.      */
  175.     public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
  176.     {
  177.         $service = new AuthenticationService();
  178.    
  179.         // Define where users should be redirected to when they are not authenticated
  180.         $service->setConfig([
  181.             'unauthenticatedRedirect' => Router::url([
  182.                     'prefix' => false,
  183.                     'plugin' => null,
  184.                     'controller' => 'Myaccount',
  185.                     'action' => 'login',
  186.             ]),
  187.             'queryParam' => 'redirect',
  188.         ]);
  189.    
  190.         $fields = [
  191.             IdentifierInterface::CREDENTIAL_USERNAME => 'email',
  192.             IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
  193.         ];
  194.         // Load the authenticators. Session should be first.
  195.         $service->loadAuthenticator('Authentication.Session');
  196.         $service->loadAuthenticator('Authentication.Form', [
  197.             'fields' => $fields,
  198.             'loginUrl' => Router::url([
  199.                 'prefix' => false,
  200.                 'plugin' => null,
  201.                 'controller' => 'Myaccount',
  202.                 'action' => 'login',
  203.             ]),
  204.         ]);
  205.    
  206.         // Load identifiers
  207.         $service->loadIdentifier('Authentication.Password', compact('fields'));
  208.    
  209.         return $service;
  210.     }
  211.    
  212.     public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
  213.     {
  214.         $mapResolver = new MapResolver();
  215.         $ormResolver = new OrmResolver();
  216.  
  217.         $mapResolver->map(ServerRequest::class, RequestPolicy::class);
  218.         $mapResolver->map(ManageController::class, ManagePolicy::class);
  219.  
  220.         $resolver = new ResolverCollection([$mapResolver, $ormResolver]);
  221.         return new AuthorizationService($resolver);
  222.     }
  223. }
  224.  
Advertisement
Add Comment
Please, Sign In to add comment