Skip to content

Instantly share code, notes, and snippets.

@ssi-anik
Last active October 4, 2018 09:01
Show Gist options
  • Save ssi-anik/7aae737c37e8c2be316253fe1b1d7f71 to your computer and use it in GitHub Desktop.
Save ssi-anik/7aae737c37e8c2be316253fe1b1d7f71 to your computer and use it in GitHub Desktop.
<?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