Skip to content

Commit

Permalink
Adds token abstraction
Browse files Browse the repository at this point in the history
  • Loading branch information
José San Martin committed Apr 23, 2024
1 parent c60665f commit d707fe7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Abstraction/TokenAbstraction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace SlashId\Php\Abstraction;

use SlashId\Php\Exception\MalformedTokenException;

class TokenAbstraction extends AbstractionBase
{
public function validateToken(string $token): bool
{
return $this->sdk->post('/token/validate', ['token' => $token])['valid'] ?? false;
}

public function getSubFromToken(string $token): string
{
if (!str_contains($token, '.')) {
throw new MalformedTokenException('The token is malformed.');
}

$tokenParts = explode('.', $token);

if (count($tokenParts) !== 3) {
throw new MalformedTokenException('The token is malformed.');
}

[, $userDataTokenPart] = $tokenParts;
$userData = json_decode(base64_decode($userDataTokenPart), true);
return $userData['sub'];
}
}
8 changes: 8 additions & 0 deletions src/Exception/MalformedTokenException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace SlashId\Php\Exception;

/**
* Exception thrown when an invalid token is informed.
*/
class MalformedTokenException extends \Exception {}

0 comments on commit d707fe7

Please sign in to comment.