Elgg  Version 4.x
PersistentLoginService.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg;
4 
7 
18 
19  use TimeUsing;
20 
24  protected $cookie_config;
25 
29  protected $cookie_token;
30 
34  protected $session;
35 
39  protected $crypto;
40 
45 
50  public $_callable_elgg_set_cookie = 'elgg_set_cookie';
51 
61  public function __construct(
62  UsersRememberMeCookiesTable $cookie_table,
64  \Elgg\Security\Crypto $crypto,
66  \Elgg\Http\Request $request) {
67  $this->persistent_cookie_table = $cookie_table;
68  $this->session = $session;
69  $this->crypto = $crypto;
70 
71  $global_cookies_config = $config->getCookieConfig();
72 
73  $this->cookie_config = $global_cookies_config['remember_me'];
74  $this->cookie_token = $request->cookies->get($this->cookie_config['name'], '');
75  }
76 
84  public function makeLoginPersistent(\ElggUser $user): void {
85  $token = $this->generateToken();
86  $hash = $this->hashToken($token);
87 
88  $this->persistent_cookie_table->insertHash($user, $hash);
89  $this->setCookie($token);
90  $this->setSessionToken($token);
91  }
92 
98  public function removePersistentLogin(): void {
99  if ($this->cookie_token) {
100  $client_hash = $this->hashToken($this->cookie_token);
101  $this->persistent_cookie_table->deleteHash($client_hash);
102  }
103 
104  $this->setCookie('');
105  $this->setSessionToken('');
106  }
107 
116  public function handlePasswordChange(\ElggUser $subject, \ElggUser $modifier = null): void {
117  $this->persistent_cookie_table->deleteAllHashes($subject);
118  if (!$modifier || ($modifier->guid !== $subject->guid) || !$this->cookie_token) {
119  return;
120  }
121 
122  $this->makeLoginPersistent($subject);
123  }
124 
131  public function bootSession(): ?\ElggUser {
132  if (!$this->cookie_token) {
133  return null;
134  }
135 
136  // is this token good?
137  $user = $this->getUserFromToken($this->cookie_token);
138  if ($user) {
139  $this->setSessionToken($this->cookie_token);
140 
141  return $user;
142  }
143 
144  $this->setCookie('');
145  return null;
146  }
147 
155  public function getUserFromToken(string $token): ?\ElggUser {
156  if (empty($token)) {
157  return null;
158  }
159 
160  $hash = $this->hashToken($token);
161  return $this->getUserFromHash($hash);
162  }
163 
172  public function getUserFromHash(string $hash): ?\ElggUser {
173  if (empty($hash)) {
174  return null;
175  }
176 
177  $user_row = $this->persistent_cookie_table->getRowFromHash($hash);
178  if (empty($user_row)) {
179  return null;
180  }
181 
182  $user = get_user($user_row->guid);
183  return ($user instanceof \ElggUser) ? $user : null;
184  }
185 
193  public function updateTokenUsage(\ElggUser $user): ?bool {
194  if (!$this->cookie_token) {
195  return null;
196  }
197 
198  // update the database record
199  // not interested in number of updated rows, as an update in the same second won't update the row
200  $this->persistent_cookie_table->updateHash($user, $this->hashToken($this->cookie_token));
201 
202  // also update the cookie lifetime client-side
203  $this->setCookie($this->cookie_token);
204 
205  return true;
206  }
207 
215  public function removeExpiredTokens($time): bool {
216  $time = Values::normalizeTime($time);
217 
218  $expires = Values::normalizeTime($this->cookie_config['expire']);
219  $diff = $time->diff($expires);
220 
221  $time->sub($diff);
222  if ($time->getTimestamp() > time()) {
223  return false;
224  }
225 
226  return (bool) $this->persistent_cookie_table->deleteExpiredHashes($time->getTimestamp());
227  }
228 
236  protected function hashToken(string $token): string {
237  // note: with user passwords, you'd want legit password hashing, but since these are randomly
238  // generated and long tokens, rainbow tables aren't any help.
239  return md5($token);
240  }
241 
249  protected function setCookie(string $token): void {
250  $cookie = new \ElggCookie($this->cookie_config['name']);
251  foreach (['expire', 'path', 'domain', 'secure', 'httpOnly'] as $key) {
252  $cookie->$key = $this->cookie_config[strtolower($key)];
253  }
254 
255  $cookie->value = $token;
256  if (!$token) {
257  $cookie->expire = $this->getCurrentTime('-30 days')->getTimestamp();
258  }
259 
260  call_user_func($this->_callable_elgg_set_cookie, $cookie);
261  }
262 
270  protected function setSessionToken(string $token): void {
271  if ($token) {
272  $this->session->set('code', $token);
273  } else {
274  $this->session->remove('code');
275  }
276  }
277 
286  protected function generateToken(): string {
287  return 'z' . $this->crypto->getRandomString(31);
288  }
289 }
get_user($guid)
Get a user object from a GUID.
Definition: users.php:20
makeLoginPersistent(\ElggUser $user)
Make the user&#39;s login persistent.
bootSession()
Boot the persistent login session, possibly returning the user who should be silently logged in...
$request
Definition: livesearch.php:11
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it plus any associated interface definition plus the scripts used to control compilation and installation of the executable as a special the source code distributed need not include anything that is normally and so on of the operating system on which the executable unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated then offering equivalent access to copy the source code from the same place counts as distribution of the source even though third parties are not compelled to copy the source along with the object code You may not or distribute the Program except as expressly provided under this License Any attempt otherwise to sublicense or distribute the Program is void
Definition: LICENSE.txt:215
if(!$annotation instanceof ElggAnnotation) $time
Definition: time.php:20
trait TimeUsing
Adds methods for setting the current time (for testing)
Definition: TimeUsing.php:10
setSessionToken(string $token)
Store the token in the session (or remove it from the session)
Manage the users_remember_me_cookies table.
$config
Advanced site settings, debugging section.
Definition: debugging.php:6
getCurrentTime($modifier= '')
Get the (cloned) time.
Definition: TimeUsing.php:25
getUserFromHash(string $hash)
Find a user with the given hash.
__construct(UsersRememberMeCookiesTable $cookie_table,\ElggSession $session,\Elgg\Security\Crypto $crypto,\Elgg\Config $config,\Elgg\Http\Request $request)
Constructor.
$user
Definition: ban.php:7
removeExpiredTokens($time)
Remove all persistent codes from the database which have expired based on the cookie config...
$token
if($container instanceof ElggGroup &&$container->guid!=elgg_get_page_owner_guid()) $key
Definition: summary.php:44
generateToken()
Generate a random token (base 64 URL)
if(isset($_COOKIE['elggperm'])) $session
Definition: login_as.php:28
updateTokenUsage(\ElggUser $user)
Update the timestamp linked to a persistent cookie code, this indicates that the code was used recent...
Request container.
Definition: Request.php:12
removePersistentLogin()
Remove the persisted login token from client and server.
setCookie(string $token)
Store the token in the client cookie (or remove the cookie)
hashToken(string $token)
Create a hash from the token.
handlePasswordChange(\ElggUser $subject,\ElggUser $modifier=null)
Handle a password change.
$subject
Definition: useradd.php:60
getUserFromToken(string $token)
Get a user from a persistent cookie token.