Passed
Push — master ( 2ca186...7f83bc )
by Alexander
05:08 queued 02:48
created

src/User.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\User;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Throwable;
9
use Yiisoft\Access\AccessCheckerInterface;
10
use Yiisoft\Auth\IdentityInterface;
11
use Yiisoft\Auth\IdentityRepositoryInterface;
12
use Yiisoft\Session\SessionInterface;
13
use Yiisoft\User\Event\AfterLogin;
14
use Yiisoft\User\Event\AfterLogout;
15
use Yiisoft\User\Event\BeforeLogin;
16
use Yiisoft\User\Event\BeforeLogout;
17
18
class User
19
{
20
    private const SESSION_AUTH_ID = '__auth_id';
21
    private const SESSION_AUTH_EXPIRE = '__auth_expire';
22
    private const SESSION_AUTH_ABSOLUTE_EXPIRE = '__auth_absolute_expire';
23
24
    /**
25
     * @var int|null the number of seconds in which the user will be logged out automatically in case of
26
     * remaining inactive. If this property is not set, the user will be logged out after
27
     * the current session expires.
28
     */
29
    private ?int $authTimeout = null;
30
31
    /**
32
     * @var int|null the number of seconds in which the user will be logged out automatically
33
     * regardless of activity.
34
     */
35
    private ?int $absoluteAuthTimeout = null;
36
37
    private IdentityRepositoryInterface $identityRepository;
38
    private EventDispatcherInterface $eventDispatcher;
39
40
    private ?AccessCheckerInterface $accessChecker = null;
41
    private ?IdentityInterface $identity = null;
42
    private ?SessionInterface $session;
43
44
    /**
45
     * @param IdentityRepositoryInterface $identityRepository
46
     * @param EventDispatcherInterface $eventDispatcher
47
     * @param SessionInterface|null $session session to persist authentication status across multiple requests.
48
     * If not set, authentication has to be performed on each request, which is often the case for stateless
49
     * application such as RESTful API.
50
     */
51 22
    public function __construct(
52
        IdentityRepositoryInterface $identityRepository,
53
        EventDispatcherInterface $eventDispatcher,
54
        SessionInterface $session = null
55
    ) {
56 22
        $this->identityRepository = $identityRepository;
57 22
        $this->eventDispatcher = $eventDispatcher;
58 22
        $this->session = $session;
59 22
    }
60
61 1
    public function setAccessChecker(AccessCheckerInterface $accessChecker): void
62
    {
63 1
        $this->accessChecker = $accessChecker;
64 1
    }
65
66
    /**
67
     * Returns the identity object associated with the currently logged-in user.
68
     * This method read the user's authentication data
69
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
70
     *
71
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
72
     *
73
     * @throws Throwable
74
     *
75
     * @return IdentityInterface the identity object associated with the currently logged-in user.
76
     *
77
     * @see logout()
78
     * @see login()
79
     */
80 18
    public function getIdentity(bool $autoRenew = true): IdentityInterface
81
    {
82 18
        if ($this->identity !== null) {
83 10
            return $this->identity;
84
        }
85 10
        if ($this->session === null || !$autoRenew) {
86 3
            return new GuestIdentity();
87
        }
88
        try {
89 7
            $this->renewAuthStatus();
90 1
        } catch (Throwable $e) {
91 1
            $this->identity = null;
92 1
            throw $e;
93
        }
94 6
        return $this->identity ?? new GuestIdentity();
95
    }
96
97
    /**
98
     * Sets the user identity object.
99
     *
100
     * Note that this method does not deal with session. You should usually use {@see switchIdentity()}
101
     * to change the identity of the current user.
102
     *
103
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
104
     * Use {{@see GuestIdentity}} to indicate that the current user is a guest.
105
     */
106 14
    public function setIdentity(IdentityInterface $identity): void
107
    {
108 14
        $this->identity = $identity;
109 14
    }
110
111
    /**
112
     * Logs in a user.
113
     *
114
     * After logging in a user:
115
     * - the user's identity information is obtainable from the {@see getIdentity()}
116
     * - the identity information will be stored in session and be available in the next requests as long as the session
117
     *   remains active or till the user closes the browser. Some browsers, such as Chrome, are keeping session when
118
     *   browser is re-opened.
119
     *
120
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
121
     *
122
     * @return bool whether the user is logged in
123
     */
124 1
    public function login(IdentityInterface $identity): bool
125
    {
126 1
        if ($this->beforeLogin($identity)) {
127 1
            $this->switchIdentity($identity);
128 1
            $this->afterLogin($identity);
129
        }
130 1
        return !$this->isGuest();
131
    }
132
133
    /**
134
     * Logs out the current user.
135
     * This will remove authentication-related session data.
136
     * If `$destroySession` is true, all session data will be removed.
137
     *
138
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
139
     *
140
     * @throws Throwable
141
     *
142
     * @return bool whether the user is logged out
143
     */
144 5
    public function logout(bool $destroySession = true): bool
145
    {
146 5
        $identity = $this->getIdentity();
147 5
        if ($this->isGuest()) {
148 1
            return false;
149
        }
150 4
        if ($this->beforeLogout($identity)) {
151 4
            $this->switchIdentity(new GuestIdentity());
152 4
            if ($destroySession && $this->session) {
153 1
                $this->session->destroy();
154
            }
155
156 4
            $this->afterLogout($identity);
157
        }
158 4
        return $this->isGuest();
159
    }
160
161
    /**
162
     * Returns a value indicating whether the user is a guest (not authenticated).
163
     *
164
     * @return bool whether the current user is a guest.
165
     *
166
     * @see getIdentity()
167
     */
168 8
    public function isGuest(): bool
169
    {
170 8
        return $this->getIdentity() instanceof GuestIdentity;
171
    }
172
173
    /**
174
     * Returns a value that uniquely represents the user.
175
     *
176
     * @throws Throwable
177
     *
178
     * @return string the unique identifier for the user. If `null`, it means the user is a guest.
179
     *
180
     * @see getIdentity()
181
     */
182 3
    public function getId(): ?string
183
    {
184 3
        return $this->getIdentity()->getId();
185
    }
186
187
    /**
188
     * This method is called before logging in a user.
189
     * The default implementation will trigger the {@see BeforeLogin} event.
190
     * If you override this method, make sure you call the parent implementation
191
     * so that the event is triggered.
192
     *
193
     * @param IdentityInterface $identity the user identity information
194
     *
195
     * @return bool whether the user should continue to be logged in
196
     */
197 1
    private function beforeLogin(IdentityInterface $identity): bool
198
    {
199 1
        $event = new BeforeLogin($identity);
200 1
        $this->eventDispatcher->dispatch($event);
201 1
        return $event->isValid();
202
    }
203
204
    /**
205
     * This method is called after the user is successfully logged in.
206
     *
207
     * @param IdentityInterface $identity the user identity information
208
     */
209 1
    private function afterLogin(IdentityInterface $identity): void
210
    {
211 1
        $this->eventDispatcher->dispatch(new AfterLogin($identity));
212 1
    }
213
214
    /**
215
     * This method is invoked when calling {@see logout()} to log out a user.
216
     *
217
     * @param IdentityInterface $identity the user identity information
218
     *
219
     * @return bool whether the user should continue to be logged out
220
     */
221 4
    private function beforeLogout(IdentityInterface $identity): bool
222
    {
223 4
        $event = new BeforeLogout($identity);
224 4
        $this->eventDispatcher->dispatch($event);
225 4
        return $event->isValid();
226
    }
227
228
    /**
229
     * This method is invoked right after a user is logged out via {@see logout()}.
230
     *
231
     * @param IdentityInterface $identity the user identity information
232
     */
233 4
    private function afterLogout(IdentityInterface $identity): void
234
    {
235 4
        $this->eventDispatcher->dispatch(new AfterLogout($identity));
236 4
    }
237
238
    /**
239
     * Switches to a new identity for the current user.
240
     *
241
     * This method use session to store the user identity information.
242
     * Please refer to {@see login()} for more details.
243
     *
244
     * This method is mainly called by {@see login()} and {@see logout()}
245
     * when the current user needs to be associated with the corresponding identity information.
246
     *
247
     * @param IdentityInterface $identity the identity information to be associated with the current user.
248
     * In order to indicate that the user is guest, use {{@see GuestIdentity}}.
249
     */
250 7
    public function switchIdentity(IdentityInterface $identity): void
251
    {
252 7
        $this->setIdentity($identity);
253 7
        if ($this->session === null) {
254 2
            return;
255
        }
256
257 5
        $this->session->regenerateID();
258
259 5
        $this->session->remove(self::SESSION_AUTH_ID);
260 5
        $this->session->remove(self::SESSION_AUTH_EXPIRE);
261
262 5
        if ($identity->getId() === null) {
263 3
            return;
264
        }
265 2
        $this->session->set(self::SESSION_AUTH_ID, $identity->getId());
266 2
        if ($this->authTimeout !== null) {
267 1
            $this->session->set(self::SESSION_AUTH_EXPIRE, time() + $this->authTimeout);
268
        }
269 2
        if ($this->absoluteAuthTimeout !== null) {
270 1
            $this->session->set(self::SESSION_AUTH_ABSOLUTE_EXPIRE, time() + $this->absoluteAuthTimeout);
271
        }
272 2
    }
273
274
    /**
275
     * Updates the authentication status using the information from session.
276
     *
277
     * This method will try to determine the user identity using a session variable.
278
     *
279
     * If {@see authTimeout} is set, this method will refresh the timer.
280
     *
281
     * @throws Throwable
282
     */
283 7
    private function renewAuthStatus(): void
284
    {
285 7
        $id = $this->session->get(self::SESSION_AUTH_ID);
0 ignored issues
show
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

285
        /** @scrutinizer ignore-call */ 
286
        $id = $this->session->get(self::SESSION_AUTH_ID);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
286
287 7
        $identity = null;
288 7
        if ($id !== null) {
289 4
            $identity = $this->identityRepository->findIdentity($id);
290
        }
291 6
        if ($identity === null) {
292 3
            $identity = new GuestIdentity();
293
        }
294 6
        $this->setIdentity($identity);
295
296 6
        if (!($identity instanceof GuestIdentity) && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
297 3
            $expire = $this->authTimeout !== null ? $this->session->get(self::SESSION_AUTH_EXPIRE) : null;
298 3
            $expireAbsolute = $this->absoluteAuthTimeout !== null
299 1
                ? $this->session->get(self::SESSION_AUTH_ABSOLUTE_EXPIRE)
300 3
                : null;
301 3
            if (($expire !== null && $expire < time()) || ($expireAbsolute !== null && $expireAbsolute < time())) {
302 2
                $this->logout(false);
303 1
            } elseif ($this->authTimeout !== null) {
304 1
                $this->session->set(self::SESSION_AUTH_EXPIRE, time() + $this->authTimeout);
305
            }
306
        }
307 6
    }
308
309
    /**
310
     * Checks if the user can perform the operation as specified by the given permission.
311
     *
312
     * Note that you must provide access checker via {{@see User::setAccessChecker()}} in order to use this method.
313
     * Otherwise it will always return false.
314
     *
315
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
316
     * @param array $params name-value pairs that would be passed to the rules associated
317
     * with the roles and permissions assigned to the user.
318
     *
319
     * @throws Throwable
320
     *
321
     * @return bool whether the user can perform the operation as specified by the given permission.
322
     */
323 2
    public function can(string $permissionName, array $params = []): bool
324
    {
325 2
        if ($this->accessChecker === null) {
326 1
            return false;
327
        }
328
329 1
        return $this->accessChecker->userHasPermission($this->getId(), $permissionName, $params);
330
    }
331
332 4
    public function setAuthTimeout(int $timeout = null): self
333
    {
334 4
        $this->authTimeout = $timeout;
335
336 4
        return $this;
337
    }
338
339 2
    public function setAbsoluteAuthTimeout(int $timeout = null): self
340
    {
341 2
        $this->absoluteAuthTimeout = $timeout;
342
343 2
        return $this;
344
    }
345
}
346