Completed
Push — develop ( 9a4c4c...0bcb7f )
by Abdelrahman
02:08
created

AuthServiceProvider::overrideMiddleware()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Auth\Providers;
6
7
use Bouncer;
8
use Cortex\Auth\Models\Role;
9
use Illuminate\Http\Request;
10
use Cortex\Auth\Models\Admin;
11
use Cortex\Auth\Models\Member;
12
use Illuminate\Routing\Router;
13
use Cortex\Auth\Models\Ability;
14
use Cortex\Auth\Models\Manager;
15
use Cortex\Auth\Models\Session;
16
use Cortex\Auth\Models\Guardian;
17
use Cortex\Auth\Models\Socialite;
18
use Illuminate\Support\ServiceProvider;
19
use Cortex\Auth\Handlers\GenericHandler;
20
use Cortex\Auth\Console\Commands\SeedCommand;
21
use Cortex\Auth\Http\Middleware\Reauthenticate;
22
use Cortex\Auth\Console\Commands\InstallCommand;
23
use Cortex\Auth\Console\Commands\MigrateCommand;
24
use Cortex\Auth\Console\Commands\PublishCommand;
25
use Cortex\Auth\Console\Commands\RollbackCommand;
26
use Cortex\Auth\Http\Middleware\UpdateLastActivity;
27
use Illuminate\Database\Eloquent\Relations\Relation;
28
use Cortex\Auth\Http\Middleware\RedirectIfAuthenticated;
29
30
class AuthServiceProvider extends ServiceProvider
31
{
32
    /**
33
     * The commands to be registered.
34
     *
35
     * @var array
36
     */
37
    protected $commands = [
38
        SeedCommand::class => 'command.cortex.auth.seed',
39
        InstallCommand::class => 'command.cortex.auth.install',
40
        MigrateCommand::class => 'command.cortex.auth.migrate',
41
        PublishCommand::class => 'command.cortex.auth.publish',
42
        RollbackCommand::class => 'command.cortex.auth.rollback',
43
    ];
44
45
    /**
46
     * Register any application services.
47
     *
48
     * This service provider is a great spot to register your various container
49
     * bindings with the application. As you can see, we are registering our
50
     * "Registrar" implementation here. You can add your own bindings too!
51
     *
52
     * @return void
53
     */
54
    public function register(): void
55
    {
56
        // Merge config
57
        $this->app['config']->set('auth.model', config('cortex.auth.models.member'));
58
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'cortex.auth');
59
60
        // Register console commands
61
        ! $this->app->runningInConsole() || $this->registerCommands();
62
63
        // Bind eloquent models to IoC container
64
        $this->app->singleton('cortex.auth.session', $sessionModel = $this->app['config']['cortex.auth.models.session']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
65
        $sessionModel === Session::class || $this->app->alias('cortex.auth.session', Session::class);
66
67
        $this->app->singleton('cortex.auth.socialite', $socialiteModel = $this->app['config']['cortex.auth.models.socialite']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
68
        $socialiteModel === Socialite::class || $this->app->alias('cortex.auth.socialite', Socialite::class);
69
70
        $this->app->singleton('cortex.auth.admin', $adminModel = $this->app['config']['cortex.auth.models.admin']);
71
        $adminModel === Admin::class || $this->app->alias('cortex.auth.admin', Admin::class);
72
73
        $this->app->singleton('cortex.auth.member', $memberModel = $this->app['config']['cortex.auth.models.member']);
74
        $memberModel === Member::class || $this->app->alias('cortex.auth.member', Member::class);
75
76
        $this->app->singleton('cortex.auth.manager', $managerModel = $this->app['config']['cortex.auth.models.manager']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
77
        $managerModel === Manager::class || $this->app->alias('cortex.auth.manager', Manager::class);
78
79
        $this->app->singleton('cortex.auth.guardian', $guardianModel = $this->app['config']['cortex.auth.models.guardian']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
80
        $guardianModel === Guardian::class || $this->app->alias('cortex.auth.guardian', Guardian::class);
81
82
        $this->app->singleton('cortex.auth.role', $roleModel = $this->app['config']['cortex.auth.models.role']);
83
        $roleModel === Role::class || $this->app->alias('cortex.auth.role', Role::class);
84
85
        $this->app->singleton('cortex.auth.ability', $abilityModel = $this->app['config']['cortex.auth.models.ability']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
86
        $abilityModel === Ability::class || $this->app->alias('cortex.auth.ability', Ability::class);
87
    }
88
89
    /**
90
     * Bootstrap any application services.
91
     *
92
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
93
     *
94
     * @return void
95
     */
96
    public function boot(Router $router): void
97
    {
98
        // Attach request macro
99
        $this->attachRequestMacro();
100
101
        // Map bouncer models
102
        Bouncer::useRoleModel(config('cortex.auth.models.role'));
103
        Bouncer::useUserModel(config('cortex.auth.models.member'));
104
        Bouncer::useAbilityModel(config('cortex.auth.models.ability'));
105
106
        // Map bouncer tables (users, roles, abilities tables are set through their models)
107
        Bouncer::tables([
108
            'permissions' => config('cortex.auth.tables.permissions'),
109
            'assigned_roles' => config('cortex.auth.tables.assigned_roles'),
110
        ]);
111
112
        // Bind route models and constrains
113
        $router->pattern('role', '[0-9]+');
114
        $router->pattern('ability', '[0-9]+');
115
        $router->pattern('session', '[a-zA-Z0-9]+');
116
        $router->pattern('admin', '[a-zA-Z0-9_-]+');
117
        $router->pattern('member', '[a-zA-Z0-9_-]+');
118
        $router->pattern('manager', '[a-zA-Z0-9_-]+');
119
        $router->model('role', config('cortex.auth.models.role'));
120
        $router->model('admin', config('cortex.auth.models.admin'));
121
        $router->model('member', config('cortex.auth.models.member'));
122
        $router->model('manager', config('cortex.auth.models.manager'));
123
        $router->model('guardian', config('cortex.auth.models.guardian'));
124
        $router->model('ability', config('cortex.auth.models.ability'));
125
        $router->model('session', config('cortex.auth.models.session'));
126
127
        // Map relations
128
        Relation::morphMap([
129
            'role' => config('cortex.auth.models.role'),
130
            'admin' => config('cortex.auth.models.admin'),
131
            'member' => config('cortex.auth.models.member'),
132
            'manager' => config('cortex.auth.models.manager'),
133
            'guardian' => config('cortex.auth.models.guardian'),
134
            'ability' => config('cortex.auth.models.ability'),
135
        ]);
136
137
        // Load resources
138
        require __DIR__.'/../../routes/breadcrumbs.php';
139
        $this->loadRoutesFrom(__DIR__.'/../../routes/web.php');
140
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'cortex/auth');
141
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'cortex/auth');
142
        ! $this->app->runningInConsole() || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
143
        $this->app->afterResolving('blade.compiler', function () {
144
            require __DIR__.'/../../routes/menus.php';
145
        });
146
147
        // Publish Resources
148
        ! $this->app->runningInConsole() || $this->publishResources();
149
150
        // Register event handlers
151
        $this->app['events']->subscribe(GenericHandler::class);
152
153
        // Register attributes entities
154
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('admin');
155
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('member');
156
        ! app()->bound('rinvex.attributes.entities') || app('rinvex.attributes.entities')->push('manager');
157
158
        // Override middlware
159
        $this->overrideMiddleware($router);
160
161
        // Register menus
162
        $this->registerMenus();
163
164
        // Share current user instance with all views
165
        $this->app['view']->composer('*', function ($view) {
166
            ! config('rinvex.tenants.active') || $view->with('currentTenant', config('rinvex.tenants.active'));
167
            $view->with('currentUser', auth()->guard(request()->route('guard'))->user());
0 ignored issues
show
Bug introduced by
The method guard does only exist in Illuminate\Contracts\Auth\Factory, but not in Illuminate\Contracts\Auth\Guard.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
168
        });
169
    }
170
171
    /**
172
     * Publish resources.
173
     *
174
     * @return void
175
     */
176
    protected function publishResources(): void
177
    {
178
        $this->publishes([realpath(__DIR__.'/../../config/config.php') => config_path('cortex.auth.php')], 'cortex-auth-config');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 129 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
179
        $this->publishes([realpath(__DIR__.'/../../database/migrations') => database_path('migrations')], 'cortex-auth-migrations');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 132 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
180
        $this->publishes([realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/cortex/auth')], 'cortex-auth-lang');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
181
        $this->publishes([realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/cortex/auth')], 'cortex-auth-views');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 137 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
182
    }
183
184
    /**
185
     * Register console commands.
186
     *
187
     * @return void
188
     */
189
    protected function registerCommands(): void
190
    {
191
        // Register artisan commands
192
        foreach ($this->commands as $key => $value) {
193
            $this->app->singleton($value, $key);
194
        }
195
196
        $this->commands(array_values($this->commands));
197
    }
198
199
    /**
200
     * Register console commands.
201
     *
202
     * @return void
203
     */
204
    protected function attachRequestMacro(): void
205
    {
206
        Request::macro('attemptUser', function (string $guard = null) {
207
            $twofactor = $this->session()->get('cortex.auth.twofactor');
0 ignored issues
show
Bug introduced by
The method session() does not seem to exist on object<Cortex\Auth\Providers\AuthServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
208
209
            return auth()->guard($guard)->getProvider()->retrieveById($twofactor['user_id']);
0 ignored issues
show
Bug introduced by
The method guard does only exist in Illuminate\Contracts\Auth\Factory, but not in Illuminate\Contracts\Auth\Guard.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
210
        });
211
    }
212
213
    /**
214
     * Register menus.
215
     *
216
     * @return void
217
     */
218
    protected function registerMenus(): void
219
    {
220
        $this->app['rinvex.menus.presenters']->put('account.sidebar', \Cortex\Auth\Presenters\AccountSidebarMenuPresenter::class);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
221
    }
222
223
    /**
224
     * Override middleware.
225
     *
226
     * @param \Illuminate\Routing\Router $router
227
     *
228
     * @return void
229
     */
230
    protected function overrideMiddleware(Router $router): void
231
    {
232
        // Append middleware to the 'web' middlware group
233
        $router->pushMiddlewareToGroup('web', UpdateLastActivity::class);
234
235
        // Override route middleware on the fly
236
        $router->aliasMiddleware('reauthenticate', Reauthenticate::class);
237
        $router->aliasMiddleware('guest', RedirectIfAuthenticated::class);
238
    }
239
}
240