Passed
Push — master ( 2fde46...c4ff34 )
by meta
02:48
created

configureSwaggerToScanEnterpriseAuthRouteFiles()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 8
nop 0
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Metaclassing\EnterpriseAuth;
4
5
class ServiceProvider extends \Illuminate\Support\ServiceProvider
6
{
7
    public function register()
8
    {
9
    }
10
11
    public function boot()
12
    {
13
        // Make sure nobody is including or running this thing without all the required env settings
14
        $this->checkMandatoryConfigsAreSet();
15
16
        // Install our API auth guard middleware
17
        $this->installOauthTokenGuardMiddleware();
18
19
        // Make sure that this vendor dir and the routes dir are in any scanned paths for swagger documentation
20
        $this->configureSwaggerToScanEnterpriseAuthRouteFiles();
21
22
        // Make sure the publish command picks up our config, migration, user model, and dummy API route files
23
        $this->publishes([
24
            __DIR__.'/../publish/config/enterpriseauth.php'                                                => config_path('enterpriseauth.php'),
25
            __DIR__.'/../publish/database/migrations/2018_02_19_152839_alter_users_table_for_azure_ad.php' => $this->app->databasePath().'/migrations/2018_02_19_152839_alter_users_table_for_azure_ad.php',
26
            __DIR__.'/../publish/app/User.php'                                                             => app_path().'/User.php',
27
            __DIR__.'/../publish/routes/api.php'                                                           => base_path('routes').'/api.php',
28
        ]);
29
30
        // Merge configs with the default configs
31
        $this->mergeConfigFrom(
32
            __DIR__.'/../publish/config/enterpriseauth.php', 'enterpriseauth'
33
        );
34
35
        // Load our HTTP routes for API and WEB authentication
36
        $this->loadRoutesFrom(__DIR__.'/../routes/api.microsoft.php');
37
        $this->loadRoutesFrom(__DIR__.'/../routes/web.microsoft.php');
38
39
        // Trigger generating our swagger oauth security settings based on application env file contents
40
        $this->generateSwaggerOauthSecurityScheme();
41
    }
42
43
    protected function checkMandatoryConfigsAreSet()
44
    {
45
        // On first run this will be false, after config file is installed it will be true
46
        if (config('enterpriseauth')) {
47
            // Go through all the credential config and make sure they are set in the .env or config file
48
            foreach (config('enterpriseauth.credentials') as $config => $env) {
49
                // If one isnt set, throw a red flat until the person fixes it
50
                if (! config('enterpriseauth.credentials.'.$config)) {
51
                    throw new \Exception('enterpriseauth setup error: missing mandatory config value for enterpriseauth.credentials.'.$config.' check your .env file!');
52
                }
53
            }
54
        }
55
    }
56
57
    protected function installOauthTokenGuardMiddleware()
58
    {
59
        // Override the application configuration to use our oauth token guard driver at runtime
60
        config(['auth.guards.api.driver' => 'oauthtoken']);
61
        // Now I have a machine gun. ho ho ho!
62
        \Illuminate\Support\Facades\Auth::extend('oauthtoken', function ($app, $name, array $config) {
63
            $userProvider = \Illuminate\Support\Facades\Auth::createUserProvider($config['provider']);
64
            return new \Metaclassing\EnterpriseAuth\Middleware\OauthTokenGuard($userProvider, $app->make('request'));
65
        });
66
    }
67
68
    protected function configureSwaggerToScanEnterpriseAuthRouteFiles()
69
    {
70
        $swaggerScanPaths = config('l5-swagger.paths.annotations');
71
        if (! is_array($swaggerScanPaths)) {
72
            $swaggerScanPaths = [$swaggerScanPaths];
73
        }
74
        if (! in_array(base_path('routes'), $swaggerScanPaths)) {
75
            $swaggerScanPaths[] = base_path('routes');
76
        }
77
        if (! in_array(__DIR__.'/../routes/', $swaggerScanPaths)) {
78
            $swaggerScanPaths[] = __DIR__.'/../routes/';
79
        }
80
        config(['l5-swagger.paths.annotations' => $swaggerScanPaths]);
81
    }
82
83
    protected function generateSwaggerOauthSecurityScheme()
84
    {
85
        // If the routes files for the swagger oauth config is NOT present, and we have all the right info, then generate it really quick
86
        $swaggerAzureadFile = __DIR__.'/../routes/swagger.azuread.php';
87
        if (! file_exists($swaggerAzureadFile)) {
88
            $aad = new AzureActiveDirectory(config('enterpriseauth.credentials.tenant'));
89
            //$authorizationUrl = $aad->authorizationEndpoint . '?resource=https://graph.microsoft.com';
90
            $authorizationUrl = $aad->authorizationEndpoint;
91
            $client_id = config('enterpriseauth.credentials.client_id');
92
            $contents = <<<EOF
93
<?php
94
/**
95
 * @SWG\SecurityScheme(
96
 *   securityDefinition="AzureAD",
97
 *   type="oauth2",
98
 *   authorizationUrl="$authorizationUrl",
99
 *   flow="implicit",
100
 *   scopes={
101
 *       "https://graph.microsoft.com/.default": "Use client_id: $client_id"
102
 *   }
103
 * )
104
 **/
105
EOF;
106
            file_put_contents($swaggerAzureadFile, $contents);
107
        }
108
    }
109
}
110