Created
February 24, 2019 17:48
-
-
Save ryanscherler/903e765027402c58ab0fef0e7fe7f969 to your computer and use it in GitHub Desktop.
Token middleware invokable class for Slim PHP
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\Middleware; | |
use Psr\Container\ContainerInterface; | |
class TokenAuthentication | |
{ | |
private $container; | |
public function __construct(ContainerInterface $container) | |
{ | |
$this->container = $container; | |
} | |
/** | |
* Token middleware invokable class | |
* | |
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request | |
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response | |
* @param callable $next Next middleware | |
* | |
* @return \Psr\Http\Message\ResponseInterface | |
*/ | |
public function __invoke($request, $response, $next) | |
{ | |
if (!$request->hasHeader('Authorization')) { | |
return $response->withJson([ | |
'status' => 'error', | |
'message' => "Token not found.", | |
], 401); | |
} | |
$header = $request->getHeader('Authorization')[0]; | |
if (!preg_match('/Bearer\s+(.*)$/i', $header, $matches)) { | |
return $response->withJson([ | |
'status' => 'error', | |
'message' => "Invalid token format. Please ensure you prefix your token with `Bearer `.", | |
'token' => $token, | |
], 401); | |
} | |
$token = $matches[1]; | |
$users = $this->container->get('users'); | |
$user = $users->where('token', $token) | |
->first(); | |
if (!$user) { | |
return $response->withJson([ | |
'status' => 'error', | |
'message' => "Invalid token.", | |
'token' => $token, | |
], 401); | |
} | |
$newRequest = $request->withAttribute('user', $user); | |
$response = $next($newRequest, $response); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment