ILIAS  trunk Revision v11.0_alpha-1753-gb21ca8c4367
All Data Structures Namespaces Files Functions Variables Enumerations Enumerator Modules Pages
class.ilAuthProviderECS.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
23 
30 {
34  private ilLanguage $lng;
39 
40  protected ?int $mid = null;
41  protected ?string $abreviation = null;
42 
45 
46 
52  {
53  parent::__construct($credentials);
54 
55  global $DIC;
56 
57  $this->clientIniFile = $DIC->clientIni();
58  $this->rbacAdmin = $DIC->rbac()->admin();
59  $this->setting = $DIC->settings();
60  $this->lng = $DIC->language();
61  $this->lng->loadLanguageModule('ecs');
62  $this->http = $DIC->http();
63  $this->refinery = $DIC->refinery();
64  $this->authSession = $DIC['ilAuthSession'];
65  $this->ctrl = $DIC->ctrl();
66 
67  $this->initECSServices();
68  }
69 
73  public function getAbreviation(): string
74  {
75  return $this->abreviation;
76  }
77 
81  public function getMID(): int
82  {
83  return $this->mid;
84  }
85 
86  public function setMID(int $a_mid): void
87  {
88  $this->mid = $a_mid;
89  }
90 
94  public function setCurrentServer(ilECSSetting $server): void
95  {
96  $this->currentServer = $server;
97  }
98 
102  public function getCurrentServer(): ilECSSetting
103  {
104  return $this->currentServer;
105  }
106 
111  {
112  return $this->servers;
113  }
114 
115 
119  public function doAuthentication(\ilAuthStatus $status): bool
120  {
121  $this->getLogger()->debug('Starting ECS authentication');
122  if (!$this->getServerSettings()->activeServerExists()) {
123  $this->getLogger()->warning('No active ecs server found. Aborting');
124  $this->handleAuthenticationFail($status, 'err_wrong_login');
125  return false;
126  }
127 
128  // Iterate through all active ecs instances
129  foreach ($this->getServerSettings()->getServers(ilECSServerSettings::ACTIVE_SERVER) as $server) {
130  $this->setCurrentServer($server);
131  if ($this->validateHash()) {
132  return $this->handleLoginByAuthMode($status);
133  }
134  }
135  $this->getLogger()->warning('Could not validate ecs hash for any active server.');
136  $this->handleAuthenticationFail($status, 'err_wrong_login');
137  return false;
138  }
139 
144  protected function handleLoginByAuthMode(ilAuthStatus $status): bool
145  {
146  $is_external_account = false;
147  if ($this->http->wrapper()->query()->has('ecs_external_account')) {
148  $is_external_account = $this->http->wrapper()->query()->retrieve(
149  'ecs_external_account',
150  $this->refinery->kindlyTo()->bool()
151  );
152  }
153  $redirection_target = '';
154  if ($this->http->wrapper()->query()->has('target')) {
155  $redirection_target = $this->http->wrapper()->query()->retrieve(
156  'target',
157  $this->refinery->kindlyTo()->string()
158  );
159  }
160  $part_settings = new ilECSParticipantSetting(
161  $this->getCurrentServer()->getServerId(),
162  $this->getMID()
163  );
164  if ($this->resumeCurrentSession()) {
165  $this->getLogger()->debug('Continuing current user session');
167  $status->setAuthenticatedUserId($this->authSession->getUserId());
168  return true;
169  }
170  if (
171  $is_external_account &&
172  $part_settings->getIncomingAuthType() === ilECSParticipantSetting::INCOMING_AUTH_TYPE_LOGIN_PAGE
173  ) {
174  $this->getLogger()->info('ILIAS login page authentication required.');
175  ilSession::set('success', $this->lng->txt('ecs_login_success_ilias'));
177  $this->ctrl->redirectToURL('login.php?target=' . $redirection_target);
178  return false;
179  }
180  if (
181  $is_external_account &&
182  $part_settings->getIncomingAuthType() === ilECSParticipantSetting::INCOMING_AUTH_TYPE_SHIBBOLETH
183  ) {
184  $this->getLogger()->info('Redirect to shibboleth authentication');
186  $this->ctrl->redirectToURL('shib_login.php?target=' . $redirection_target);
187  }
188  if ($part_settings->areIncomingLocalAccountsSupported()) {
189  // handle successful authentication
190  $new_usr_id = $this->handleLogin();
191  $this->getLogger()->info('ECS authentication successful.');
193  $status->setAuthenticatedUserId($new_usr_id);
194  return true;
195  }
196  $this->handleAuthenticationFail($status, 'err_wrong_login');
197  return false;
198  }
199 
200  protected function resumeCurrentSession(): bool
201  {
202  $session_user_id = $this->authSession->getUserId();
203  if (!$session_user_id || $session_user_id === ANONYMOUS_USER_ID) {
204  $this->getLogger()->debug('No valid session found');
205  $this->authSession->setAuthenticated(false, ANONYMOUS_USER_ID);
206  return false;
207  }
208  $session_ext_account = ilObjUser::_lookupExternalAccount($session_user_id);
209  $user = new ilECSUser($this->http->request()->getQueryParams());
210  $this->getLogger()->debug('ECS user name: ' . $user->getLogin());
211  $this->getLogger()->debug('Session external account: ' . $session_ext_account);
212  if (!$session_ext_account || strcmp($user->getLogin(), $session_ext_account) !== 0) {
213  $this->getLogger()->debug('No matching session found. Terminating current user session.');
214  $this->authSession->setAuthenticated(false, ANONYMOUS_USER_ID);
215  return false;
216  }
217  // assign to ECS global role
218  $this->rbacAdmin->assignUser($this->getCurrentServer()->getGlobalRole(), $this->authSession->getUserId());
219  return true;
220  }
221 
222 
226  public function handleLogin()
227  {
228  $user = new ilECSUser($this->http->request()->getQueryParams());
229 
230  if (!$usr_id = ilObject::_lookupObjIdByImportId($user->getImportId())) {
231  $username = $this->createUser($user);
232  } else {
233  $username = $this->updateUser($user, $usr_id);
234  }
235 
236  // set user imported
237  $import = new ilECSImport($this->getCurrentServer()->getServerId(), $usr_id);
238  $import->save();
239 
240  // Store remote user data
241  $remoteUserRepository = new ilECSRemoteUserRepository();
242  $remoteUserRepository->createIfNotExisting(
243  $this->getCurrentServer()->getServerId(),
244  $this->getMID(),
245  ilObjUser::_lookupId($username),
246  $user->getImportId()
247  );
248 
249  $this->getLogger()->info('Current user is: ' . $username);
250 
251  return ilObjUser::_lookupId($username);
252  }
253 
254  public function initRemoteUserWithRemoteId(): void
255  {
256  $user = new ilECSUser($this->http->request()->getQueryParams());
257 
258  // Store remote user data
259  $remoteUserRepository = new ilECSRemoteUserRepository();
260  $remoteUserRepository->createIfRemoteUserNotExisting(
261  $this->getCurrentServer()->getServerId(),
262  $this->getMID(),
263  0,
264  $user->getLogin()
265  );
266  }
267 
271  public function validateHash(): bool
272  {
273  // fetch hash
274  $hash = "";
275  if ($this->http->wrapper()->query()->has('ecs_hash')) {
276  $hash = $this->http->wrapper()->query()->retrieve(
277  'ecs_hash',
278  $this->refinery->kindlyTo()->string()
279  );
280  }
281  if ($this->http->wrapper()->query()->has('ecs_hash_url')) {
282  $hashurl = urldecode(
283  $this->http->wrapper()->query()->retrieve(
284  'ecs_hash_url',
285  $this->refinery->kindlyTo()->string()
286  )
287  );
288  $hash = basename(parse_url($hashurl, PHP_URL_PATH));
289  }
290 
291  $this->getLogger()->info('Using ecs hash: ' . $hash);
292  // Check if hash is valid ...
293  try {
294  $connector = new ilECSConnector($this->getCurrentServer());
295  $res = $connector->getAuth($hash);
296  $auths = $res->getResult();
297 
298  $this->getLogger()->dump($auths, ilLogLevel::DEBUG);
299 
300  if ($auths->pid) {
301  try {
302  $reader = ilECSCommunityReader::getInstanceByServerId($this->getCurrentServer()->getServerId());
303  foreach ($reader->getParticipantsByPid($auths->pid) as $participant) {
304  if ($participant->getOrganisation() instanceof \ilECSOrganisation) {
305  $this->abreviation = $participant->getOrganisation()->getAbbreviation();
306  break;
307  }
308  }
309  if (!$this->abreviation) {
310  $this->abreviation = $auths->abbr;
311  }
312  } catch (Exception $e) {
313  $this->getLogger()->warning('Authentication failed with message: ' . $e->getMessage());
314  return false;
315  }
316  } else {
317  $this->abreviation = $auths->abbr;
318  }
319 
320  $this->getLogger()->debug('Got abbreviation: ' . $this->abreviation);
321  } catch (ilECSConnectorException $e) {
322  $this->getLogger()->warning('Authentication failed with message: ' . $e->getMessage());
323  return false;
324  }
325 
326  // read current mid
327  try {
328  $connector = new ilECSConnector($this->getCurrentServer());
329  $details = $connector->getAuth($hash, true);
330 
331  $this->getLogger()->dump($details, ilLogLevel::DEBUG);
332  $this->getLogger()->debug('Token create for mid: ' . $details->getFirstSender());
333 
334  $this->setMID($details->getFirstSender());
335  } catch (ilECSConnectorException $e) {
336  $this->getLogger()->warning('Receiving mid failed with message: ' . $e->getMessage());
337  return false;
338  }
339  return true;
340  }
341 
342 
346  private function initECSServices(): void
347  {
348  $this->servers = ilECSServerSettings::getInstance();
349  }
350 
354  protected function createUser(ilECSUser $user): string
355  {
356  $userObj = new ilObjUser();
357  $userObj->setOwner(SYSTEM_USER_ID);
358 
359  $local_user = ilAuthUtils::_generateLogin($this->getAbreviation() . '_' . $user->getLogin());
360 
361  $newUser["login"] = $local_user;
362  $newUser["firstname"] = $user->getFirstname();
363  $newUser["lastname"] = $user->getLastname();
364  $newUser['email'] = $user->getEmail();
365  $newUser['institution'] = $user->getInstitution();
366 
367  // set "plain md5" password (= no valid password)
368  $newUser["passwd"] = "";
369  $newUser["passwd_type"] = ilObjUser::PASSWD_CRYPTED;
370 
371  $newUser["auth_mode"] = "ecs";
372  $newUser["profile_incomplete"] = 0;
373 
374  // system data
375  $userObj->assignData($newUser);
376  $userObj->setTitle($userObj->getFullname());
377  $userObj->setDescription($userObj->getEmail());
378 
379  // set user language to system language
380  $userObj->setLanguage($this->setting->get("language"));
381 
382  // Time limit
383  $userObj->setTimeLimitOwner(7);
384  $userObj->setTimeLimitUnlimited(false);
385  $userObj->setTimeLimitFrom(time() - 5);
386  $userObj->setTimeLimitUntil(time() + (int) $this->clientIniFile->readVariable("session", "expire"));
387 
388  // Create user in DB
389  $userObj->setOwner(6);
390  $tmp_date = new ilDateTime(time(), IL_CAL_UNIX);
391  $userObj->setAgreeDate($tmp_date->get(IL_CAL_DATETIME));
392  $userObj->create();
393  $userObj->setActive(true);
394  $userObj->saveAsNew();
395  $userObj->updateOwner();
396  $userObj->writePrefs();
397 
398  if ($this->getCurrentServer()->getGlobalRole()) {
399  $this->rbacAdmin->assignUser($this->getCurrentServer()->getGlobalRole(), $userObj->getId());
400  }
401  ilObject::_writeImportId($userObj->getId(), $user->getImportId());
402 
403  $this->getLogger()->info('Created new remote user with usr_id: ' . $user->getImportId());
404 
405  // Send Mail
406  #$this->sendNotification($userObj);
407  $this->resetMailOptions($userObj->getId());
408 
409  return $userObj->getLogin();
410  }
411 
415  protected function updateUser(ilECSUser $user, int $a_local_user_id): string
416  {
417  $user_obj = new ilObjUser($a_local_user_id);
418  $user_obj->setFirstname($user->getFirstname());
419  $user_obj->setLastname($user->getLastname());
420  $user_obj->setEmail($user->getEmail());
421  $user_obj->setInstitution($user->getInstitution());
422  $user_obj->setActive(true);
423 
424  $until = $user_obj->getTimeLimitUntil();
425 
426  if ($until < (time() + (int) $this->clientIniFile->readVariable('session', 'expire'))) {
427  $user_obj->setTimeLimitFrom(time() - 60);
428  $user_obj->setTimeLimitUntil(time() + (int) $this->clientIniFile->readVariable("session", "expire"));
429  }
430  $user_obj->update();
431  $user_obj->refreshLogin();
432 
433  if ($this->getCurrentServer()->getGlobalRole()) {
434  $this->rbacAdmin->assignUser(
435  $this->getCurrentServer()->getGlobalRole(),
436  $user_obj->getId()
437  );
438  }
439 
440  $this->resetMailOptions($a_local_user_id);
441 
442  $this->getLogger()->debug('Finished update of remote user with usr_id: ' . $user->getImportId());
443  return $user_obj->getLogin();
444  }
445 
450  protected function resetMailOptions(int $a_usr_id): void
451  {
452  $options = new ilMailOptions($a_usr_id);
453  $options->setIncomingType(ilMailOptions::INCOMING_LOCAL);
454  $options->updateOptions();
455  }
456 }
static _lookupObjIdByImportId(string $import_id)
Get (latest) object id for an import id.
handleLogin()
Called from base class after successful login.
$res
Definition: ltiservices.php:66
static _generateLogin(string $a_login)
generate free login by starting with a default string and adding postfix numbers
const IL_CAL_DATETIME
Interface of auth credentials.
const ANONYMOUS_USER_ID
Definition: constants.php:27
getFirstname()
get firstname
static _writeImportId(int $obj_id, string $import_id)
write import id to db (static)
getServerSettings()
Get server settings.
handleLoginByAuthMode(ilAuthStatus $status)
Redirects to shibboleth login; to standard login page for LDAP based authentication or authenticates/...
updateUser(ilECSUser $user, int $a_local_user_id)
update existing user
resetMailOptions(int $a_usr_id)
Reset mail options to "local only".
getCurrentServer()
Get current server.
static getInstance()
Get singleton instance.
const SYSTEM_USER_ID
This file contains constants for PHPStan analyis, see: https://phpstan.org/config-reference#constants...
Definition: constants.php:26
static _lookupId($a_user_str)
static _lookupExternalAccount(int $a_user_id)
const IL_CAL_UNIX
doAuthentication(\ilAuthStatus $status)
Try ecs authentication.
while($session_entry=$r->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) return null
createUser(ilECSUser $user)
create new user
getAbreviation()
get abbreviation
handleAuthenticationFail(ilAuthStatus $status, string $a_reason)
Handle failed authentication.
final const INCOMING_LOCAL
Base class for authentication providers (ldap, apache, ...)
ilECSServerSettings $servers
Auth prvider for ecs auth.
static http()
Fetches the global http state from ILIAS.
__construct(\ilAuthCredentials $credentials)
Constructor.
getLastname()
getLastname
static getInstanceByServerId(int $a_server_id)
Get instance by server id.
Collection of ECS settings.
setStatus(int $a_status)
Set auth status.
setCurrentServer(ilECSSetting $server)
Set current server.
global $DIC
Definition: shib_login.php:22
Storage of ECS imported objects.
ilAuthCredentials $credentials
initECSServices()
Init ECS Services.
getLogger()
Get logger.
const PASSWD_CRYPTED
getEmail()
get email
getLogin()
get login
getImportId()
get Email
__construct(Container $dic, ilPlugin $plugin)
setAuthenticatedUserId(int $a_id)
$server
Definition: shib_login.php:24
Class ilRbacAdmin Core functions for role based access control.
getInstitution()
get institution
validateHash()
Validate ECS hash.
Auth status implementation.
static set(string $a_var, $a_val)
Set a value.
Stores relevant user data.