-
-
Save pwFoo/46602cd9158e8b228cf28079de939c84 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