Last active
October 4, 2018 09:01
-
-
Save ssi-anik/7aae737c37e8c2be316253fe1b1d7f71 to your computer and use it in GitHub Desktop.
snippet 2 from https://github.com/ssi-anik/laravel-custom-auth for medium article - https://medium.com/@sirajul.anik/laravel-api-authenticate-user-with-custom-driver-different-table-using-auth-middleware-fa2cabec2d61
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Extensions; | |
use Illuminate\Auth\GuardHelpers; | |
use Illuminate\Contracts\Auth\Guard; | |
use Illuminate\Contracts\Auth\UserProvider; | |
use Illuminate\Http\Request; | |
class AccessTokenGuard implements Guard | |
{ | |
use GuardHelpers; | |
private $inputKey = ''; | |
private $storageKey = ''; | |
private $request; | |
public function __construct (UserProvider $provider, Request $request, $configuration) { | |
$this->provider = $provider; | |
$this->request = $request; | |
// key to check in request | |
$this->inputKey = isset($configuration['input_key']) ? $configuration['input_key'] : 'access_token'; | |
// key to check in database | |
$this->storageKey = isset($configuration['storage_key']) ? $configuration['storage_key'] : 'access_token'; | |
} | |
public function user () { | |
if (!is_null($this->user)) { | |
return $this->user; | |
} | |
$user = null; | |
// retrieve via token | |
$token = $this->getTokenForRequest(); | |
if (!empty($token)) { | |
// the token was found, how you want to pass? | |
$user = $this->provider->retrieveByToken($this->storageKey, $token); | |
} | |
return $this->user = $user; | |
} | |
/** | |
* Get the token for the current request. | |
* @return string | |
*/ | |
public function getTokenForRequest () { | |
$token = $this->request->query($this->inputKey); | |
if (empty($token)) { | |
$token = $this->request->input($this->inputKey); | |
} | |
if (empty($token)) { | |
$token = $this->request->bearerToken(); | |
} | |
return $token; | |
} | |
/** | |
* Validate a user's credentials. | |
* | |
* @param array $credentials | |
* | |
* @return bool | |
*/ | |
public function validate (array $credentials = []) { | |
if (empty($credentials[$this->inputKey])) { | |
return false; | |
} | |
$credentials = [ $this->storageKey => $credentials[$this->inputKey] ]; | |
if ($this->provider->retrieveByCredentials($credentials)) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment