Projekt

Obecné

Profil

Stáhnout (20.5 KB) Statistiky
| Větev: | Revize:
1
<?php
2

    
3
namespace Illuminate\Auth;
4

    
5
use RuntimeException;
6
use Illuminate\Support\Str;
7
use Illuminate\Http\Response;
8
use Illuminate\Contracts\Events\Dispatcher;
9
use Illuminate\Contracts\Auth\UserProvider;
10
use Illuminate\Contracts\Auth\StatefulGuard;
11
use Symfony\Component\HttpFoundation\Request;
12
use Illuminate\Contracts\Auth\SupportsBasicAuth;
13
use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
14
use Symfony\Component\HttpFoundation\Session\SessionInterface;
15
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
16

    
17
class SessionGuard implements StatefulGuard, SupportsBasicAuth
18
{
19
    use GuardHelpers;
20

    
21
    /**
22
     * The name of the Guard. Typically "session".
23
     *
24
     * Corresponds to driver name in authentication configuration.
25
     *
26
     * @var string
27
     */
28
    protected $name;
29

    
30
    /**
31
     * The user we last attempted to retrieve.
32
     *
33
     * @var \Illuminate\Contracts\Auth\Authenticatable
34
     */
35
    protected $lastAttempted;
36

    
37
    /**
38
     * Indicates if the user was authenticated via a recaller cookie.
39
     *
40
     * @var bool
41
     */
42
    protected $viaRemember = false;
43

    
44
    /**
45
     * The session used by the guard.
46
     *
47
     * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
48
     */
49
    protected $session;
50

    
51
    /**
52
     * The Illuminate cookie creator service.
53
     *
54
     * @var \Illuminate\Contracts\Cookie\QueueingFactory
55
     */
56
    protected $cookie;
57

    
58
    /**
59
     * The request instance.
60
     *
61
     * @var \Symfony\Component\HttpFoundation\Request
62
     */
63
    protected $request;
64

    
65
    /**
66
     * The event dispatcher instance.
67
     *
68
     * @var \Illuminate\Contracts\Events\Dispatcher
69
     */
70
    protected $events;
71

    
72
    /**
73
     * Indicates if the logout method has been called.
74
     *
75
     * @var bool
76
     */
77
    protected $loggedOut = false;
78

    
79
    /**
80
     * Indicates if a token user retrieval has been attempted.
81
     *
82
     * @var bool
83
     */
84
    protected $tokenRetrievalAttempted = false;
85

    
86
    /**
87
     * Create a new authentication guard.
88
     *
89
     * @param  string  $name
90
     * @param  \Illuminate\Contracts\Auth\UserProvider  $provider
91
     * @param  \Symfony\Component\HttpFoundation\Session\SessionInterface  $session
92
     * @param  \Symfony\Component\HttpFoundation\Request  $request
93
     * @return void
94
     */
95
    public function __construct($name,
96
                                UserProvider $provider,
97
                                SessionInterface $session,
98
                                Request $request = null)
99
    {
100
        $this->name = $name;
101
        $this->session = $session;
102
        $this->request = $request;
103
        $this->provider = $provider;
104
    }
105

    
106
    /**
107
     * Get the currently authenticated user.
108
     *
109
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
110
     */
111
    public function user()
112
    {
113
        if ($this->loggedOut) {
114
            return;
115
        }
116

    
117
        // If we've already retrieved the user for the current request we can just
118
        // return it back immediately. We do not want to fetch the user data on
119
        // every call to this method because that would be tremendously slow.
120
        if (! is_null($this->user)) {
121
            return $this->user;
122
        }
123

    
124
        $id = $this->session->get($this->getName());
125

    
126
        // First we will try to load the user using the identifier in the session if
127
        // one exists. Otherwise we will check for a "remember me" cookie in this
128
        // request, and if one exists, attempt to retrieve the user using that.
129
        $user = null;
130

    
131
        if (! is_null($id)) {
132
            $user = $this->provider->retrieveById($id);
133
        }
134

    
135
        // If the user is null, but we decrypt a "recaller" cookie we can attempt to
136
        // pull the user data on that cookie which serves as a remember cookie on
137
        // the application. Once we have a user we can return it to the caller.
138
        $recaller = $this->getRecaller();
139

    
140
        if (is_null($user) && ! is_null($recaller)) {
141
            $user = $this->getUserByRecaller($recaller);
142

    
143
            if ($user) {
144
                $this->updateSession($user->getAuthIdentifier());
145

    
146
                $this->fireLoginEvent($user, true);
147
            }
148
        }
149

    
150
        return $this->user = $user;
151
    }
152

    
153
    /**
154
     * Get the ID for the currently authenticated user.
155
     *
156
     * @return int|null
157
     */
158
    public function id()
159
    {
160
        if ($this->loggedOut) {
161
            return;
162
        }
163

    
164
        $id = $this->session->get($this->getName());
165

    
166
        if (is_null($id) && $this->user()) {
167
            $id = $this->user()->getAuthIdentifier();
168
        }
169

    
170
        return $id;
171
    }
172

    
173
    /**
174
     * Pull a user from the repository by its recaller ID.
175
     *
176
     * @param  string  $recaller
177
     * @return mixed
178
     */
179
    protected function getUserByRecaller($recaller)
180
    {
181
        if ($this->validRecaller($recaller) && ! $this->tokenRetrievalAttempted) {
182
            $this->tokenRetrievalAttempted = true;
183

    
184
            list($id, $token) = explode('|', $recaller, 2);
185

    
186
            $this->viaRemember = ! is_null($user = $this->provider->retrieveByToken($id, $token));
187

    
188
            return $user;
189
        }
190
    }
191

    
192
    /**
193
     * Get the decrypted recaller cookie for the request.
194
     *
195
     * @return string|null
196
     */
197
    protected function getRecaller()
198
    {
199
        return $this->request->cookies->get($this->getRecallerName());
200
    }
201

    
202
    /**
203
     * Get the user ID from the recaller cookie.
204
     *
205
     * @return string|null
206
     */
207
    protected function getRecallerId()
208
    {
209
        if ($this->validRecaller($recaller = $this->getRecaller())) {
210
            return head(explode('|', $recaller));
211
        }
212
    }
213

    
214
    /**
215
     * Determine if the recaller cookie is in a valid format.
216
     *
217
     * @param  mixed  $recaller
218
     * @return bool
219
     */
220
    protected function validRecaller($recaller)
221
    {
222
        if (! is_string($recaller) || ! Str::contains($recaller, '|')) {
223
            return false;
224
        }
225

    
226
        $segments = explode('|', $recaller);
227

    
228
        return count($segments) == 2 && trim($segments[0]) !== '' && trim($segments[1]) !== '';
229
    }
230

    
231
    /**
232
     * Log a user into the application without sessions or cookies.
233
     *
234
     * @param  array  $credentials
235
     * @return bool
236
     */
237
    public function once(array $credentials = [])
238
    {
239
        if ($this->validate($credentials)) {
240
            $this->setUser($this->lastAttempted);
241

    
242
            return true;
243
        }
244

    
245
        return false;
246
    }
247

    
248
    /**
249
     * Validate a user's credentials.
250
     *
251
     * @param  array  $credentials
252
     * @return bool
253
     */
254
    public function validate(array $credentials = [])
255
    {
256
        return $this->attempt($credentials, false, false);
257
    }
258

    
259
    /**
260
     * Attempt to authenticate using HTTP Basic Auth.
261
     *
262
     * @param  string  $field
263
     * @param  array  $extraConditions
264
     * @return \Symfony\Component\HttpFoundation\Response|null
265
     */
266
    public function basic($field = 'email', $extraConditions = [])
267
    {
268
        if ($this->check()) {
269
            return;
270
        }
271

    
272
        // If a username is set on the HTTP basic request, we will return out without
273
        // interrupting the request lifecycle. Otherwise, we'll need to generate a
274
        // request indicating that the given credentials were invalid for login.
275
        if ($this->attemptBasic($this->getRequest(), $field, $extraConditions)) {
276
            return;
277
        }
278

    
279
        return $this->getBasicResponse();
280
    }
281

    
282
    /**
283
     * Perform a stateless HTTP Basic login attempt.
284
     *
285
     * @param  string  $field
286
     * @param  array  $extraConditions
287
     * @return \Symfony\Component\HttpFoundation\Response|null
288
     */
289
    public function onceBasic($field = 'email', $extraConditions = [])
290
    {
291
        $credentials = $this->getBasicCredentials($this->getRequest(), $field);
292

    
293
        if (! $this->once(array_merge($credentials, $extraConditions))) {
294
            return $this->getBasicResponse();
295
        }
296
    }
297

    
298
    /**
299
     * Attempt to authenticate using basic authentication.
300
     *
301
     * @param  \Symfony\Component\HttpFoundation\Request  $request
302
     * @param  string  $field
303
     * @param  array  $extraConditions
304
     * @return bool
305
     */
306
    protected function attemptBasic(Request $request, $field, $extraConditions = [])
307
    {
308
        if (! $request->getUser()) {
309
            return false;
310
        }
311

    
312
        $credentials = $this->getBasicCredentials($request, $field);
313

    
314
        return $this->attempt(array_merge($credentials, $extraConditions));
315
    }
316

    
317
    /**
318
     * Get the credential array for a HTTP Basic request.
319
     *
320
     * @param  \Symfony\Component\HttpFoundation\Request  $request
321
     * @param  string  $field
322
     * @return array
323
     */
324
    protected function getBasicCredentials(Request $request, $field)
325
    {
326
        return [$field => $request->getUser(), 'password' => $request->getPassword()];
327
    }
328

    
329
    /**
330
     * Get the response for basic authentication.
331
     *
332
     * @return \Symfony\Component\HttpFoundation\Response
333
     */
334
    protected function getBasicResponse()
335
    {
336
        $headers = ['WWW-Authenticate' => 'Basic'];
337

    
338
        return new Response('Invalid credentials.', 401, $headers);
339
    }
340

    
341
    /**
342
     * Attempt to authenticate a user using the given credentials.
343
     *
344
     * @param  array  $credentials
345
     * @param  bool   $remember
346
     * @param  bool   $login
347
     * @return bool
348
     */
349
    public function attempt(array $credentials = [], $remember = false, $login = true)
350
    {
351
        $this->fireAttemptEvent($credentials, $remember, $login);
352

    
353
        $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
354

    
355
        // If an implementation of UserInterface was returned, we'll ask the provider
356
        // to validate the user against the given credentials, and if they are in
357
        // fact valid we'll log the users into the application and return true.
358
        if ($this->hasValidCredentials($user, $credentials)) {
359
            if ($login) {
360
                $this->login($user, $remember);
361
            }
362

    
363
            return true;
364
        }
365

    
366
        // If the authentication attempt fails we will fire an event so that the user
367
        // may be notified of any suspicious attempts to access their account from
368
        // an unrecognized user. A developer may listen to this event as needed.
369
        if ($login) {
370
            $this->fireFailedEvent($user, $credentials);
371
        }
372

    
373
        return false;
374
    }
375

    
376
    /**
377
     * Determine if the user matches the credentials.
378
     *
379
     * @param  mixed  $user
380
     * @param  array  $credentials
381
     * @return bool
382
     */
383
    protected function hasValidCredentials($user, $credentials)
384
    {
385
        return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
386
    }
387

    
388
    /**
389
     * Fire the attempt event with the arguments.
390
     *
391
     * @param  array  $credentials
392
     * @param  bool  $remember
393
     * @param  bool  $login
394
     * @return void
395
     */
396
    protected function fireAttemptEvent(array $credentials, $remember, $login)
397
    {
398
        if (isset($this->events)) {
399
            $this->events->fire(new Events\Attempting(
400
                $credentials, $remember, $login
401
            ));
402
        }
403
    }
404

    
405
    /**
406
     * Fire the failed authentication attempt event with the given arguments.
407
     *
408
     * @param  \Illuminate\Contracts\Auth\Authenticatable|null  $user
409
     * @param  array  $credentials
410
     * @return void
411
     */
412
    protected function fireFailedEvent($user, array $credentials)
413
    {
414
        if (isset($this->events)) {
415
            $this->events->fire(new Events\Failed($user, $credentials));
416
        }
417
    }
418

    
419
    /**
420
     * Register an authentication attempt event listener.
421
     *
422
     * @param  mixed  $callback
423
     * @return void
424
     */
425
    public function attempting($callback)
426
    {
427
        if (isset($this->events)) {
428
            $this->events->listen(Events\Attempting::class, $callback);
429
        }
430
    }
431

    
432
    /**
433
     * Log a user into the application.
434
     *
435
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
436
     * @param  bool  $remember
437
     * @return void
438
     */
439
    public function login(AuthenticatableContract $user, $remember = false)
440
    {
441
        $this->updateSession($user->getAuthIdentifier());
442

    
443
        // If the user should be permanently "remembered" by the application we will
444
        // queue a permanent cookie that contains the encrypted copy of the user
445
        // identifier. We will then decrypt this later to retrieve the users.
446
        if ($remember) {
447
            $this->createRememberTokenIfDoesntExist($user);
448

    
449
            $this->queueRecallerCookie($user);
450
        }
451

    
452
        // If we have an event dispatcher instance set we will fire an event so that
453
        // any listeners will hook into the authentication events and run actions
454
        // based on the login and logout events fired from the guard instances.
455
        $this->fireLoginEvent($user, $remember);
456

    
457
        $this->setUser($user);
458
    }
459

    
460
    /**
461
     * Fire the login event if the dispatcher is set.
462
     *
463
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
464
     * @param  bool  $remember
465
     * @return void
466
     */
467
    protected function fireLoginEvent($user, $remember = false)
468
    {
469
        if (isset($this->events)) {
470
            $this->events->fire(new Events\Login($user, $remember));
471
        }
472
    }
473

    
474
    /**
475
     * Update the session with the given ID.
476
     *
477
     * @param  string  $id
478
     * @return void
479
     */
480
    protected function updateSession($id)
481
    {
482
        $this->session->set($this->getName(), $id);
483

    
484
        $this->session->migrate(true);
485
    }
486

    
487
    /**
488
     * Log the given user ID into the application.
489
     *
490
     * @param  mixed  $id
491
     * @param  bool   $remember
492
     * @return \Illuminate\Contracts\Auth\Authenticatable
493
     */
494
    public function loginUsingId($id, $remember = false)
495
    {
496
        $user = $this->provider->retrieveById($id);
497

    
498
        if (! is_null($user)) {
499
            $this->login($user, $remember);
500

    
501
            return $user;
502
        }
503

    
504
        return false;
505
    }
506

    
507
    /**
508
     * Log the given user ID into the application without sessions or cookies.
509
     *
510
     * @param  mixed  $id
511
     * @return bool
512
     */
513
    public function onceUsingId($id)
514
    {
515
        $user = $this->provider->retrieveById($id);
516

    
517
        if (! is_null($user)) {
518
            $this->setUser($user);
519

    
520
            return true;
521
        }
522

    
523
        return false;
524
    }
525

    
526
    /**
527
     * Queue the recaller cookie into the cookie jar.
528
     *
529
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
530
     * @return void
531
     */
532
    protected function queueRecallerCookie(AuthenticatableContract $user)
533
    {
534
        $value = $user->getAuthIdentifier().'|'.$user->getRememberToken();
535

    
536
        $this->getCookieJar()->queue($this->createRecaller($value));
537
    }
538

    
539
    /**
540
     * Create a "remember me" cookie for a given ID.
541
     *
542
     * @param  string  $value
543
     * @return \Symfony\Component\HttpFoundation\Cookie
544
     */
545
    protected function createRecaller($value)
546
    {
547
        return $this->getCookieJar()->forever($this->getRecallerName(), $value);
548
    }
549

    
550
    /**
551
     * Log the user out of the application.
552
     *
553
     * @return void
554
     */
555
    public function logout()
556
    {
557
        $user = $this->user();
558

    
559
        // If we have an event dispatcher instance, we can fire off the logout event
560
        // so any further processing can be done. This allows the developer to be
561
        // listening for anytime a user signs out of this application manually.
562
        $this->clearUserDataFromStorage();
563

    
564
        if (! is_null($this->user)) {
565
            $this->refreshRememberToken($user);
566
        }
567

    
568
        if (isset($this->events)) {
569
            $this->events->fire(new Events\Logout($user));
570
        }
571

    
572
        // Once we have fired the logout event we will clear the users out of memory
573
        // so they are no longer available as the user is no longer considered as
574
        // being signed into this application and should not be available here.
575
        $this->user = null;
576

    
577
        $this->loggedOut = true;
578
    }
579

    
580
    /**
581
     * Remove the user data from the session and cookies.
582
     *
583
     * @return void
584
     */
585
    protected function clearUserDataFromStorage()
586
    {
587
        $this->session->remove($this->getName());
588

    
589
        if (! is_null($this->getRecaller())) {
590
            $recaller = $this->getRecallerName();
591

    
592
            $this->getCookieJar()->queue($this->getCookieJar()->forget($recaller));
593
        }
594
    }
595

    
596
    /**
597
     * Refresh the "remember me" token for the user.
598
     *
599
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
600
     * @return void
601
     */
602
    protected function refreshRememberToken(AuthenticatableContract $user)
603
    {
604
        $user->setRememberToken($token = Str::random(60));
605

    
606
        $this->provider->updateRememberToken($user, $token);
607
    }
608

    
609
    /**
610
     * Create a new "remember me" token for the user if one doesn't already exist.
611
     *
612
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
613
     * @return void
614
     */
615
    protected function createRememberTokenIfDoesntExist(AuthenticatableContract $user)
616
    {
617
        if (empty($user->getRememberToken())) {
618
            $this->refreshRememberToken($user);
619
        }
620
    }
621

    
622
    /**
623
     * Get the cookie creator instance used by the guard.
624
     *
625
     * @return \Illuminate\Contracts\Cookie\QueueingFactory
626
     *
627
     * @throws \RuntimeException
628
     */
629
    public function getCookieJar()
630
    {
631
        if (! isset($this->cookie)) {
632
            throw new RuntimeException('Cookie jar has not been set.');
633
        }
634

    
635
        return $this->cookie;
636
    }
637

    
638
    /**
639
     * Set the cookie creator instance used by the guard.
640
     *
641
     * @param  \Illuminate\Contracts\Cookie\QueueingFactory  $cookie
642
     * @return void
643
     */
644
    public function setCookieJar(CookieJar $cookie)
645
    {
646
        $this->cookie = $cookie;
647
    }
648

    
649
    /**
650
     * Get the event dispatcher instance.
651
     *
652
     * @return \Illuminate\Contracts\Events\Dispatcher
653
     */
654
    public function getDispatcher()
655
    {
656
        return $this->events;
657
    }
658

    
659
    /**
660
     * Set the event dispatcher instance.
661
     *
662
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
663
     * @return void
664
     */
665
    public function setDispatcher(Dispatcher $events)
666
    {
667
        $this->events = $events;
668
    }
669

    
670
    /**
671
     * Get the session store used by the guard.
672
     *
673
     * @return \Illuminate\Session\Store
674
     */
675
    public function getSession()
676
    {
677
        return $this->session;
678
    }
679

    
680
    /**
681
     * Get the user provider used by the guard.
682
     *
683
     * @return \Illuminate\Contracts\Auth\UserProvider
684
     */
685
    public function getProvider()
686
    {
687
        return $this->provider;
688
    }
689

    
690
    /**
691
     * Set the user provider used by the guard.
692
     *
693
     * @param  \Illuminate\Contracts\Auth\UserProvider  $provider
694
     * @return void
695
     */
696
    public function setProvider(UserProvider $provider)
697
    {
698
        $this->provider = $provider;
699
    }
700

    
701
    /**
702
     * Return the currently cached user.
703
     *
704
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
705
     */
706
    public function getUser()
707
    {
708
        return $this->user;
709
    }
710

    
711
    /**
712
     * Set the current user.
713
     *
714
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
715
     * @return $this
716
     */
717
    public function setUser(AuthenticatableContract $user)
718
    {
719
        $this->user = $user;
720

    
721
        $this->loggedOut = false;
722

    
723
        return $this;
724
    }
725

    
726
    /**
727
     * Get the current request instance.
728
     *
729
     * @return \Symfony\Component\HttpFoundation\Request
730
     */
731
    public function getRequest()
732
    {
733
        return $this->request ?: Request::createFromGlobals();
734
    }
735

    
736
    /**
737
     * Set the current request instance.
738
     *
739
     * @param  \Symfony\Component\HttpFoundation\Request  $request
740
     * @return $this
741
     */
742
    public function setRequest(Request $request)
743
    {
744
        $this->request = $request;
745

    
746
        return $this;
747
    }
748

    
749
    /**
750
     * Get the last user we attempted to authenticate.
751
     *
752
     * @return \Illuminate\Contracts\Auth\Authenticatable
753
     */
754
    public function getLastAttempted()
755
    {
756
        return $this->lastAttempted;
757
    }
758

    
759
    /**
760
     * Get a unique identifier for the auth session value.
761
     *
762
     * @return string
763
     */
764
    public function getName()
765
    {
766
        return 'login_'.$this->name.'_'.sha1(static::class);
767
    }
768

    
769
    /**
770
     * Get the name of the cookie used to store the "recaller".
771
     *
772
     * @return string
773
     */
774
    public function getRecallerName()
775
    {
776
        return 'remember_'.$this->name.'_'.sha1(static::class);
777
    }
778

    
779
    /**
780
     * Determine if the user was authenticated via "remember me" cookie.
781
     *
782
     * @return bool
783
     */
784
    public function viaRemember()
785
    {
786
        return $this->viaRemember;
787
    }
788
}
(11-11/13)