-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
98 additions
and
2 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
<?php | ||
|
||
namespace Own3d\Socket\Support; | ||
|
||
use Firebase\JWT\JWT; | ||
|
||
/** | ||
* Helper class to generate tokens for the socket server. | ||
*/ | ||
class SocketToken | ||
{ | ||
const ALGORITHM = 'HS256'; | ||
|
||
/** | ||
* Generates a pre-signed token for the socket server to join a room. | ||
* | ||
* This will generate a token that can be used to authenticate with the socket server to join a specific room. | ||
*/ | ||
public static function auth(string $room): string | ||
{ | ||
return self::encode(self::payload('auth', [ | ||
'type' => 'auth', | ||
'room' => $room, | ||
], 60 * 15)); | ||
} | ||
|
||
/** | ||
* Generate a pre-signed token for the socket server to emit a message. | ||
*/ | ||
public static function emit(string $room, string $event, array $data): string | ||
{ | ||
return self::encode(self::payload('emit', [ | ||
'room' => $room, | ||
'event' => $event, | ||
'data' => $data, | ||
], 60 * 15)); | ||
} | ||
|
||
/** | ||
* Helper to generate a JWT token. | ||
*/ | ||
public static function encode(array $payload): string | ||
{ | ||
return JWT::encode($payload, config('services.own3d-socket.secret'), self::ALGORITHM); | ||
} | ||
|
||
/** | ||
* Helper to decode a JWT token. | ||
*/ | ||
private static function payload(string $type, array $extra, float $ttl): array | ||
{ | ||
return array_merge([ | ||
'type' => $type, | ||
'iat' => time(), | ||
'exp' => time() + $ttl, | ||
], $extra); | ||
} | ||
} |