ShibbolethController.php 16 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
 *
Aster's avatar
Aster 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\controllers;
Marcello Pivanti's avatar
Marcello Pivanti committed
17

Aster's avatar
Aster committed
18
use arter\amos\admin\AmosAdmin;
waltermazza's avatar
waltermazza committed
19
20
21
22
23
24
use arter\amos\admin\models\UserProfile;
use arter\amos\core\controllers\BackendController;
use arter\amos\core\user\User;
use arter\amos\socialauth\models\SocialIdmUser;
use arter\amos\socialauth\Module;
use arter\amos\socialauth\utility\SocialAuthUtility;
Marcello Pivanti's avatar
Marcello Pivanti committed
25
use Yii;
Aster's avatar
Aster committed
26
27
28
use yii\base\Action;
use yii\filters\AccessControl;
use yii\helpers\Url;
Marcello Pivanti's avatar
Marcello Pivanti committed
29
30
31

/**
 * Class ShibbolethController
waltermazza's avatar
waltermazza committed
32
 * @package arter\amos\socialauth\controllers
Marcello Pivanti's avatar
Marcello Pivanti committed
33
34
35
 */
class ShibbolethController extends BackendController
{
Aster's avatar
Aster committed
36
37
    const LOGGED_WITH_SPID_SESSION_ID = 'logged_with_spid_user_id';

Marcello Pivanti's avatar
Marcello Pivanti committed
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
    /**
     * @var string $layout
     */
    public $layout = 'login';

    /**
     * @var string $authType
     */
    protected $authType = '';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => [
                            'endpoint',
                            'mobile',
                            'sign-up',
Aster's avatar
Aster committed
63
                            'set-module-instance',
Marcello Pivanti's avatar
Marcello Pivanti committed
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
97
98
99
100
101
102
103
104
105
106
107
108
                        ],
                        //'roles' => ['*']
                    ]
                ],
            ],
        ];
    }

    /**
     *
     * @param Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

    /**
     * @inheritdoc
     */
    public function init()
    {

        parent::init();
        $this->setUpLayout('login');
        // custom initialization code goes here
    }

    /**
     * Endpoint bridge with shibbolethsp authentication
     * @param bool $confirm
     * @return bool|\yii\web\Response
     */
    public function actionEndpoint($confirm = false)
    {
        //Link to current user with IDM
        return $this->tryIdmLink($confirm);
    }

    public function actionMobile()
    {
        $result = $this->tryIdmLink(false, true, false);

Aster's avatar
Aster committed
109
        if (is_array($result) && isset($result['status'])) {
waltermazza's avatar
waltermazza committed
110
            $user = \arter\amos\mobile\bridge\modules\v1\models\User::findOne(Yii::$app->user->id);
Marcello Pivanti's avatar
Marcello Pivanti committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
            $user->refreshAccessToken('', '');

            return $this->redirect(['/socialauth/social-auth/land', 'token' => $user->getAccessToken()]);
        } else {
            return $this->redirect(['/socialauth/social-auth/land', 'error' => true]);
        }
    }

    /**
     * @param string $type
     * @param array $dataFetch
     * @return string|\yii\web\Response
     */
    public function tryIdmLink($confirmLink = false, $render = true, $redirect = true)
    {
        $procedure = $this->procedure($confirmLink, $render);
Aster's avatar
Aster committed
127
128
129
130
131
132
133
        $adminModule = AmosAdmin::getInstance();

        $urlRedirectPersonalized = \Yii::$app->session->get('redirect_url_spid');
        if (!empty($urlRedirectPersonalized)) {
            $redirect = true;
            \Yii::$app->session->remove('redirect_url_spid');
        }
Marcello Pivanti's avatar
Marcello Pivanti committed
134
135

        if (!is_array($procedure)) {
Aster's avatar
Aster committed
136
137
138
            if (!empty($urlRedirectPersonalized)) {
                return $this->redirect($urlRedirectPersonalized);
            }
Marcello Pivanti's avatar
Marcello Pivanti committed
139
140
141
            return $procedure;
        }

Aster's avatar
Aster committed
142
        if ($redirect) {
Marcello Pivanti's avatar
Marcello Pivanti committed
143
144
            switch ($procedure['status']) {
                case 'success':
Aster's avatar
Aster committed
145
                case 'rl':
Marcello Pivanti's avatar
Marcello Pivanti committed
146
147
148
149
150
                case 'fc':
                case 'ND':
                case 'override':
                case 'conf':
                    {
Aster's avatar
Aster committed
151
152
153
154
155
156
157
158
159
                        if (!empty($urlRedirectPersonalized)) {
                            return $this->redirect($urlRedirectPersonalized);
                        }
                        Yii::debug("Login Status for {$procedure['user_id']} : {$procedure['status']}");
                        return $this->goHome();                    }
                    break;
                case 'disabled':
                    \Yii::$app->session->set(self::LOGGED_WITH_SPID_SESSION_ID, $procedure['user_id']);
                    return $this->redirect(['/Shibboleth.sso/Logout', 'return' => Url::to('/'.$adminModule->id.'/login-info-request/activate-user?id=' . $procedure['user_id'], true)]);
Marcello Pivanti's avatar
Marcello Pivanti committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
                    break;
            }
        } else {
            return $procedure;
        }
    }

    protected function procedure($confirmLink = false, $render = true)
    {
        //Store data into session
        $userDatas = $this->storeDataInSession();

        //Find for existing relation
        $relation = SocialIdmUser::findOne(['numeroMatricola' => $userDatas['matricola']]);
Aster's avatar
Aster committed
174
//pr($relation->toArray());die;
Marcello Pivanti's avatar
Marcello Pivanti committed
175
        //Find by other attributes
Aster's avatar
Aster committed
176
177
178
179
180
181
182
183
        $usersByCF = [];
        $countUsersByCF = 0;

        if ($userDatas['codiceFiscale']) {
            $usersByCF = UserProfile::find()->andWhere(['codice_fiscale' => $userDatas['codiceFiscale']])->all();
            $countUsersByCF = count($usersByCF);
        }

Marcello Pivanti's avatar
Marcello Pivanti committed
184
185
186
187
188
189
        /** @var UserProfile|null $existsByFC */
        $existsByFC = (($countUsersByCF == 1) ? reset($usersByCF) : null);
        $existsByEmail = User::findOne(['email' => $userDatas['emailAddress']]);

        /** @var Module $socialAuthModule */
        $socialAuthModule = Module::instance();
Aster's avatar
Aster committed
190
        $adminModule = AmosAdmin::getInstance();
Marcello Pivanti's avatar
Marcello Pivanti committed
191
192
193
194
195
196
197
198
199
200
201

        //Get timeout for app login
        $loginTimeout = \Yii::$app->params['loginTimeout'] ?: 3600;

        if ($socialAuthModule->enableSpidMultiUsersSameCF && ($countUsersByCF > 1) && \Yii::$app->user->isGuest) {
            $post = \Yii::$app->request->post();
            if ($post && isset($post['user_by_fiscal_code'])) {
                $usersByCFUserIds = SocialAuthUtility::makeUsersByCFUserIds($usersByCF);
                if (in_array($post['user_by_fiscal_code'], $usersByCFUserIds)) {
                    $user = User::findOne($post['user_by_fiscal_code']);
                    if (!is_null($user)) {
Aster's avatar
Aster committed
202
203
204
                        //Store IDM user
                        $this->createIdmUser($userDatas, $user->id);

Marcello Pivanti's avatar
Marcello Pivanti committed
205
                        $signIn = \Yii::$app->user->login($user, $loginTimeout);
Aster's avatar
Aster committed
206

Marcello Pivanti's avatar
Marcello Pivanti committed
207
                        if ($signIn === true) {
Aster's avatar
Aster committed
208
                            SocialAuthUtility::updateFiscalCode(\Yii::$app->user->id, $userDatas['codiceFiscale']);
Marcello Pivanti's avatar
Marcello Pivanti committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

                            return ['status' => 'fc'];
                            //return $this->redirect(['/', 'done' => 'fc']);
                        } else {
                            \Yii::$app->getSession()->addFlash('danger', Module::t('amossocialauth', 'Login Failed'));
                        }
                    } else {
                        \Yii::$app->getSession()->addFlash('danger', Module::t('amossocialauth', 'User Not Found, Please try with Other User'));
                    }
                } else {
                    \Yii::$app->getSession()->addFlash('danger', Module::t('amossocialauth', 'User Not Corresponding'));
                }
            }
            // Form to select identity by fiscal code and log-in
            return $this->render('ask-which-user', [
                'userDatas' => $userDatas,
                'usersByCF' => $usersByCF
            ]);
        } elseif ($relation && $relation->id && \Yii::$app->user->isGuest) {
Aster's avatar
Aster committed
228
229
230
231
232
233
234
            if ($this->isUserDisabled($relation->user_id)) {
                return ['status' => 'disabled', 'user_id' => $relation->user_id];
            }
//pr($relation->user_id);die;
            //Store IDM user
            $this->createIdmUser($userDatas, $relation->user_id);

Marcello Pivanti's avatar
Marcello Pivanti committed
235
236
237
238
239
240
241
242
243
            //Se l'utente è già collegato logga in automatico
            $signIn = \Yii::$app->user->login($relation->user, $loginTimeout);

            //Remove session data
            \Yii::$app->session->remove('IDM');

            return ['status' => 'rl'];
            //return $this->redirect(['/', 'done' => 'rl']);
        } elseif ($existsByFC && $existsByFC->id && \Yii::$app->user->isGuest) {
Aster's avatar
Aster committed
244
245
246
            if ($this->isUserDisabled($existsByFC->user_id)) {
                return ['status' => 'disabled', 'user_id' => $existsByFC->user_id];
            }
Marcello Pivanti's avatar
Marcello Pivanti committed
247
248

            //Store IDM user
Aster's avatar
Aster committed
249
250
251
            $this->createIdmUser($userDatas, $existsByFC->user_id);

            $signIn = \Yii::$app->user->login($existsByFC->user, $loginTimeout);
Marcello Pivanti's avatar
Marcello Pivanti committed
252
253
254
255
256
257
258

            return ['status' => 'fc'];
            //return $this->redirect(['/', 'done' => 'fc']);
        } elseif ((($relation && $relation->id) || ($existsByFC && $existsByFC->id)) && !\Yii::$app->user->isGuest) {
            //User logged and idm exists, go to home, case not allowed
            //return $this->redirect(['/', 'error' => 'overload']);
        } elseif ($existsByEmail && $existsByEmail->id && \Yii::$app->user->isGuest && !$confirmLink && $render) {
Aster's avatar
Aster committed
259
260
261
262
263
            // AUTOMATIC LOGIN & AUTOMATIC REGISTRATION
            if ($socialAuthModule->shibbolethAutoLogin) {
                return $this->redirect(['/socialauth/shibboleth/endpoint', 'confirm' => true]);
            }

Marcello Pivanti's avatar
Marcello Pivanti committed
264
265
266
267
268
269
270
            //Form to confirm identity and log-in
            return $this->render('log-in', [
                'userDatas' => $userDatas,
                'userProfile' => $existsByEmail->profile,
                'authType' => $this->authType,
            ]);
        } elseif ($existsByEmail && $existsByEmail->id && \Yii::$app->user->isGuest && $confirmLink) {
Aster's avatar
Aster committed
271
272
273
            if ($this->isUserDisabled($existsByEmail->id)) {
                return ['status' => 'disabled', 'user_id' => $existsByEmail->id];
            }
Marcello Pivanti's avatar
Marcello Pivanti committed
274
275

            //Store IDM user
Aster's avatar
Aster committed
276
277
278
279
            $this->createIdmUser($userDatas, $existsByEmail->id);

            //Login
            $signIn = \Yii::$app->user->login($existsByEmail, $loginTimeout);
Marcello Pivanti's avatar
Marcello Pivanti committed
280
281
282
283

            return ['status' => 'conf'];
            //return $this->redirect(['/', 'done' => 'conf']);
        } elseif (\Yii::$app->user->isGuest && $render) {
Aster's avatar
Aster committed
284
285
286
287
288
            // AUTOMATIC LOGIN & AUTOMATIC REGISTRATION
            if ($socialAuthModule->shibbolethAutoRegistration) {
                return $this->redirect(['/'.$adminModule->id.'/security/register', 'confirm' => true]);
            }

Marcello Pivanti's avatar
Marcello Pivanti committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
            //Form to confirm identity and log-in
            return $this->render('ask-signup', [
                'userDatas' => $userDatas,
                'authType' => $this->authType,
            ]);
        } elseif (!\Yii::$app->user->isGuest) {

            //Store IDM user
            $this->createIdmUser($userDatas);

            return ['status' => 'override'];
            //return $this->redirect(['/', 'done' => 'override']);
        }

        if ($render) {
            return ['status' => 'ND'];
            //return $this->redirect(['/', 'done' => 'ND']);
        }
    }

    /**
     * @return array|mixed
     */
    public function storeDataInSession()
    {
        //Get Headers to ckeck the reverse proxy header datas
        $headers = \Yii::$app->request->getHeaders();

        //Get Session IDM datas (copy of headers)
        $sessionIDM = \Yii::$app->session->get('IDM');

        //Check what type
        if ($headers->get('serialNumber')) {
            $type = 'header_idm';
            $dataFetch = $headers;
        } else if ($headers->get('saml_attribute_codicefiscale') || $headers->get('saml-attribute-codicefiscale')) {
            $type = 'header_spid';
            $dataFetch = $headers;
        } else if ($sessionIDM && $sessionIDM['matricola']) {
            $type = 'idm';
            $dataFetch = $headers;
        } else if ($sessionIDM && $sessionIDM['saml_attribute_codicefiscale']) {
            $type = 'spid';
            $dataFetch = $sessionIDM;
        }

        if (!$sessionIDM || !$sessionIDM['matricola']) {
            $matricola = null;
            $nome = null;
            $cognome = null;
            $emailAddress = null;
            $codiceFiscale = null;
Aster's avatar
Aster committed
341
            $rawData = null;
Marcello Pivanti's avatar
Marcello Pivanti committed
342
343
344
345
346
347
348
349
350
351

            //Based on type i pick the user identiffier
            switch ($type) {
                case 'idm':
                    {
                        $matricola = $dataFetch['serialNumber'];
                        $nome = $dataFetch['name'];
                        $cognome = $dataFetch['familyName'];
                        $emailAddress = $dataFetch['email'];
                        $codiceFiscale = $dataFetch['codiceFiscale'];
Aster's avatar
Aster committed
352
                        $rawData = $dataFetch;
Marcello Pivanti's avatar
Marcello Pivanti committed
353
354
355
356
357
358
359
360
361
                    }
                    break;
                case 'spid':
                    {
                        $matricola = $dataFetch['saml_attribute_codicefiscale'] ?: $dataFetch['saml-attribute-codicefiscale'];
                        $nome = $dataFetch['saml_attribute_nome'] ?: $dataFetch['saml-attribute-nome'];
                        $cognome = $dataFetch['saml_attribute_cognome'] ?: $dataFetch['saml-attribute-cognome'];
                        $emailAddress = $dataFetch['saml_attribute_emailaddress'] ?: $dataFetch['saml-attribute-emailaddress'];
                        $codiceFiscale = $dataFetch['saml_attribute_codicefiscale'] ?: $dataFetch['saml-attribute-codicefiscale'];
Aster's avatar
Aster committed
362
                        $codiceFiscale = $dataFetch;
Marcello Pivanti's avatar
Marcello Pivanti committed
363
364
365
366
367
368
369
370
371
                    }
                    break;
                case 'header_idm':
                    {
                        $matricola = $dataFetch->get('serialNumber');
                        $nome = $dataFetch->get('name');
                        $cognome = $dataFetch->get('familyName');
                        $emailAddress = $dataFetch->get('email');
                        $codiceFiscale = $dataFetch->get('fiscalCode');
Aster's avatar
Aster committed
372
                        $rawData = $dataFetch->toArray();
Marcello Pivanti's avatar
Marcello Pivanti committed
373
374
375
376
377
378
379
380
381
                    }
                    break;
                case 'header_spid':
                {
                    $matricola = $dataFetch->get('saml_attribute_codicefiscale') ?: $dataFetch->get('saml-attribute-codicefiscale');
                    $nome = $dataFetch->get('saml_attribute_nome') ?: $dataFetch->get('saml-attribute-nome');
                    $cognome = $dataFetch->get('saml_attribute_cognome') ?: $dataFetch->get('saml-attribute-cognome');
                    $emailAddress = $dataFetch->get('saml_attribute_emailaddress') ?: $dataFetch->get('saml-attribute-emailaddress');
                    $codiceFiscale = $dataFetch->get('saml_attribute_codicefiscale') ?: $dataFetch->get('saml-attribute-codicefiscale');
Aster's avatar
Aster committed
382
                    $rawData = $dataFetch->toArray();
Marcello Pivanti's avatar
Marcello Pivanti committed
383
384
385
386
387
388
389
390
391
                }
            }

            //Data to store in session in case header is not filled
            $sessionIDM = [
                'matricola' => $matricola,
                'nome' => $nome,
                'cognome' => $cognome,
                'emailAddress' => $emailAddress,
Aster's avatar
Aster committed
392
393
                'codiceFiscale' => $codiceFiscale,
                'rawData' => $rawData
Marcello Pivanti's avatar
Marcello Pivanti committed
394
395
396
397
398
399
400
401
402
403
404
405
406
            ];

            //Store to session
            \Yii::$app->session->set('IDM', $sessionIDM);
        }

        return $sessionIDM;
    }

    /**
     * @param $userDatas
     * @return bool
     */
Aster's avatar
Aster committed
407
    public function createIdmUser($userDatas, $user_id = null)
Marcello Pivanti's avatar
Marcello Pivanti committed
408
    {
Aster's avatar
Aster committed
409
        return SocialAuthUtility::createIdmUser($userDatas, $user_id);
Marcello Pivanti's avatar
Marcello Pivanti committed
410
411
412
    }

    /**
Aster's avatar
Aster committed
413
     * @param $user
Marcello Pivanti's avatar
Marcello Pivanti committed
414
415
     * @return bool
     */
Aster's avatar
Aster committed
416
    public function isUserDisabled($user_id)
Marcello Pivanti's avatar
Marcello Pivanti committed
417
    {
Aster's avatar
Aster committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        $user = User::findOne($user_id);
        if ($user) {
            if ($user->status == User::STATUS_DELETED || !$user->userProfile->attivo) {
                \Yii::$app->session->remove('IDM');
                \Yii::$app->getSession()->addFlash('danger', Module::t('amossocialauth', 'User is disabled'));

                return true;
            }
        }
        return false;
    }

    public function actionSetModuleInstance() {
        $moduleId = $this->module->id;

        \Yii::$app->session->set('socialAuthInstance', $moduleId);

        return $this->goHome();
Marcello Pivanti's avatar
Marcello Pivanti committed
436
437
    }
}