From 238b000f02d9fe0db87a998c776bb3070d735731 Mon Sep 17 00:00:00 2001 From: Joseph Silber Date: Mon, 23 May 2016 10:36:18 -0400 Subject: [PATCH] [5.2] Add authenticate method to the guards (#13651) * Make setUser fluent * Create AuthenticationException * Add authenticate method to the guards * Convert an AuthenticationException into an unauthenticated response --- AuthenticationException.php | 37 +++++++++++++++++++++++++++++++++++++ GuardHelpers.php | 20 +++++++++++++++++++- SessionGuard.php | 4 +++- 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 AuthenticationException.php diff --git a/AuthenticationException.php b/AuthenticationException.php new file mode 100644 index 000000000..142afd1c8 --- /dev/null +++ b/AuthenticationException.php @@ -0,0 +1,37 @@ +guard = $guard; + + parent::__construct('Unauthenticated.'); + } + + /** + * Get the guard instance. + * + * @return \Illuminate\Contracts\Auth\Guard|null + */ + public function guard() + { + return $this->guard; + } +} diff --git a/GuardHelpers.php b/GuardHelpers.php index 1785904f3..95fee3ae7 100644 --- a/GuardHelpers.php +++ b/GuardHelpers.php @@ -23,6 +23,22 @@ trait GuardHelpers */ protected $provider; + /** + * Determine if the current user is authenticated. + * + * @return \Illuminate\Contracts\Auth\Authenticatable + * + * @throws \Illuminate\Auth\AuthenticationException + */ + public function authenticate() + { + if (! is_null($user = $this->user())) { + return $user; + } + + throw new AuthenticationException($this); + } + /** * Determine if the current user is authenticated. * @@ -59,10 +75,12 @@ public function id() * Set the current user. * * @param \Illuminate\Contracts\Auth\Authenticatable $user - * @return void + * @return $this */ public function setUser(AuthenticatableContract $user) { $this->user = $user; + + return $this; } } diff --git a/SessionGuard.php b/SessionGuard.php index 3f522239b..a744962e7 100644 --- a/SessionGuard.php +++ b/SessionGuard.php @@ -691,13 +691,15 @@ public function getUser() * Set the current user. * * @param \Illuminate\Contracts\Auth\Authenticatable $user - * @return void + * @return $this */ public function setUser(AuthenticatableContract $user) { $this->user = $user; $this->loggedOut = false; + + return $this; } /**