Elgg  Version 3.0
sessions.php
Go to the documentation of this file.
1 <?php
2 
5 
20 function elgg_get_session() {
21  return elgg()->session;
22 }
23 
30  return elgg()->session->getLoggedInUser();
31 }
32 
40  return elgg()->session->getLoggedInUserGuid();
41 }
42 
48 function elgg_is_logged_in() {
49  return elgg()->session->isLoggedIn();
50 }
51 
58  return elgg()->session->isAdminLoggedIn();
59 }
60 
72 
73  $user_guid = (int) $user_guid;
74 
76  if (!$entity) {
77  return false;
78  }
79 
80  return $entity->isAdmin();
81 }
82 
99  $pam = new \ElggPAM('user');
100  $credentials = ['username' => $username, 'password' => $password];
101  $result = $pam->authenticate($credentials);
102  if (!$result) {
103  return $pam->getFailureMessage();
104  }
105  return true;
106 }
107 
120 function pam_auth_userpass(array $credentials = []) {
121 
122  if (!isset($credentials['username']) || !isset($credentials['password'])) {
123  return false;
124  }
125 
126  $user = get_user_by_username($credentials['username']);
127  if (!$user) {
128  throw new \LoginException(_elgg_services()->translator->translate('LoginException:UsernameFailure'));
129  }
130 
131  $password_svc = _elgg_services()->passwords;
132  $password = $credentials['password'];
133  $hash = $user->password_hash;
134 
135  if (check_rate_limit_exceeded($user->guid)) {
136  throw new \LoginException(_elgg_services()->translator->translate('LoginException:AccountLocked'));
137  }
138 
139  if (!$password_svc->verify($password, $hash)) {
140  log_login_failure($user->guid);
141  throw new \LoginException(_elgg_services()->translator->translate('LoginException:PasswordFailure'));
142  }
143 
144  if ($password_svc->needsRehash($hash)) {
145  $password_svc->forcePasswordReset($user, $password);
146  }
147 
148  return true;
149 }
150 
160  $user_guid = (int) $user_guid;
162 
163  if (($user_guid) && ($user) && ($user instanceof \ElggUser)) {
164  $fails = (int) $user->getPrivateSetting("login_failures");
165  $fails++;
166 
167  $user->setPrivateSetting("login_failures", $fails);
168  $user->setPrivateSetting("login_failure_$fails", time());
169 
170  return true;
171  }
172 
173  return false;
174  });
175 }
176 
186  $user_guid = (int) $user_guid;
187 
189 
190  if (($user_guid) && ($user) && ($user instanceof \ElggUser)) {
191  $fails = (int) $user->getPrivateSetting("login_failures");
192 
193  if ($fails) {
194  for ($n = 1; $n <= $fails; $n++) {
195  $user->removePrivateSetting("login_failure_$n");
196  }
197 
198  $user->removePrivateSetting("login_failures");
199 
200  return true;
201  }
202 
203  // nothing to reset
204  return true;
205  }
206 
207  return false;
208  });
209 }
210 
220  // 5 failures in 5 minutes causes temporary block on logins
221  $limit = 5;
222  $user_guid = (int) $user_guid;
224 
225  if (($user_guid) && ($user) && ($user instanceof \ElggUser)) {
226  $fails = (int) $user->getPrivateSetting("login_failures");
227  if ($fails >= $limit) {
228  $cnt = 0;
229  $time = time();
230  for ($n = $fails; $n > 0; $n--) {
231  $f = $user->getPrivateSetting("login_failure_$n");
232  if ($f > $time - (60 * 5)) {
233  $cnt++;
234  }
235 
236  if ($cnt == $limit) {
237  // Limit reached
238  return true;
239  }
240  }
241  }
242  }
243 
244  return false;
245  });
246 }
247 
257 function elgg_set_cookie(\ElggCookie $cookie) {
258  return _elgg_services()->responseFactory->setCookie($cookie);
259 }
260 
273 function login(\ElggUser $user, $persistent = false) {
274  if ($user->isBanned()) {
275  throw new \LoginException(elgg_echo('LoginException:BannedUser'));
276  }
277 
278  $session = elgg()->session;
279 
280  // give plugins a chance to reject the login of this user (no user in session!)
281  if (!elgg_trigger_before_event('login', 'user', $user)) {
282  throw new \LoginException(elgg_echo('LoginException:Unknown'));
283  }
284 
285  // #5933: set logged in user early so code in login event will be able to
286  // use elgg_get_logged_in_user_entity().
287  $session->setLoggedInUser($user);
288 
289  // re-register at least the core language file for users with language other than site default
290  elgg()->translator->registerTranslations(\Elgg\Project\Paths::elgg() . 'languages/');
291 
292  // if remember me checked, set cookie with token and store hash(token) for user
293  if ($persistent) {
294  _elgg_services()->persistentLogin->makeLoginPersistent($user);
295  }
296 
297  // User's privilege has been elevated, so change the session id (prevents session fixation)
298  $session->migrate();
299 
300  $user->setLastLogin();
301  reset_login_failure_count($user->guid);
302 
303  elgg_trigger_after_event('login', 'user', $user);
304 
305  return true;
306 }
307 
313 function logout() {
314  $session = elgg()->session;
315  $user = $session->getLoggedInUser();
316  if (!$user) {
317  return false;
318  }
319 
320  if (!elgg_trigger_before_event('logout', 'user', $user)) {
321  return false;
322  }
323 
324  _elgg_services()->persistentLogin->removePersistentLogin();
325 
326  // pass along any messages into new session
327  $old_msg = $session->get(SystemMessagesService::SESSION_KEY, []);
328  $session->invalidate();
329  $session->set(SystemMessagesService::SESSION_KEY, $old_msg);
330 
331  elgg_trigger_after_event('logout', 'user', $user);
332 
333  return true;
334 }
335 
346 
347  $session = elgg_get_session();
348  if ($session->has('last_forward_from')) {
349  $forward_url = $session->get('last_forward_from');
350  $session->remove('last_forward_from');
351  $forward_source = 'last_forward_from';
352  } elseif ($request->getParam('returntoreferer')) {
354  $forward_source = 'return_to_referer';
355  } else {
356  // forward to main index page
357  $forward_url = '';
358  $forward_source = null;
359  }
360 
361  $params = [
362  'request' => $request,
363  'user' => $user,
364  'source' => $forward_source,
365  ];
366 
367  return elgg_trigger_plugin_hook('login:forward', 'user', $params, $forward_url);
368 
369 }
370 
381 
382  $time = (int) $hook->getParam('time', time());
383  _elgg_services()->persistentLogin->removeExpiredTokens($time);
384 }
385 
394 function _elgg_session_boot(ServiceProvider $services) {
395  $services->timer->begin([__FUNCTION__]);
396 
397  $session = $services->session;
398  $session->start();
399 
400  // test whether we have a user session
401  if ($session->has('guid')) {
403  $user = $services->entityTable->get($session->get('guid'), 'user');
404  if (!$user) {
405  // OMG user has been deleted.
406  $session->invalidate();
407  forward('');
408  }
409 
410  $services->persistentLogin->replaceLegacyToken($user);
411  } else {
412  $user = $services->persistentLogin->bootSession();
413  if ($user) {
414  $services->persistentLogin->updateTokenUsage($user);
415  }
416  }
417 
418  if ($user) {
419  $session->setLoggedInUser($user);
420  $user->setLastAction();
421 
422  // logout a user with open session who has been banned
423  if ($user->isBanned()) {
424  logout();
425  return false;
426  }
427  }
428 
429  $services->timer->end([__FUNCTION__]);
430  return true;
431 }
432 
436 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
437  register_pam_handler('pam_auth_userpass');
438 
439  $hooks->registerHandler('cron', 'daily', '_elgg_session_cleanup_persistent_login');
440 };
elgg_call(int $flags, Closure $closure)
Calls a callable autowiring the arguments using public DI services and applying logic based on flags...
Definition: elgglib.php:1176
elgg_is_logged_in()
Returns whether or not the user is currently logged in.
Definition: sessions.php:48
if(!$entity->delete()) $forward_url
Definition: delete.php:30
$username
Definition: delete.php:23
_elgg_get_login_forward_url(\Elgg\Request $request,\ElggUser $user)
Determine which URL the user should be forwarded to upon successful login.
Definition: sessions.php:345
$params
Saves global plugin settings.
Definition: save.php:13
get_user($guid)
Get a user object from a GUID.
Definition: users.php:40
elgg_is_admin_logged_in()
Returns whether or not the viewer is currently logged in and an admin user.
Definition: sessions.php:57
register_pam_handler($handler, $importance="sufficient", $policy="user")
Register a PAM handler.
Definition: pam.php:39
pam_auth_userpass(array $credentials=[])
Hook into the PAM system which accepts a username and password and attempts to authenticate it agains...
Definition: sessions.php:120
$request
Page handler for autocomplete endpoint.
Definition: livesearch.php:9
elgg_get_session()
Gets Elgg&#39;s session object.
Definition: sessions.php:20
Events service.
setLastLogin()
Sets the last logon time of the user to right now.
Definition: ElggUser.php:237
reset_login_failure_count($user_guid)
Resets the fail login count for $user_guid.
Definition: sessions.php:184
elgg forward
Meant to mimic the php forward() function by simply redirecting the user to another page...
Definition: elgglib.js:417
_elgg_session_cleanup_persistent_login(\Elgg\Hook $hook)
Cleanup expired persistent login tokens from the database.
Definition: sessions.php:380
elgg_echo($message_key, array $args=[], $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
elgg_trigger_before_event($event, $object_type, $object=null)
Trigger a "Before event" indicating a process is about to begin.
Definition: elgglib.php:534
check_rate_limit_exceeded($user_guid)
Checks if the rate limit of failed logins has been exceeded for $user_guid.
Definition: sessions.php:218
get_user_by_username($username)
Get user by username.
Definition: users.php:61
$user_guid
Validate a user.
Definition: validate.php:6
$persistent
Definition: login.php:10
const ELGG_IGNORE_ACCESS
elgg_call() flags
Definition: constants.php:156
Configuration exception.
$limit
Definition: userpicker.php:52
if(!$user||!$user->canEdit()) $password
Base class for events and hooks.
$entity
Definition: reset.php:8
const ELGG_SHOW_DISABLED_ENTITIES
Definition: constants.php:158
if(!$entity instanceof ElggEntity) $time
Definition: time.php:21
elgg_is_admin_user($user_guid)
Check if the given user has full access.
Definition: sessions.php:71
$user
Definition: ban.php:7
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Definition: elgglib.php:720
if($item instanceof\ElggEntity) elseif($item instanceof\ElggRiverItem) elseif(is_callable([$item, 'getType']))
Definition: item.php:39
elgg_set_cookie(\ElggCookie $cookie)
Set a cookie, but allow plugins to customize it first.
Definition: sessions.php:257
logout()
Log the current user out.
Definition: sessions.php:313
const REFERER
Definition: constants.php:52
elgg_authenticate($username, $password)
Perform user authentication with a given username and password.
Definition: sessions.php:98
login(\ElggUser $user, $persistent=false)
Logs in a specified .
Definition: sessions.php:273
_elgg_services()
Get the global service provider.
Definition: elgglib.php:1292
elgg_trigger_after_event($event, $object_type, $object=null)
Trigger an "After event" indicating a process has finished.
Definition: elgglib.php:553
elgg_get_logged_in_user_entity()
Return the current logged in user, or null if no user is logged in.
Definition: sessions.php:29
isBanned()
Is this user banned or not?
Definition: ElggUser.php:171
log_login_failure($user_guid)
Log a failed login for $user_guid.
Definition: sessions.php:158
elgg_get_logged_in_user_guid()
Return the current logged in user by guid.
Definition: sessions.php:39
var elgg
Definition: elgglib.js:4
get_entity($guid)
Loads and returns an entity object from a guid.
Definition: entities.php:87