Created
March 14, 2017 17:41
-
-
Save mikemand/e66cf680a782a3e7b62ff5786e30671c to your computer and use it in GitHub Desktop.
LoginByApiToken middleware for AsgardCMS
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 Modules\Module\Http\Middleware; | |
use Cartalyst\Sentinel\Laravel\Facades\Sentinel; | |
use Illuminate\Http\Request; | |
use Illuminate\Http\Response; | |
use Modules\User\Entities\UserToken; | |
use Modules\User\Repositories\UserTokenRepository; | |
class LoginByApiToken | |
{ | |
/** | |
* @var UserTokenRepository | |
*/ | |
private $userTokenRepository; | |
/** | |
* @var UserToken | |
*/ | |
private $userToken; | |
public function __construct(UserTokenRepository $userTokenRepository) | |
{ | |
$this->userTokenRepository = $userTokenRepository; | |
} | |
public function handle(Request $request, \Closure $next) | |
{ | |
$authorizationHeader = $request->header('Authorization'); | |
if ($authorizationHeader === null) { | |
return new Response('Unauthorized', 401); | |
} | |
if ($this->isValidToken($authorizationHeader) === false) { | |
return new Response('Unauthorized', 401); | |
} | |
if ($this->userToken->user === null) { | |
return new Response('Unauthorized', 401); | |
} | |
$this->logUserIn($this->userToken); | |
return $next($request); | |
} | |
private function isValidToken($token) | |
{ | |
$found = $this->getUserFromToken($token); | |
if ($found === null) { | |
return false; | |
} | |
return true; | |
} | |
private function getUserFromToken($token) | |
{ | |
return $this->userToken = $this->userTokenRepository->findByAttributes(['access_token' => $this->parseToken($token)]); | |
} | |
private function parseToken($token) | |
{ | |
return str_replace('Bearer ', '', $token); | |
} | |
private function logUserIn(UserToken $userToken) | |
{ | |
$user = Sentinel::findById($userToken->user_id); | |
Sentinel::login($user); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment