Module.php 9.15 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
2
3
4
5
6
7
<?php

/**
 * Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
 * OPEN 2.0
 *
 *
waltermazza's avatar
waltermazza committed
8
 * @package    arter\amos\socialauth
Marcello Pivanti's avatar
Marcello Pivanti committed
9
10
11
12
 * @category   CategoryName
 * @author     Elite Division S.r.l.
 */

waltermazza's avatar
waltermazza committed
13
namespace arter\amos\socialauth;
Marcello Pivanti's avatar
Marcello Pivanti committed
14

waltermazza's avatar
waltermazza committed
15
16
17
18
use arter\amos\admin\AmosAdmin;
use arter\amos\core\module\AmosModule;
use arter\amos\socialauth\controllers\ShibbolethController;
use arter\amos\socialauth\models\SocialAuthServices;
Marcello Pivanti's avatar
Marcello Pivanti committed
19
20
21
22
23
24
use Yii;
use yii\base\BootstrapInterface;
use yii\helpers\ArrayHelper;

/**
 * Class Module
waltermazza's avatar
waltermazza committed
25
 * @package arter\amos\socialauth
Marcello Pivanti's avatar
Marcello Pivanti committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
 */
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;

    /**
     * @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
86
    public $controllerNamespace = 'arter\amos\socialauth\controllers';
Marcello Pivanti's avatar
Marcello Pivanti committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100

    public $timeout = 180;

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

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
waltermazza's avatar
waltermazza committed
101
        \Yii::setAlias('@arter/amos/' . static::getModuleName() . '/controllers', __DIR__ . '/controllers');
Marcello Pivanti's avatar
Marcello Pivanti committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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

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

    /**
     * @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);

        //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);
        }
    }
}