Module.php 10.4 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
2
<?php
/**
3
4
5
 * Copyright 2020 Art-ER S. Cons. P.A.
 * EROI - Emilia Romagna Open Innovation is based on:
 * https://www.open2.0.regione.lombardia.it
Marcello Pivanti's avatar
Marcello Pivanti committed
6
 *
Aster's avatar
Aster committed
7
 * @see http://example.com Developers'community
8
9
 * @license GPLv3
 * @license https://opensource.org/licenses/gpl-3.0.html GNU General Public License version 3
Marcello Pivanti's avatar
Marcello Pivanti committed
10
 *
waltermazza's avatar
waltermazza committed
11
 * @package    arter\amos\socialauth
Marcello Pivanti's avatar
Marcello Pivanti committed
12
13
14
15
 * @category   CategoryName
 * @author     Elite Division S.r.l.
 */

waltermazza's avatar
waltermazza committed
16
namespace arter\amos\socialauth;
Marcello Pivanti's avatar
Marcello Pivanti committed
17

waltermazza's avatar
waltermazza committed
18
use arter\amos\admin\AmosAdmin;
Aster's avatar
Aster committed
19
use arter\amos\admin\models\UserProfile;
waltermazza's avatar
waltermazza committed
20
21
22
use arter\amos\core\module\AmosModule;
use arter\amos\socialauth\controllers\ShibbolethController;
use arter\amos\socialauth\models\SocialAuthServices;
Aster's avatar
Aster committed
23
use arter\amos\socialauth\utility\SocialAuthUtility;
Marcello Pivanti's avatar
Marcello Pivanti committed
24
25
use Yii;
use yii\base\BootstrapInterface;
Aster's avatar
Aster committed
26
use yii\base\Event;
Marcello Pivanti's avatar
Marcello Pivanti committed
27
28
29
30
use yii\helpers\ArrayHelper;

/**
 * Class Module
waltermazza's avatar
waltermazza committed
31
 * @package arter\amos\socialauth
Marcello Pivanti's avatar
Marcello Pivanti committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 */
class Module extends AmosModule implements BootstrapInterface
{
    public static $CONFIG_FOLDER = 'config';

    /**
     * @var array providers configuration
     */
    public $providers = [];

    /**
     * @var $enableLogin bool Is Login With Social Enabled?
     */
    public $enableLogin;

    /**
     * @var $enableSpid bool Is Login With Spid Enabled?
     */
    public $enableSpid = false;

Aster's avatar
Aster committed
52
53
54
55
56
    public $shibbolethConfig = [
        'buttonLabel' => '#fullsize_login_spid_text',
        'buttonDescription' => '#fullsize_login_spid_text_right'
    ];

Marcello Pivanti's avatar
Marcello Pivanti committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    /**
     * @var $enableLogin bool Is Social Account Link Enabled?
     */
    public $enableLink;

    /**
     * @var $enableLogin bool Is Social registration Enabled?
     */
    public $enableRegister;

    /**
     * @var bool Decide if the overload security is enabled (false) or user can be oberloaded by social (true)
     */
    public $userOverload = false;

    /**
     * @var bool $enableServices - array with enabled service names
     */
    public $enableServices = ['calendar', 'contacts'];

    /**
     * @inheritdoc
     */
    public $name = 'socialauth';

    /**
     * @var string $moduleName
     */
    private static $moduleName = 'socialauth';

    /**
     * @var string|boolean the layout that should be applied for views within this module. This refers to a view name
     * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
     * will be taken. If this is false, layout will be disabled within this module.
     */
    public $layout = 'main';

    /**
     * @inheritdoc
     */
waltermazza's avatar
waltermazza committed
97
    public $controllerNamespace = 'arter\amos\socialauth\controllers';
Marcello Pivanti's avatar
Marcello Pivanti committed
98
99
100
101
102
103
104
105

    public $timeout = 180;

    /**
     * @var bool $enableSpidMultiUsersSameCF If true the model validation doesn't check the unique of che fiscal code.
     */
    public $enableSpidMultiUsersSameCF = false;

Aster's avatar
Aster committed
106
107
108
109
110
111
112
113
114
115
    /**
     * @var bool $shibbolethAutoLogin if true on shibboleth controller make automatic login
     */
    public $shibbolethAutoLogin = false;

    /**
     * @var bool $shibbolethAutoRegistration if true on shibboleth controller make automatic registration
     */
    public $shibbolethAutoRegistration = false;

Marcello Pivanti's avatar
Marcello Pivanti committed
116
117
118
119
120
121
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
waltermazza's avatar
waltermazza committed
122
        \Yii::setAlias('@arter/amos/' . static::getModuleName() . '/controllers', __DIR__ . '/controllers');
Marcello Pivanti's avatar
Marcello Pivanti committed
123
124
125
126
127
128

        //Configuration
        $config = require(__DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php');
        \Yii::configure($this, ArrayHelper::merge($config, $this));
    }

Aster's avatar
Aster committed
129
130
131
132
133
134
135
136
137
138
139
    /**
     * @inheritdoc
     */
    public static function getInstance() {
        if(Yii::$app->session->has('socialAuthInstance')) {
            return Yii::$app->getModule(Yii::$app->session->get('socialAuthInstance'));
        }

        return parent::getInstance();
    }

Marcello Pivanti's avatar
Marcello Pivanti committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    /**
     * @return array
     */
    public function getProviders()
    {
        return $this->providers;
    }

    /**
     * @inheritdoc
     */
    public static function getModuleName()
    {
        return static::$moduleName;
    }

    /**
     * @inheritdoc
     */
    public function getWidgetIcons()
    {
        return [
        ];
    }

    /**
     * @inheritdoc
     */
    public function getWidgetGraphics()
    {
        return [
        ];
    }

    /**
     * @inheritdoc
     */
    protected function getDefaultModels()
    {
        return [
        ];
    }

    /**
     * @param string $provider
     * @param null|SocialAuthServices $service
     * @return \Google_Client|null
     */
    public function getClient($provider = 'google', $service = null)
    {
        $providers = $this->providers;
        $client = null;
        if ($provider == 'google') {
            if (!empty($providers) && array_key_exists('Google', $providers)) {
                $key = $providers['Google']['keys']['secret'];
                $clientId = $providers['Google']['keys']['id'];
                $client = new \Google_Client();
                $client->setClientId($clientId);
                $client->setClientSecret($key);
                if (!is_null($service)) {
                    $accessToken['access_token'] = $service->access_token;
                    $accessToken['token_type'] = $service->token_type;
                    $accessToken['expires_in'] = $service->expires_in;
                    $accessToken['created'] = $service->token_created;
                    $client->setAccessToken($accessToken);
                    // Refresh the token if it's expired.
                    if ($client->isAccessTokenExpired()) {
                        $accessToken = $client->fetchAccessTokenWithRefreshToken($service->refresh_token);
                        $service->access_token = $accessToken['access_token'];
                        $service->token_type = $accessToken['token_type'];
                        $service->expires_in = $accessToken['expires_in'];
                        $service->token_created = $accessToken['created'];
                        if (!$service->save()) {
                            \Yii::$app->session->addFlash('danger', Module::t('amossocialauth',
                                'An error occurred while synchronizing {provider} {serviceName}',
                                ['provider' => $provider, 'serviceName' => $service->service]));
                        }
                    }
                }
            }
        }
        return $client;
    }

    /**
     * @param SocialAuthServices $service
     * @return string $message
     */
    public function synchronizeGoogleService($service)
    {
        $message = '';
        $client = $this->getClient('google', $service);
        if ($service->service == 'calendar') {
            $serviceGoogle = new \Google_Service_Calendar($client);
            $calendarId = $service->service_id;
            if (empty($calendarId)) {
                $calendar = new \Google_Service_Calendar_Calendar();
                $calendar->setSummary(\Yii::$app->name);
                $calendar = $serviceGoogle->calendars->insert($calendar);
                $calendarId = $calendar->getId();

                $service->service_id = $calendarId;
                $service->save(false);
                $message = Module::t('amossocialauth', 'Calendar \'{appName}\' has been added successfully to your Google Account.', ['appName' => \Yii::$app->name]);
            } else {
                $message .= Module::t('amossocialauth', 'Calendar \'{appName}\' synchronization', ['appName' => \Yii::$app->name]);
            }

            $eventsModule = Yii::$app->getModule('events');
            if (!is_null($eventsModule)) {
                return $eventsModule->synchronizeEvents($serviceGoogle, $calendarId, $message);
            }
        } elseif ($service->service == 'contacts') {
            $serviceGoogle = new \Google_Service_PeopleService($client);
            $message = AmosAdmin::synchronizeGoogleContacts($serviceGoogle);
        }
        return $message;
    }

    /**
     * @param SocialAuthServices $service
     * @return string
     */
    public function removeGoogleService($service)
    {
        $message = '';
        $client = $this->getClient();
        $accessToken['access_token'] = $service->access_token;
        $accessToken['token_type'] = $service->token_type;
        $accessToken['expires_in'] = $service->expires_in;
        $accessToken['created'] = $service->token_created;
        $client->setAccessToken($accessToken);
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $accessToken = $client->fetchAccessTokenWithRefreshToken($service->refresh_token);
            $service->access_token = $accessToken['access_token'];
            $service->token_type = $accessToken['token_type'];
            $service->expires_in = $accessToken['expires_in'];
            $service->token_created = $accessToken['created'];
            if (!$service->save()) {
                $message = Module::t('amosadmin', 'Errore durante l\'aggiornamento delle impostazioni');
            }
        }
        if ($service->service == 'calendar') {
            $message .= ' calendar : ';
            $serviceGoogle = new \Google_Service_Calendar($client);
            $calendarId = $service->service_id;
            if (!empty($calendarId)) {
                $calendar = $serviceGoogle->calendars->get($calendarId);
                if ($calendar) {
                    $message .= $calendarId . ' ';
                }
            }
            $serviceGoogle->calendars->delete($calendarId);
        } elseif ($service->service == 'contacts') {
            AmosAdmin::removeGoogleContacts();
        }
        return $message;
    }

    /**
     * @inheritdoc
     */
    public function bootstrap($app)
    {
        //Init a new shibboleth controller to link user
        $shibbolethController = new ShibbolethController('shibboleth', $this);

Aster's avatar
Aster committed
308
309
        Event::on(AmosAdmin::instance()->model('UserProfile'), UserProfile::EVENT_AFTER_INSERT, ['arter\amos\socialauth\utility\SocialAuthUtility', 'createIdmUser']);

Marcello Pivanti's avatar
Marcello Pivanti committed
310
311
312
313
314
315
316
317
318
319
320
        //Get Session IDM datas (copy of headers)
        $sessionIDM = \Yii::$app->session->get('IDM');

        //Link to current user with IDM
        if ($sessionIDM && $sessionIDM['matricola']) {
            return $shibbolethController->tryIdmLink('idm', $sessionIDM, false, false);
        } else if ($sessionIDM && $sessionIDM['saml_attribute_codicefiscale']) {
            return $shibbolethController->tryIdmLink('spid', $sessionIDM, false, false);
        }
    }
}