|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * @file |
| 5 | + * Contains \Drupal\restful\Authentication\UserSessionState. |
| 6 | + */ |
| 7 | + |
| 8 | +namespace Drupal\restful\Authentication; |
| 9 | + |
| 10 | +/** |
| 11 | + * Class UserSessionState. |
| 12 | + * |
| 13 | + * @package Drupal\restful\Authentication |
| 14 | + */ |
| 15 | +class UserSessionState implements UserSessionStateInterface { |
| 16 | + |
| 17 | + /** |
| 18 | + * Boolean holding if this is the first switch. |
| 19 | + * |
| 20 | + * @var bool |
| 21 | + */ |
| 22 | + protected static $isSwitched = FALSE; |
| 23 | + |
| 24 | + /** |
| 25 | + * Boolean holding if the session needs to be saved. |
| 26 | + * |
| 27 | + * @var bool |
| 28 | + */ |
| 29 | + protected $needsSaving = FALSE; |
| 30 | + |
| 31 | + /** |
| 32 | + * Object holding the original user. |
| 33 | + * |
| 34 | + * This is saved for switch back purposes. |
| 35 | + * |
| 36 | + * @var object |
| 37 | + */ |
| 38 | + protected $originalUser; |
| 39 | + |
| 40 | + /** |
| 41 | + * {@inheritdoc} |
| 42 | + */ |
| 43 | + public static function isSwitched() { |
| 44 | + return static::$isSwitched; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * {@inheritdoc} |
| 49 | + */ |
| 50 | + public function switchUser($account) { |
| 51 | + global $user; |
| 52 | + |
| 53 | + if (!static::isSwitched() && !$this->originalUser && !$this->needsSaving) { |
| 54 | + // This is the first time a user switched, and there isn't an original |
| 55 | + // user session. |
| 56 | + $this->needsSaving = drupal_save_session(); |
| 57 | + $this->originalUser = $user; |
| 58 | + |
| 59 | + // Don't allow a session to be saved. Provider that require a session to |
| 60 | + // be saved, like the cookie provider, need to explicitly set |
| 61 | + // drupal_save_session(TRUE). |
| 62 | + // @see LoginCookie__1_0::loginUser(). |
| 63 | + drupal_save_session(FALSE); |
| 64 | + } |
| 65 | + |
| 66 | + // Set the global user. |
| 67 | + $user = $account; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Switch the user to the authenticated user, and back. |
| 72 | + * |
| 73 | + * This should be called only for an API call. It should not be used for calls |
| 74 | + * via the menu system, as it might be a login request, so we avoid switching |
| 75 | + * back to the anonymous user. |
| 76 | + */ |
| 77 | + public function switchUserBack() { |
| 78 | + global $user; |
| 79 | + if (!$this->originalUser) { |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + $user = $this->originalUser; |
| 84 | + drupal_save_session($this->needsSaving); |
| 85 | + $this->reset(); |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + * Reset the initial values. |
| 90 | + */ |
| 91 | + protected function reset() { |
| 92 | + // Reset initial values. |
| 93 | + static::$isSwitched = FALSE; |
| 94 | + $this->originalUser = NULL; |
| 95 | + $this->needsSaving = FALSE; |
| 96 | + } |
| 97 | + |
| 98 | +} |
0 commit comments