Last active
March 31, 2020 19:09
-
-
Save apiraino/aa2a2302afa54b3e1c22b990acddc8cf to your computer and use it in GitHub Desktop.
Simple static token authentication with Directus API
This file contains 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 | |
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; | |
} | |
} | |
?> |
This file contains 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 | |
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