AuthenticationController.php 36 KB
Newer Older
Damien's avatar
Damien committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

/**
 * Copyright Maarch since 2008 under licence GPLv3.
 * See LICENCE.txt file at the root folder for more details.
 * This file is part of Maarch software.
 */

/**
 * @brief Authentication Controller
 *
 * @author dev@maarch.org
 */

namespace SrcCore\controllers;

17
use Configuration\models\ConfigurationModel;
18
use Email\controllers\EmailController;
19
use Firebase\JWT\JWT;
20
use History\controllers\HistoryController;
21
use Parameter\models\ParameterModel;
22
23
24
use Respect\Validation\Validator;
use Slim\Http\Request;
use Slim\Http\Response;
Damien's avatar
Damien committed
25
use SrcCore\models\AuthenticationModel;
26
use SrcCore\models\CoreConfigModel;
27
use SrcCore\models\CurlModel;
Damien's avatar
Damien committed
28
29
use SrcCore\models\PasswordModel;
use SrcCore\models\ValidatorModel;
30
use Stevenmaguire\OAuth2\Client\Provider\Keycloak;
31
use User\controllers\UserController;
Damien's avatar
Damien committed
32
33
34
35
use User\models\UserModel;

class AuthenticationController
{
36
37
    const MAX_DURATION_TOKEN = 30; //Minutes
    const ROUTES_WITHOUT_AUTHENTICATION = [
38
        'GET/authenticationInformations', 'PUT/versionsUpdateSQL', 'GET/validUrl', 'GET/authenticate/token', 'GET/images', 'POST/password', 'PUT/password', 'GET/passwordRules',
39
        'GET/jnlp/{jnlpUniqueId}', 'GET/onlyOffice/mergedFile', 'POST/onlyOfficeCallback', 'POST/authenticate',
40
        'GET/wopi/files/{id}', 'GET/wopi/files/{id}/contents', 'POST/wopi/files/{id}/contents','GET/onlyOffice/content', 'GET/languages/{lang}', 'GET/languages', 'GET/commitInformation'
41
42
    ];

43
44
    public function getInformations(Request $request, Response $response)
    {
45
46
47
48
        $path = CoreConfigModel::getConfigPath();
        if (!file_exists($path)) {
            return $response->withStatus(403)->withJson(['errors' => 'No configuration file found']);
        }
49
        $hashedPath = md5($path);
50

51
        $appName   = CoreConfigModel::getApplicationName();
52
        $configFile = CoreConfigModel::getJsonLoaded(['path' => 'config/config.json']);
53
54
        $maarchUrl = $configFile['config']['maarchUrl'] ?? '';

55
56
        $parameter = ParameterModel::getById(['id' => 'loginpage_message', 'select' => ['param_value_string']]);

57
58
        $encryptKey = CoreConfigModel::getEncryptKey();

Damien's avatar
Damien committed
59
60
61
        $loggingMethod = CoreConfigModel::getLoggingMethod();
        $authUri = null;
        if ($loggingMethod['id'] == 'cas') {
62
            $casConfiguration = CoreConfigModel::getXmlLoaded(['path' => 'config/cas_config.xml']);
63
64
65
66
            $hostname         = (string)$casConfiguration->WEB_CAS_URL;
            $port             = (string)$casConfiguration->WEB_CAS_PORT;
            $uri              = (string)$casConfiguration->WEB_CAS_CONTEXT;
            $authUri          = "https://{$hostname}:{$port}{$uri}/login?service=" . UrlController::getCoreUrl() . 'dist/index.html#/login';
67
68
        } elseif ($loggingMethod['id'] == 'keycloak') {
            $keycloakConfig = CoreConfigModel::getKeycloakConfiguration();
69
70
71
            $provider       = new Keycloak($keycloakConfig);
            $authUri        = $provider->getAuthorizationUrl(['scope' => $keycloakConfig['scope']]);
            $keycloakState  = $provider->getState();
Damien's avatar
Damien committed
72
73
74
        } elseif ($loggingMethod['id'] == 'sso') {
            $ssoConfiguration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_sso', 'select' => ['value']]);
            $ssoConfiguration = !empty($ssoConfiguration['value']) ? json_decode($ssoConfiguration['value'], true) : null;
75
            $authUri          = $ssoConfiguration['url'] ?? null;
76
        } elseif ($loggingMethod['id'] == 'openam') {
77
            $configuration  = CoreConfigModel::getJsonLoaded(['path' => 'config/openAM.json']);
78
            $authUri        = $configuration['connectionUrl'] ?? null;
Damien's avatar
Damien committed
79
80
        }

81
82
83
        $emailConfiguration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_email_server', 'select' => ['value']]);
        $emailConfiguration = !empty($emailConfiguration['value']) ? json_decode($emailConfiguration['value'], true) : null;

84
        $return = [
Damien's avatar
Damien committed
85
86
87
88
89
            'instanceId'        => $hashedPath,
            'applicationName'   => $appName,
            'loginMessage'      => $parameter['param_value_string'] ?? null,
            'changeKey'         => $encryptKey == 'Security Key Maarch Courrier #2008',
            'authMode'          => $loggingMethod['id'],
90
            'authUri'           => $authUri,
91
            'lang'              => CoreConfigModel::getLanguage(),
92
93
            'mailServerOnline'  => $emailConfiguration['online'],
            'maarchUrl'         => $maarchUrl
94
95
96
97
98
99
100
        ];

        if (!empty($keycloakState)) {
            $return['keycloakState'] = $keycloakState;
        }

        return $response->withJson($return);
101
102
    }

Damien's avatar
Damien committed
103
104
105
    public function getValidUrl(Request $request, Response $response)
    {
        if (!is_file('custom/custom.json')) {
106
            return $response->withJson(['message' => 'No custom file', 'lang' => 'noConfiguration']);
Damien's avatar
Damien committed
107
108
109
110
        }

        $jsonFile = file_get_contents('custom/custom.json');
        $jsonFile = json_decode($jsonFile, true);
111
        if (empty($jsonFile)) {
112
            return $response->withJson(['message' => 'No custom', 'lang' => 'noConfiguration']);
113
        } elseif (count($jsonFile) > 1) {
114
            return $response->withJson(['message' => 'There is more than 1 custom', 'lang' => 'moreOneCustom']);
Damien's avatar
Damien committed
115
116
117
118
119
120
        }

        $url = null;
        if (!empty($jsonFile[0]['path'])) {
            $coreUrl = UrlController::getCoreUrl();
            $url = $coreUrl . $jsonFile[0]['path'] . "/dist/index.html";
121
122
        } elseif (!empty($jsonFile[0]['uri'])) {
            $url = $jsonFile[0]['uri'] . "/dist/index.html";
Damien's avatar
Damien committed
123
124
125
126
127
        }

        return $response->withJson(['url' => $url]);
    }

128
    public static function authentication($authorizationHeaders = [])
Damien's avatar
Damien committed
129
130
    {
        $userId = null;
131
132
133
134
135
136
137
138
139
140
141

        $canBasicAuth = true;
        $loginMethod = CoreConfigModel::getLoggingMethod();
        if ($loginMethod['id'] != 'standard' && !empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
            $rawUser = UserModel::getByLogin(['select' => ['mode'], 'login' => $_SERVER['PHP_AUTH_USER']]);
            if (!empty($rawUser) && $rawUser['mode'] != 'rest') {
                $canBasicAuth = false;
            }
        }

        if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW']) && $canBasicAuth) {
142
            if (AuthenticationModel::authentication(['login' => $_SERVER['PHP_AUTH_USER'], 'password' => $_SERVER['PHP_AUTH_PW']])) {
143
                $user = UserModel::getByLogin(['select' => ['id', 'mode'], 'login' => $_SERVER['PHP_AUTH_USER']]);
144
                $userId = $user['id'];
Damien's avatar
Damien committed
145
146
            }
        } else {
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
            if (!empty($authorizationHeaders)) {
                $token = null;
                foreach ($authorizationHeaders as $authorizationHeader) {
                    if (strpos($authorizationHeader, 'Bearer') === 0) {
                        $token = str_replace('Bearer ', '', $authorizationHeader);
                    }
                }
                if (!empty($token)) {
                    try {
                        $jwt = (array)JWT::decode($token, CoreConfigModel::getEncryptKey(), ['HS256']);
                    } catch (\Exception $e) {
                        return null;
                    }
                    $jwt['user'] = (array)$jwt['user'];
                    if (!empty($jwt) && !empty($jwt['user']['id'])) {
                        $userId = $jwt['user']['id'];
                    }
                }
            }
Damien's avatar
Damien committed
166
167
        }

168
169
170
        if (!empty($userId)) {
            UserModel::update([
                'set'   => ['reset_token' => null],
171
                'where' => ['id = ?'],
172
173
174
175
                'data'  => [$userId]
            ]);
        }

Damien's avatar
Damien committed
176
177
178
        return $userId;
    }

179
    public static function isRouteAvailable(array $args)
180
    {
Damien's avatar
Damien committed
181
        ValidatorModel::notEmpty($args, ['userId', 'currentRoute', 'currentMethod']);
182
        ValidatorModel::intVal($args, ['userId']);
Damien's avatar
Damien committed
183
        ValidatorModel::stringType($args, ['currentRoute', 'currentMethod']);
184

Damien's avatar
Damien committed
185
        $user = UserModel::getById(['select' => ['status', 'password_modification_date', 'mode', 'authorized_api'], 'id' => $args['userId']]);
186

187
        if ($user['mode'] == 'rest') {
Damien's avatar
Damien committed
188
189
190
191
            $authorizedApi = json_decode($user['authorized_api'], true);
            if (!empty($authorizedApi) && !in_array($args['currentMethod'].$args['currentRoute'], $authorizedApi)) {
                return ['isRouteAvailable' => false, 'errors' => 'This route is not authorized for this user'];
            }
192
            return ['isRouteAvailable' => true];
Damien's avatar
Damien committed
193
        } elseif ($user['status'] == 'ABS' && !in_array($args['currentRoute'], ['/users/{id}/status', '/currentUser/profile', '/header', '/passwordRules', '/users/{id}/password'])) {
194
195
            return ['isRouteAvailable' => false, 'errors' => 'User is ABS and must be activated'];
        }
196

197
198
        if (!in_array($args['currentRoute'], ['/passwordRules', '/users/{id}/password'])) {
            $loggingMethod = CoreConfigModel::getLoggingMethod();
199

200
            if (in_array($loggingMethod['id'], ['standard'])) {
201
202
203
204
205
                $passwordRules = PasswordModel::getEnabledRules();
                if (!empty($passwordRules['renewal'])) {
                    $currentDate = new \DateTime();
                    $lastModificationDate = new \DateTime($user['password_modification_date']);
                    $lastModificationDate->add(new \DateInterval("P{$passwordRules['renewal']}D"));
206

207
208
                    if ($currentDate > $lastModificationDate) {
                        return ['isRouteAvailable' => false, 'errors' => 'User must change his password'];
209
210
211
212
213
214
215
216
                    }
                }
            }
        }

        return ['isRouteAvailable' => true];
    }

217
    public static function handleFailedAuthentication(array $args)
Damien's avatar
Damien committed
218
    {
219
220
        ValidatorModel::notEmpty($args, ['userId']);
        ValidatorModel::intVal($args, ['userId']);
Damien's avatar
Damien committed
221
222
223
224

        $passwordRules = PasswordModel::getEnabledRules();

        if (!empty($passwordRules['lockAttempts'])) {
225
            $user = UserModel::getById(['select' => ['failed_authentication', 'locked_until'], 'id' => $args['userId']]);
226
            $set = [];
227
            if (!empty($user['locked_until'])) {
228
229
230
231
232
233
234
235
                $currentDate = new \DateTime();
                $lockedUntil = new \DateTime($user['locked_until']);
                if ($lockedUntil < $currentDate) {
                    $set['locked_until'] = null;
                    $user['failed_authentication'] = 0;
                } else {
                    return ['accountLocked' => true, 'lockedDate' => $user['locked_until']];
                }
236
            }
Damien's avatar
Damien committed
237

238
            $set['failed_authentication'] = $user['failed_authentication'] + 1;
239
            UserModel::update([
240
                'set'       => $set,
241
242
243
                'where'     => ['id = ?'],
                'data'      => [$args['userId']]
            ]);
Damien's avatar
Damien committed
244

245
246
247
            if (!empty($user['failed_authentication']) && ($user['failed_authentication'] + 1) >= $passwordRules['lockAttempts'] && !empty($passwordRules['lockTime'])) {
                $lockedUntil = time() + 60 * $passwordRules['lockTime'];
                UserModel::update([
248
                    'set'       => ['locked_until'  => date('Y-m-d H:i:s', $lockedUntil)],
249
250
251
                    'where'     => ['id = ?'],
                    'data'      => [$args['userId']]
                ]);
252
                return ['accountLocked' => true, 'lockedDate' => date('Y-m-d H:i:s', $lockedUntil)];
Damien's avatar
Damien committed
253
254
255
            }
        }

256
        return true;
Damien's avatar
Damien committed
257
    }
258

259
260
261
262
    public function authenticate(Request $request, Response $response)
    {
        $body = $request->getParsedBody();

263
        $loggingMethod = CoreConfigModel::getLoggingMethod();
Damien's avatar
Damien committed
264
265
266
267
268
269
        if (in_array($loggingMethod['id'], ['standard', 'ldap'])) {
            if (!Validator::stringType()->notEmpty()->validate($body['login']) || !Validator::stringType()->notEmpty()->validate($body['password'])) {
                return $response->withStatus(400)->withJson(['errors' => 'Bad Request']);
            }
        }

270
        if ($loggingMethod['id'] == 'standard') {
271
            $login = strtolower($body['login']);
Damien's avatar
Damien committed
272
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
273
                return $response->withStatus(403)->withJson(['errors' => 'Authentication Failed']);
Damien's avatar
Damien committed
274
            }
275
276
277
278
279
280
281
            $authenticated = AuthenticationController::standardConnection(['login' => $login, 'password' => $body['password']]);
            if (!empty($authenticated['date'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors'], 'date' => $authenticated['date']]);
            } elseif (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
        } elseif ($loggingMethod['id'] == 'ldap') {
282
            $login = $body['login'];
Damien's avatar
Damien committed
283
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
284
                return $response->withStatus(403)->withJson(['errors' => 'Authentication Failed']);
Damien's avatar
Damien committed
285
            }
286
287
288
289
            $authenticated = AuthenticationController::ldapConnection(['login' => $login, 'password' => $body['password']]);
            if (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
Damien's avatar
Damien committed
290
291
292
293
294
295
296
        } elseif ($loggingMethod['id'] == 'cas') {
            $authenticated = AuthenticationController::casConnection();
            if (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
            $login = strtolower($authenticated['login']);
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
297
                return $response->withStatus(403)->withJson(['errors' => 'Authentication Failed']);
Damien's avatar
Damien committed
298
            }
299
300
301
302
303
304
        } elseif ($loggingMethod['id'] == 'keycloak') {
            $queryParams = $request->getQueryParams();
            $authenticated = AuthenticationController::keycloakConnection(['code' => $queryParams['code']]);
            if (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
305
            $login = $authenticated['login'];
306
307
308
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
                return $response->withStatus(403)->withJson(['errors' => 'Authentication unauthorized']);
            }
Damien's avatar
Damien committed
309
310
311
312
313
314
315
316
317
        } elseif ($loggingMethod['id'] == 'sso') {
            $authenticated = AuthenticationController::ssoConnection();
            if (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
            $login = strtolower($authenticated['login']);
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
                return $response->withStatus(403)->withJson(['errors' => 'Authentication unauthorized']);
            }
318
319
320
321
322
323
324
325
326
        } elseif ($loggingMethod['id'] == 'openam') {
            $authenticated = AuthenticationController::openAMConnection();
            if (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
            $login = strtolower($authenticated['login']);
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
                return $response->withStatus(403)->withJson(['errors' => 'Authentication unauthorized']);
            }
327
328
329
330
331
332
333
334
335
        } elseif ($loggingMethod['id'] == 'azure_saml') {
            $authenticated = AuthenticationController::azureSamlConnection();
            if (!empty($authenticated['errors'])) {
                return $response->withStatus(401)->withJson(['errors' => $authenticated['errors']]);
            }
            $login = strtolower($authenticated['login']);
            if (!AuthenticationController::isUserAuthorized(['login' => $login])) {
                return $response->withStatus(403)->withJson(['errors' => 'Authentication unauthorized']);
            }
Damien's avatar
Damien committed
336
337
        } else {
            return $response->withStatus(403)->withJson(['errors' => 'Logging method unauthorized']);
338
339
        }

340
        UserController::setAbsences();
341
        $user = UserModel::getByLowerLogin(['login' => $login, 'select' => ['id', 'refresh_token', 'user_id']]);
Damien's avatar
Damien committed
342

343
        $GLOBALS['id'] = $user['id'];
Damien's avatar
Damien committed
344
        $GLOBALS['login'] = $user['user_id'];
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361

        $user['refresh_token'] = json_decode($user['refresh_token'], true);
        foreach ($user['refresh_token'] as $key => $refreshToken) {
            try {
                JWT::decode($refreshToken, CoreConfigModel::getEncryptKey(), ['HS256']);
            } catch (\Exception $e) {
                unset($user['refresh_token'][$key]);
            }
        }
        $user['refresh_token'] = array_values($user['refresh_token']);
        if (count($user['refresh_token']) > 10) {
            array_shift($user['refresh_token']);
        }

        $refreshToken = AuthenticationController::getRefreshJWT();
        $user['refresh_token'][] = $refreshToken;
        UserModel::update([
362
            'set'   => ['reset_token' => null, 'refresh_token' => json_encode($user['refresh_token']), 'failed_authentication' => 0, 'locked_until' => null],
363
364
365
            'where' => ['id = ?'],
            'data'  => [$user['id']]
        ]);
366

367
368
369
        $response = $response->withHeader('Token', AuthenticationController::getJWT());
        $response = $response->withHeader('Refresh-Token', $refreshToken);

Damien's avatar
Damien committed
370
        HistoryController::add([
371
372
373
374
375
            'tableName' => 'users',
            'recordId'  => $user['id'],
            'eventType' => 'LOGIN',
            'info'      => _LOGIN . ' : ' . $login,
            'moduleId'  => 'authentication',
376
            'eventId'   => 'userlogin'
Damien's avatar
Damien committed
377
        ]);
378
379
380
381

        return $response->withStatus(204);
    }

Damien's avatar
Damien committed
382
383
384
385
    public function logout(Request $request, Response $response)
    {
        $loggingMethod = CoreConfigModel::getLoggingMethod();

Damien's avatar
Damien committed
386
        $logoutUrl = null;
Damien's avatar
Damien committed
387
        if ($loggingMethod['id'] == 'cas') {
Damien's avatar
Damien committed
388
389
            $disconnection = AuthenticationController::casDisconnection();
            $logoutUrl = $disconnection['logoutUrl'];
390
        } elseif ($loggingMethod['id'] == 'keycloak') {
Damien's avatar
Damien committed
391
392
            $disconnection = AuthenticationController::keycloakDisconnection();
            $logoutUrl = $disconnection['logoutUrl'];
393
394
395
        } elseif ($loggingMethod['id'] == 'azure_saml') {
            $disconnection = AuthenticationController::azureSamlDisconnection();
            $logoutUrl = $disconnection['logoutUrl'];
Damien's avatar
Damien committed
396
        }
397

398
399
400
401
402
403
404
405
406
        HistoryController::add([
            'tableName' => 'users',
            'recordId'  => $GLOBALS['id'],
            'eventType' => 'LOGOUT',
            'info'      => _LOGOUT . ' : ' . $GLOBALS['login'],
            'moduleId'  => 'authentication',
            'eventId'   => 'userlogout'
        ]);

Damien's avatar
Damien committed
407
        return $response->withJson(['logoutUrl' => $logoutUrl]);
Damien's avatar
Damien committed
408
409
    }

410
411
412
413
414
415
416
    private static function standardConnection(array $args)
    {
        $login = $args['login'];
        $password = $args['password'];

        $authenticated = AuthenticationModel::authentication(['login' => $login, 'password' => $password]);
        if (empty($authenticated)) {
417
            $user = UserModel::getByLowerLogin(['login' => $login, 'select' => ['id']]);
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
            $handle = AuthenticationController::handleFailedAuthentication(['userId' => $user['id']]);
            if (!empty($handle['accountLocked'])) {
                return ['errors' => 'Account Locked', 'date' => $handle['lockedDate']];
            }
            return ['errors' => 'Authentication Failed'];
        }

        return true;
    }

    private static function ldapConnection(array $args)
    {
        $login = $args['login'];
        $password = $args['password'];

        $ldapConfigurations = CoreConfigModel::getXmlLoaded(['path' => 'modules/ldap/xml/config.xml']);
434
        if (empty($ldapConfigurations) || empty($ldapConfigurations->config->ldap)) {
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
            return ['errors' => 'No ldap configurations'];
        }

        foreach ($ldapConfigurations->config->ldap as $ldapConfiguration) {
            $ssl = (string)$ldapConfiguration->ssl;
            $domain = (string)$ldapConfiguration->domain;
            $prefix = (string)$ldapConfiguration->prefix_login;
            $suffix = (string)$ldapConfiguration->suffix_login;
            $standardConnect = (string)$ldapConfiguration->standardConnect;

            $uri = ($ssl == 'true' ? "LDAPS://{$domain}" : $domain);

            $ldap = @ldap_connect($uri);
            if ($ldap === false) {
                $error = 'Ldap connect failed : uri is maybe wrong';
                continue;
            }
            ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
            ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
            ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, 10);
            $ldapLogin = (!empty($prefix) ? $prefix . '\\' . $login : $login);
            $ldapLogin = (!empty($suffix) ? $ldapLogin . $suffix : $ldapLogin);
            if (!empty((string)$ldapConfiguration->baseDN)) { //OpenLDAP
                $search = @ldap_search($ldap, (string)$ldapConfiguration->baseDN, "(uid={$ldapLogin})", ['dn']);
                if ($search === false) {
                    $error = 'Ldap search failed : baseDN is maybe wrong => ' . ldap_error($ldap);
                    continue;
                }
                $entries = ldap_get_entries($ldap, $search);
                $ldapLogin = $entries[0]['dn'];
            }
            $authenticated = @ldap_bind($ldap, $ldapLogin, $password);
            if ($authenticated) {
                break;
            }
            $error = ldap_error($ldap);
        }

        if (!empty($standardConnect) && $standardConnect == 'true') {
            if (empty($authenticated)) {
                $authenticated = AuthenticationModel::authentication(['login' => $login, 'password' => $password]);
            } else {
477
                $user = UserModel::getByLowerLogin(['login' => $login, 'select' => ['id']]);
478
479
480
481
482
483
                UserModel::updatePassword(['id' => $user['id'], 'password' => $password]);
            }
        }

        if (empty($authenticated) && !empty($error) && $error != 'Invalid credentials') {
            return ['errors' => $error];
484
        } elseif (empty($authenticated)) {
485
486
487
488
489
490
            return ['errors' => 'Authentication Failed'];
        }

        return true;
    }

Damien's avatar
Damien committed
491
492
    private static function casConnection()
    {
493
        $casConfiguration = CoreConfigModel::getXmlLoaded(['path' => 'config/cas_config.xml']);
Damien's avatar
Damien committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514

        $version = (string)$casConfiguration->CAS_VERSION;
        $hostname = (string)$casConfiguration->WEB_CAS_URL;
        $port = (string)$casConfiguration->WEB_CAS_PORT;
        $uri = (string)$casConfiguration->WEB_CAS_CONTEXT;
        $certificate = (string)$casConfiguration->PATH_CERTIFICATE;
        $separator = (string)$casConfiguration->ID_SEPARATOR;

        if (!in_array($version, ['CAS_VERSION_2_0', 'CAS_VERSION_3_0'])) {
            return ['errors' => 'Cas version not supported'];
        }

        \phpCAS::setDebug();
        \phpCAS::setVerbose(true);
        \phpCAS::client(constant($version), $hostname, (int)$port, $uri, $version != 'CAS_VERSION_3_0');

        if (!empty($certificate)) {
            \phpCAS::setCasServerCACert($certificate);
        } else {
            \phpCAS::setNoCasServerValidation();
        }
Damien's avatar
Damien committed
515
516
517
518
519
        \phpCAS::setFixedServiceURL(UrlController::getCoreUrl() . 'dist/index.html');
        \phpCAS::setNoClearTicketsFromUrl();
        if (!\phpCAS::isAuthenticated()) {
            return ['errors' => 'Cas authentication failed'];
        }
Damien's avatar
Damien committed
520
521
522
523
524
525
526
527
528
529
530

        $casId = \phpCAS::getUser();
        if (!empty($separator)) {
            $login = explode($separator, $casId)[0];
        } else {
            $login = $casId;
        }

        return ['login' => $login];
    }

Damien's avatar
Damien committed
531
532
    private static function casDisconnection()
    {
533
        $casConfiguration = CoreConfigModel::getXmlLoaded(['path' => 'config/cas_config.xml']);
Damien's avatar
Damien committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

        $version = (string)$casConfiguration->CAS_VERSION;
        $hostname = (string)$casConfiguration->WEB_CAS_URL;
        $port = (string)$casConfiguration->WEB_CAS_PORT;
        $uri = (string)$casConfiguration->WEB_CAS_CONTEXT;
        $certificate = (string)$casConfiguration->PATH_CERTIFICATE;

        \phpCAS::setDebug();
        \phpCAS::setVerbose(true);
        \phpCAS::client(constant($version), $hostname, (int)$port, $uri, $version != 'CAS_VERSION_3_0');

        if (!empty($certificate)) {
            \phpCAS::setCasServerCACert($certificate);
        } else {
            \phpCAS::setNoCasServerValidation();
        }
        \phpCAS::setFixedServiceURL(UrlController::getCoreUrl() . 'dist/index.html');
        \phpCAS::setNoClearTicketsFromUrl();
552
        $logoutUrl = \phpCAS::getServerLogoutURL();
Damien's avatar
Damien committed
553

554
555
556
        return ['logoutUrl' => $logoutUrl];
    }

Damien's avatar
Damien committed
557
558
559
560
561
562
563
564
565
566
567
568
569
    private static function ssoConnection()
    {
        $ssoConfiguration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_sso', 'select' => ['value']]);
        if (empty($ssoConfiguration['value'])) {
            return ['errors' => 'Sso configuration missing'];
        }

        $ssoConfiguration = json_decode($ssoConfiguration['value'], true);
        $mapping = array_column($ssoConfiguration['mapping'], 'ssoId', 'maarchId');
        if (empty($mapping['login'])) {
            return ['errors' => 'Sso configuration missing : no login mapping'];
        }

570
571
572
573
574
        if (in_array(strtoupper($mapping['login']), ['REMOTE_USER', 'PHP_AUTH_USER'])) {
            $login = $_SERVER[strtoupper($mapping['login'])] ?? null;
        } else {
            $login = $_SERVER['HTTP_' . strtoupper($mapping['login'])] ?? null;
        }
Damien's avatar
Damien committed
575
576
577
578
579
580
581
        if (empty($login)) {
            return ['errors' => 'Authentication Failed : login not present in header'];
        }

        return ['login' => $login];
    }

582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    private static function keycloakConnection(array $args)
    {
        $keycloakConfig = CoreConfigModel::getKeycloakConfiguration();

        if (empty($keycloakConfig) || empty($keycloakConfig['authServerUrl']) || empty($keycloakConfig['realm']) || empty($keycloakConfig['clientId']) || empty($keycloakConfig['clientSecret']) || empty($keycloakConfig['redirectUri'])) {
            return ['errors' => 'Keycloak not configured'];
        }

        $provider = new Keycloak($keycloakConfig);

        try {
            $token = $provider->getAccessToken('authorization_code', ['code' => $args['code']]);
        } catch (\Exception $e) {
            return ['errors' => 'Authentication Failed'];
        }

        try {
            $user = $provider->getResourceOwner($token);

            $login = $user->getId();
            $keycloakAccessToken = $token->getToken();

            $userMaarch = UserModel::getByLogin(['login' => $login, 'select' => ['id', 'external_id']]);

            if (empty($userMaarch)) {
                return ['errors' => 'Authentication Failed'];
            }

            $userMaarch['external_id'] = json_decode($userMaarch['external_id'], true);
            $userMaarch['external_id']['keycloakAccessToken'] = $keycloakAccessToken;
            $userMaarch['external_id'] = json_encode($userMaarch['external_id']);

            UserModel::updateExternalId(['id' => $userMaarch['id'], 'externalId' => $userMaarch['external_id']]);

            return ['login' => $login];
        } catch (\Exception $e) {
            return ['errors' => 'Authentication Failed'];
        }
    }

    private static function keycloakDisconnection()
    {
        $keycloakConfig = CoreConfigModel::getKeycloakConfiguration();

        $provider = new Keycloak($keycloakConfig);

        $externalId = UserModel::getById(['id' => $GLOBALS['id'], 'select' => ['external_id']]);
        $externalId = json_decode($externalId['external_id'], true);
        $accessToken = $externalId['keycloakAccessToken'];
        unset($externalId['keycloakAccessToken']);
        UserModel::update([
            'set'   => ['external_id' => json_encode($externalId)],
            'where' => ['id = ?'],
            'data'  => [$GLOBALS['id']]
        ]);

        $url = $provider->getLogoutUrl(['client_id' => $keycloakConfig['clientId'], 'refresh_token' => $accessToken]);

        return ['logoutUrl' => $url];
Damien's avatar
Damien committed
641
642
    }

643
644
    private static function openAMConnection()
    {
645
        $configuration = CoreConfigModel::getJsonLoaded(['path' => 'config/openAM.json']);
646
647
648
649
650
651
652
653

        if (empty($configuration['attributeUrl']) || empty($configuration['cookieName']) || empty($configuration['attributeName'])) {
            return ['errors' => 'OpenAM configuration missing'];
        }

        if (empty($_COOKIE[$configuration['cookieName']])) {
            return ['errors' => 'Authentication Failed : User cookie is not set'];
        }
654
        $curlResponse = CurlModel::exec([
655
656
657
658
659
660
661
662
663
664
665
666
667
            'url'           => "{$configuration['attributeUrl']}?subjectid={$_COOKIE[$configuration['cookieName']]}&attributenames={$configuration['attributeName']}",
            'method'        => 'GET',
        ]);

        $login = $curlResponse['response']['attributes'][0]['values'][0] ?? null;

        if (empty($login)) {
            return ['errors' => 'Authentication Failed : login not present in response'];
        }

        return ['login' => $login];
    }

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
    private static function azureSamlConnection()
    {
        $libDir = CoreConfigModel::getLibrariesDirectory();
        if (!is_file($libDir . 'simplesamlphp/lib/_autoload.php')) {
            return ['errors' => 'Library simplesamlphp not present'];
        }

        require_once($libDir . 'simplesamlphp/lib/_autoload.php');
        $as = new \SimpleSAML\Auth\Simple('default-sp');
        $as->requireAuth([
            'ReturnTo'          => UrlController::getCoreUrl(),
            'skipRedirection'   => true
        ]);

        $attributes = $as->getAttributes();
Damien's avatar
Damien committed
683
        $login = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'][0];
684
685
686
687
688
689
690
        if (empty($login)) {
            return ['errors' => 'Authentication Failed : login not present in attributes'];
        }

        return ['login' => $login];
    }

691
692
693
694
695
696
697
698
699
700
701
702
703
704
    private static function azureSamlDisconnection()
    {
        $libDir = CoreConfigModel::getLibrariesDirectory();
        if (!is_file($libDir . 'simplesamlphp/lib/_autoload.php')) {
            return ['errors' => 'Library simplesamlphp not present'];
        }

        require_once($libDir . 'simplesamlphp/lib/_autoload.php');
        $as = new \SimpleSAML\Auth\Simple('default-sp');
        $url = $as->getLogoutURL();

        return ['logoutUrl' => $url];
    }

705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
    public function getRefreshedToken(Request $request, Response $response)
    {
        $queryParams = $request->getQueryParams();

        if (!Validator::stringType()->notEmpty()->validate($queryParams['refreshToken'])) {
            return $response->withStatus(400)->withJson(['errors' => 'Refresh Token is empty']);
        }

        try {
            $jwt = JWT::decode($queryParams['refreshToken'], CoreConfigModel::getEncryptKey(), ['HS256']);
        } catch (\Exception $e) {
            return $response->withStatus(401)->withJson(['errors' => 'Authentication Failed']);
        }

        $user = UserModel::getById(['select' => ['id', 'refresh_token'], 'id' => $jwt->user->id]);
        if (empty($user['refresh_token'])) {
            return $response->withStatus(401)->withJson(['errors' => 'Authentication Failed']);
        }

        $user['refresh_token'] = json_decode($user['refresh_token'], true);
        if (!in_array($queryParams['refreshToken'], $user['refresh_token'])) {
            return $response->withStatus(401)->withJson(['errors' => 'Authentication Failed']);
        }

        $GLOBALS['id'] = $user['id'];

        return $response->withJson(['token' => AuthenticationController::getJWT()]);
    }

    public static function getJWT()
    {
        $sessionTime = AuthenticationController::MAX_DURATION_TOKEN;

738
        $file = CoreConfigModel::getJsonLoaded(['path' => 'config/config.json']);
739
740
741
742
        if ($file) {
            if (!empty($file['config']['cookieTime'])) {
                if ($sessionTime > (int)$file['config']['cookieTime']) {
                    $sessionTime = (int)$file['config']['cookieTime'];
743
744
745
746
                }
            }
        }

747
748
        $user = UserModel::getById(['id' => $GLOBALS['id'], 'select' => ['id', 'firstname', 'lastname', 'status', 'user_id as login']]);

749
750
        $token = [
            'exp'   => time() + 60 * $sessionTime,
751
            'user'  => $user
752
753
754
755
756
757
758
759
760
761
762
        ];

        $jwt = JWT::encode($token, CoreConfigModel::getEncryptKey());

        return $jwt;
    }

    public static function getRefreshJWT()
    {
        $sessionTime = AuthenticationController::MAX_DURATION_TOKEN;

763
        $file = CoreConfigModel::getJsonLoaded(['path' => 'config/config.json']);
764
765
        if ($file) {
            $sessionTime = (int)$file['config']['cookieTime'];
766
767
768
769
770
771
772
773
774
775
776
777
778
779
        }

        $token = [
            'exp'   => time() + 60 * $sessionTime,
            'user'  => [
                'id' => $GLOBALS['id']
            ]
        ];

        $jwt = JWT::encode($token, CoreConfigModel::getEncryptKey());

        return $jwt;
    }

780
    public static function getResetJWT($args = [])
781
782
    {
        $token = [
783
            'exp'   => time() + $args['expirationTime'],
784
            'user'  => [
785
                'id' => $args['id']
786
787
788
789
790
791
792
            ]
        ];

        $jwt = JWT::encode($token, CoreConfigModel::getEncryptKey());

        return $jwt;
    }
793

794
    public static function sendAccountActivationNotification(array $args)
795
796
797
798
    {
        $resetToken = AuthenticationController::getResetJWT(['id' => $args['userId'], 'expirationTime' => 1209600]); // 14 days
        UserModel::update(['set' => ['reset_token' => $resetToken], 'where' => ['id = ?'], 'data' => [$args['userId']]]);

799
        $url = UrlController::getCoreUrl() . 'dist/index.html#/reset-password?token=' . $resetToken;
800

801
        $configuration = ConfigurationModel::getByPrivilege(['privilege' => 'admin_email_server', 'select' => ['value']]);
802
803
804
805
806
807
        $configuration = json_decode($configuration['value'], true);
        if (!empty($configuration['from'])) {
            $sender = $configuration['from'];
        } else {
            $sender = $args['userEmail'];
        }
808
        $user = UserModel::getById(['select' => ['user_id'], 'id' => $args['userId']]);
809
810
811
        EmailController::createEmail([
            'userId'    => $args['userId'],
            'data'      => [
812
813
814
                'sender'     => ['email' => $sender],
                'recipients' => [$args['userEmail']],
                'object'     => _NOTIFICATIONS_USER_CREATION_SUBJECT,
815
                'body'       => _NOTIFICATIONS_USER_CREATION_BODY . '<a href="' . $url . '">'.$url.'</a><br/><br/>' . _YOUR_ID . ' ' . $user['user_id'] . _NOTIFICATIONS_USER_CREATION_FOOTER,
816
817
                'isHtml'     => true,
                'status'     => 'WAITING'
818
819
820
821
822
            ]
        ]);

        return true;
    }
Damien's avatar
Damien committed
823
824
825

    private static function isUserAuthorized(array $args)
    {
826
        $user = UserModel::getByLowerLogin(['login' => $args['login'], 'select' => ['mode', 'status']]);
Damien's avatar
Damien committed
827
828
829
830
831
832
        if (empty($user) || $user['mode'] == 'rest' || $user['status'] == 'SPD') {
            return false;
        }

        return true;
    }
833
834
835
836
837
838
839
840
841

    public static function canAccessInstallerWhitoutAuthentication(array $args)
    {
        $installerRoutes = [
            'GET/installer/prerequisites', 'GET/installer/databaseConnection', 'GET/installer/sqlDataFiles', 'GET/installer/docservers', 'GET/installer/custom',
            'GET/installer/customs', 'POST/installer/custom', 'POST/installer/database', 'POST/installer/docservers', 'POST/installer/customization',
            'PUT/installer/administrator', 'DELETE/installer/lock'
        ];

842
        if (!in_array($args['route'], $installerRoutes)) {
843
            return false;
844
845
846
847
848
849
850
851
852
853
854
855
856
        } elseif (is_file("custom/custom.json")) {
            $customs = scandir('custom');
            if (count($customs) > 4) {
                return false;
            }
            foreach ($customs as $custom) {
                if (in_array($custom, ['custom.json', '.', '..'])) {
                    continue;
                }
                if (!is_file("custom/{$custom}/initializing.lck")) {
                    return false;
                }
            }
857
858
859
860
        }

        return true;
    }
Damien's avatar
Damien committed
861
}