@@ -2,7 +2,9 @@
|
||||
require_once('UserDataSet.php');
|
||||
|
||||
/**
|
||||
* Authentication service for handling JWT-based authentication
|
||||
* Backend Authentication service for handling JWT authentication
|
||||
* https://jwt.io/introduction
|
||||
* This cost me blood, sweat and tears, mostly tears.
|
||||
*/
|
||||
class AuthService {
|
||||
private string $secretKey;
|
||||
@@ -14,7 +16,7 @@ class AuthService {
|
||||
* @throws Exception if OpenSSL extension is not loaded
|
||||
*/
|
||||
public function __construct() {
|
||||
// Load environment variables from .env file
|
||||
// Load environment variables from .env file (:D more configuration needs to be added to .env, but scope creep already huge)
|
||||
$envFile = __DIR__ . '/../.env';
|
||||
if (file_exists($envFile)) {
|
||||
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
@@ -37,14 +39,14 @@ class AuthService {
|
||||
$this->secretKey = getenv('JWT_SECRET_KEY') ?: 'your-256-bit-secret';
|
||||
$this->tokenExpiry = (int)(getenv('JWT_TOKEN_EXPIRY') ?: 3600);
|
||||
|
||||
// Verify OpenSSL extension is available
|
||||
// Verify OpenSSL extension is available. This should be on by default regardless, but just in case.
|
||||
if (!extension_loaded('openssl')) {
|
||||
throw new Exception('OpenSSL extension is required for JWT');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a JWT token for a user
|
||||
* Generates a JWT token
|
||||
* @param array $userData User information to include in token
|
||||
* @return string The generated JWT token
|
||||
*/
|
||||
@@ -52,6 +54,7 @@ class AuthService {
|
||||
$issuedAt = time();
|
||||
$expire = $issuedAt + $this->tokenExpiry;
|
||||
|
||||
// Create payload with user data
|
||||
$payload = [
|
||||
'iat' => $issuedAt,
|
||||
'exp' => $expire,
|
||||
@@ -101,7 +104,7 @@ class AuthService {
|
||||
$signature = hash_hmac('sha256', "$header.$payload", $this->secretKey, true);
|
||||
$signature = $this->base64UrlEncode($signature);
|
||||
|
||||
return "$header.$payload.$signature";
|
||||
return "$header.$payload.$signature"; //Wooooooo!!! JWT is a thing!
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user