Passed
Branch master (e828dd)
by giu
03:47
created

Application::bootstrapCli()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
7
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
8
 *
9
 * Licensed under The MIT License
10
 * For full copyright and license information, please see the LICENSE.txt
11
 * Redistributions of files must retain the above copyright notice.
12
 *
13
 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
14
 * @link      https://cakephp.org CakePHP(tm) Project
15
 * @since     3.3.0
16
 * @license   https://opensource.org/licenses/mit-license.php MIT License
17
 */
18
19
namespace App;
20
21
use Cake\Core\Configure;
22
use Cake\Core\Exception\MissingPluginException;
23
use Cake\Error\Middleware\ErrorHandlerMiddleware;
24
use Cake\Http\BaseApplication;
25
use Cake\Http\Middleware\BodyParserMiddleware;
26
use Cake\Http\Middleware\CsrfProtectionMiddleware;
27
use Cake\Http\MiddlewareQueue;
28
use Cake\Routing\Middleware\AssetMiddleware;
29
use Cake\Routing\Middleware\RoutingMiddleware;
30
use Authentication\AuthenticationService;
31
use Authentication\AuthenticationServiceInterface;
32
use Authentication\AuthenticationServiceProviderInterface;
33
use Authentication\Identifier\IdentifierInterface;
34
use Authentication\Middleware\AuthenticationMiddleware;
35
#use Cake\Http\MiddlewareQueue;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
36
use Cake\Routing\Router;
37
use Psr\Http\Message\ServerRequestInterface;
38
39
/**
40
 * Application setup class.
41
 *
42
 * This defines the bootstrapping logic and middleware layers you
43
 * want to use in your application.
44
 */
45
class Application extends BaseApplication implements AuthenticationServiceProviderInterface {
46
47
    /**
48
     * Load all the application configuration and bootstrap logic.
49
     *
50
     * @return void
51
     */
52 19
    public function bootstrap(): void {
53
        // Call parent to load bootstrap from files.
54 19
        parent::bootstrap();
55
56 19
        if (PHP_SAPI === 'cli') {
57 19
            $this->bootstrapCli();
58
        }
59
60
        /*
61
         * Only try to load DebugKit in development mode
62
         * Debug Kit should not be installed on a production system
63
         */
64 18
        if (Configure::read('debug')) {
65 17
            $this->addPlugin('DebugKit');
66
        }
67
68
        // Load more plugins here
69 18
        $this->addPlugin('Authentication');
70 18
    }
71
72
    /**
73
     * Setup the middleware queue your application will use.
74
     *
75
     * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
76
     * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
77
     */
78 18
    public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue {
79
        $middlewareQueue
80
                // Catch any exceptions in the lower layers,
81
                // and make an error page/response
82 18
                ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
83
84
                // Handle plugin/theme assets like CakePHP normally does.
85 18
                ->add(new AssetMiddleware([
86 18
                            'cacheTime' => Configure::read('Asset.cacheTime'),
87
                        ]))
88
89
                // Add routing middleware.
90
                // If you have a large number of routes connected, turning on routes
91
                // caching in production could improve performance. For that when
92
                // creating the middleware instance specify the cache config name by
93
                // using it's second constructor argument:
94
                // `new RoutingMiddleware($this, '_cake_routes_')`
95 18
                ->add(new RoutingMiddleware($this))
96
97
                // Parse various types of encoded request bodies so that they are
98
                // available as array through $request->getData()
99
                // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
100 18
                ->add(new BodyParserMiddleware())
101
102
                // Cross Site Request Forgery (CSRF) Protection Middleware
103
                // https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware
104 18
                ->add(new CsrfProtectionMiddleware([
105 18
                            'httponly' => true,
106
                        ]))
107 18
                ->add(new AuthenticationMiddleware($this));
108
109 18
        return $middlewareQueue;
110
    }
111
112
    /**
113
     * Bootrapping for CLI application.
114
     *
115
     * That is when running commands.
116
     *
117
     * @return void
118
     */
119 19
    protected function bootstrapCli(): void {
120
        try {
121 19
            $this->addPlugin('Bake');
122 1
        } catch (MissingPluginException $e) {
123
            // Do not halt if the plugin is missing
124
        }
125
126 18
        $this->addPlugin('Migrations');
127
128
        // Load more plugins here
129 18
    }
130
131
    /**
132
     * Returns a service provider instance.
133
     *
134
     * @param \Psr\Http\Message\ServerRequestInterface $request Request
135
     * @return \Authentication\AuthenticationServiceInterface
136
     */
137 16
    public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface {
138 16
        $service = new AuthenticationService();
139
140
        // Define where users should be redirected to when they are not authenticated
141 16
        $service->setConfig([
142 16
            'unauthenticatedRedirect' => Router::url([
143 16
                'prefix' => 'Admin',
144
                'plugin' => null,
145
                'controller' => 'Users',
146
                'action' => 'login',
147
            ]),
148 16
            'queryParam' => 'redirect',
149
        ]);
150
151
        $fields = [
152 16
            IdentifierInterface::CREDENTIAL_USERNAME => 'email',
153 16
            IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
154
        ];
155
        // Load the authenticators. Session should be first.
156 16
        $service->loadAuthenticator('Authentication.Session');
157 16
        $service->loadAuthenticator('Authentication.Form', [
158 16
            'fields' => $fields,
159 16
            'loginUrl' => Router::url([
160 16
                'prefix' => 'Admin',
161
                'plugin' => null,
162
                'controller' => 'Users',
163
                'action' => 'login',
164
            ]),
165
        ]);
166
167
        // Load identifiers
168 16
        $service->loadIdentifier('Authentication.Password', compact('fields'));
169
170 16
        return $service;
171
    }
172
173
}
174