Skip to content

Instantly share code, notes, and snippets.

@pwFoo
Forked from apiraino/AuthService.php
Created March 31, 2020 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwFoo/46602cd9158e8b228cf28079de939c84 to your computer and use it in GitHub Desktop.
Save pwFoo/46602cd9158e8b228cf28079de939c84 to your computer and use it in GitHub Desktop.
Simple static token authentication with Directus API
<?php
declare(strict_types=1);
use Directus\Services\AuthService as DirectusAuthService;
use Directus\Authentication\Exception\UserNotFoundException;
class AuthService
{
private function getToken($req)
{
$auth_header = $req->getHeader('Authorization');
if (!$auth_header)
return '';
// Array
// (
// [0] => Bearer SECRET_TOKEN_ADMIN
// )
$bearer = $auth_header[0];
if (!$bearer)
return '';
// "Bearer abcdefgh"
list($_, $token) = explode(' ', $bearer);
if (!$token)
return '';
return trim($token);
}
public function authToken($request) : bool
{
$token = $this->getToken($request);
if (!$token)
return false;
$container = \Directus\Application\Application::getInstance()->getContainer();
$authService = new DirectusAuthService($container);
try {
$user = $authService->authenticateWithToken($token);
} catch (UserNotFoundException $e) {
return false;
}
if (!$user->role)
return false;
return true;
}
}
?>
<?php
declare(strict_types=1);
use Directus\Application\Http\Request;
use Directus\Application\Http\Response;
require_once __DIR__ . "/AuthService.php";
class ExampleCustomEndpoint extends AuthService
{
public function __invoke(Request $request, Response $response)
{
$auth_result = $this->authToken($request);
if (!$auth_result)
{
$response = $response->withStatus(403);
return $response->withJson("Schoooo, go away");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment