Completed
Push — master ( b42a23...f9e78a )
by Abdelrahman
07:26
created

FortServiceProvider::overrideTokenGuard()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * NOTICE OF LICENSE
5
 *
6
 * Part of the Rinvex Fort Package.
7
 *
8
 * This source file is subject to The MIT License (MIT)
9
 * that is bundled with this package in the LICENSE file.
10
 *
11
 * Package: Rinvex Fort Package
12
 * License: The MIT License (MIT)
13
 * Link:    https://rinvex.com
14
 */
15
16
namespace Rinvex\Fort\Providers;
17
18
use Illuminate\Routing\Router;
19
use Collective\Html\FormFacade;
20
use Collective\Html\HtmlFacade;
21
use Illuminate\Support\Facades\Auth;
22
use Rinvex\Fort\Guards\SessionGuard;
23
use Rinvex\Fort\Guards\TokenGuard;
24
use Rinvex\Fort\Services\AccessGate;
25
use Illuminate\Foundation\AliasLoader;
26
use Rinvex\Repository\Traits\Bindable;
27
use Rinvex\Fort\Services\BrokerManager;
28
use Illuminate\Support\ServiceProvider;
29
use Collective\Html\HtmlServiceProvider;
30
use Rinvex\Fort\Listeners\FortEventListener;
31
use Illuminate\View\Compilers\BladeCompiler;
32
use Rinvex\Fort\Repositories\UserRepository;
33
use Rinvex\Fort\Repositories\RoleRepository;
34
use Laravel\Socialite\SocialiteServiceProvider;
35
use Rinvex\Fort\Repositories\AbilityRepository;
36
use Rinvex\Fort\Repositories\PersistenceRepository;
37
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
38
39
class FortServiceProvider extends ServiceProvider
40
{
41
    use Bindable;
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function register()
47
    {
48
        // Merge config
49
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.fort');
50
51
        // Register bindings
52
        $this->registerAccessGate();
53
        $this->registerRepositories();
54
        $this->registerBrokerManagers();
55
        $this->registerBladeExtensions();
56
57
        // Register the event listener
58
        $this->app->bind('rinvex.fort.listener', FortEventListener::class);
59
60
        // Register the Socialite Service Provider
61
        $this->app->register(SocialiteServiceProvider::class);
62
63
        // Register the LaravelCollective HTML Service Provider
64
        $this->app->register(HtmlServiceProvider::class);
65
66
        // Alias the LaravelCollective Form & HTML Facades
67
        AliasLoader::getInstance()->alias('Form', FormFacade::class);
68
        AliasLoader::getInstance()->alias('Html', HtmlFacade::class);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function boot(Router $router)
75
    {
76
        // Publish Resources
77
        $this->publishResources();
78
79
        // Add middleware group on the fly
80
        $router->middlewareGroup('rinvex.fort.backend', [
81
            \App\Http\Middleware\EncryptCookies::class,
82
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
83
            \Illuminate\Session\Middleware\StartSession::class,
84
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
85
            \App\Http\Middleware\VerifyCsrfToken::class,
86
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
87
            \Rinvex\Fort\Http\Middleware\Abilities::class,
88
        ]);
89
90
        // Override route middleware on the fly
91
        $router->middleware('auth', \Rinvex\Fort\Http\Middleware\Authenticate::class);
92
        $router->middleware('guest', \Rinvex\Fort\Http\Middleware\RedirectIfAuthenticated::class);
93
94
        // Load routes
95
        $this->loadRoutes($router);
96
97
        // Override exception handler
98
        $this->app->singleton(
99
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
100
            \Rinvex\Fort\Exceptions\ExceptionHandler::class
101
        );
102
103
        // Load views
104
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'rinvex/fort');
105
106
        // Load language phrases
107
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'rinvex/fort');
108
109
        // Load migrations
110
        $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
111
112
        // Subscribe the registered event listener
113
        $this->app['events']->subscribe('rinvex.fort.listener');
114
115
        // Override user provider
116
        $this->overrideUserProvider();
117
118
        // Override session guard
119
        $this->overrideSessionGuard();
120
121
        // Override token guard
122
        $this->overrideTokenGuard();
123
124
        // Share current user instance with all views
125
        $this->app['view']->composer('*', function ($view) {
126
            $view->with('currentUser', Auth::user());
127
        });
128
    }
129
130
    /**
131
     * Register the access gate service.
132
     *
133
     * @return void
134
     */
135
    protected function registerAccessGate()
136
    {
137
        $this->app->singleton(GateContract::class, function ($app) {
138
            return new AccessGate($app, function () use ($app) {
139
                return call_user_func($app['auth']->userResolver());
140
            });
141
        });
142
    }
143
144
    /**
145
     * Bind the repositories into the IoC.
146
     *
147
     * @return void
148
     */
149
    protected function registerRepositories()
150
    {
151
        $this->bindRepository('rinvex.fort.role', RoleRepository::class);
152
        $this->bindRepository('rinvex.fort.user', UserRepository::class);
153
        $this->bindRepository('rinvex.fort.ability', AbilityRepository::class);
154
        $this->bindRepository('rinvex.fort.persistence', PersistenceRepository::class);
155
    }
156
157
    /**
158
     * Register the broker managers.
159
     *
160
     * @return void
161
     */
162
    protected function registerBrokerManagers()
163
    {
164
        // Register reset broker manager
165
        $this->app->singleton('rinvex.fort.passwordreset', function ($app) {
166
            return new BrokerManager($app, 'PasswordReset');
167
        });
168
169
        // Register verification broker manager
170
        $this->app->singleton('rinvex.fort.emailverification', function ($app) {
171
            return new BrokerManager($app, 'EmailVerification');
172
        });
173
    }
174
175
    /**
176
     * Register the blade extensions.
177
     *
178
     * @return void
179
     */
180
    protected function registerBladeExtensions()
181
    {
182
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
183
184
            // @role('writer') / @hasrole(['writer', 'editor'])
185
            $bladeCompiler->directive('role', function ($roles) {
186
                return "<?php if(auth()->user()->hasRole({$roles})): ?>";
187
            });
188
            $bladeCompiler->directive('endrole', function () {
189
                return '<?php endif; ?>';
190
            });
191
192
            // @hasrole('writer') / @hasrole(['writer', 'editor'])
193
            $bladeCompiler->directive('hasrole', function ($roles) {
194
                return "<?php if(auth()->user()->hasRole({$roles})): ?>";
195
            });
196
            $bladeCompiler->directive('endhasrole', function () {
197
                return '<?php endif; ?>';
198
            });
199
200
            // @hasanyrole(['writer', 'editor'])
201
            $bladeCompiler->directive('hasanyrole', function ($roles) {
202
                return "<?php if(auth()->user()->hasAnyRole({$roles})): ?>";
203
            });
204
            $bladeCompiler->directive('endhasanyrole', function () {
205
                return '<?php endif; ?>';
206
            });
207
208
            // @hasallroles(['writer', 'editor'])
209
            $bladeCompiler->directive('hasallroles', function ($roles) {
210
                return "<?php if(auth()->user()->hasAllRoles({$roles})): ?>";
211
            });
212
            $bladeCompiler->directive('endhasallroles', function () {
213
                return '<?php endif; ?>';
214
            });
215
        });
216
    }
217
218
    /**
219
     * Publish resources.
220
     *
221
     * @return void
222
     */
223
    protected function publishResources()
224
    {
225
        // Publish config
226
        $this->publishes([
227
            realpath(__DIR__.'/../../config/config.php') => config_path('rinvex.fort.php'),
228
        ], 'config');
229
230
        // Publish migrations
231
        $this->publishes([
232
            realpath(__DIR__.'/../../database/migrations') => database_path('migrations'),
233
        ], 'migrations');
234
235
        // Publish language phrases
236
        $this->publishes([
237
            realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/rinvex/fort'),
238
        ], 'lang');
239
240
        // Publish views
241
        $this->publishes([
242
            realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/rinvex/fort'),
243
        ], 'views');
244
    }
245
246
    /**
247
     * Load the routes.
248
     *
249
     * @param \Illuminate\Routing\Router $router
250
     *
251
     * @return void
252
     */
253
    public function loadRoutes(Router $router)
254
    {
255
        // Load routes
256
        if ($this->app->routesAreCached()) {
257
            $this->app->booted(function () {
258
                require $this->app->getCachedRoutesPath();
259
            });
260
        } else {
261
            // Load the application routes
262
            require __DIR__.'/../../routes/web.backend.php';
263
            require __DIR__.'/../../routes/web.frontend.php';
264
265
            $this->app->booted(function () use ($router) {
266
                $router->getRoutes()->refreshNameLookups();
267
            });
268
        }
269
    }
270
271
    /**
272
     * Add custom user provider.
273
     *
274
     * @return void
275
     */
276
    protected function overrideUserProvider()
277
    {
278
        $this->app['auth']->provider('eloquent', function ($app, array $config) {
0 ignored issues
show
Unused Code introduced by
The parameter $app is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
279
            // Return an instance of Rinvex\Fort\Contracts\UserRepositoryContract
280
            return $this->app['rinvex.fort.user'];
281
        });
282
    }
283
284
    /**
285
     * Override session guard.
286
     *
287
     * @return void
288
     */
289
    protected function overrideSessionGuard()
290
    {
291
        // Add custom session guard
292
        $this->app['auth']->extend('session', function ($app, $name, array $config) {
293
            $provider = $app['auth']->createUserProvider($config['provider']);
294
295
            $guard = new SessionGuard($name, $provider, $app['session.store'], $app['request']);
296
297
            // When using the remember me functionality of the authentication services we
298
            // will need to be set the encryption instance of the guard, which allows
299
            // secure, encrypted cookie values to get generated for those cookies.
300
            if (method_exists($guard, 'setCookieJar')) {
301
                $guard->setCookieJar($this->app['cookie']);
302
            }
303
304
            if (method_exists($guard, 'setDispatcher')) {
305
                $guard->setDispatcher($this->app['events']);
306
            }
307
308
            if (method_exists($guard, 'setRequest')) {
309
                $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
310
            }
311
312
            return $guard;
313
        });
314
    }
315
316
    /**
317
     * Override Token guard.
318
     *
319
     * @return void
320
     */
321
    protected function overrideTokenGuard()
322
    {
323
        // Add custom session guard
324
        $this->app['auth']->extend('token', function ($app, $name, array $config) {
325
            // The token guard implements a basic API token based guard implementation
326
            // that takes an API token field from the request and matches it to the
327
            // user in the database or another persistence layer where users are.
328
            $guard = new TokenGuard(
329
                $app['auth']->createUserProvider($config['provider']),
330
                $app['request']
331
            );
332
333
            $app->refresh('request', $guard, 'setRequest');
334
335
            return $guard;
336
        });
337
    }
338
}
339