fedi-feed-router/backend/app/Services/Auth/LemmyAuthService.php

42 lines
1.2 KiB
PHP
Raw Normal View History

2025-07-02 21:32:37 +02:00
<?php
namespace App\Services\Auth;
use App\Enums\PlatformEnum;
use App\Exceptions\PlatformAuthException;
2025-07-05 01:55:53 +02:00
use App\Models\PlatformAccount;
2025-07-02 21:32:37 +02:00
use App\Modules\Lemmy\Services\LemmyApiService;
use Illuminate\Support\Facades\Cache;
class LemmyAuthService
{
2025-07-05 01:55:53 +02:00
/**
* @throws PlatformAuthException
*/
2025-08-07 21:19:19 +02:00
public function getToken(PlatformAccount $account): string
2025-07-02 21:32:37 +02:00
{
2025-07-05 01:55:53 +02:00
$cacheKey = "lemmy_jwt_token_$account->id";
$cachedToken = Cache::get($cacheKey);
2025-07-02 21:32:37 +02:00
if ($cachedToken) {
return $cachedToken;
}
2025-07-05 01:55:53 +02:00
if (! $account->username || ! $account->password || ! $account->instance_url) {
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Missing credentials for account: ' . $account->username);
2025-07-02 21:32:37 +02:00
}
2025-07-05 01:55:53 +02:00
$api = new LemmyApiService($account->instance_url);
$token = $api->login($account->username, $account->password);
2025-07-02 21:32:37 +02:00
if (!$token) {
2025-07-05 01:55:53 +02:00
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed for account: ' . $account->username);
2025-07-02 21:32:37 +02:00
}
2025-07-03 21:34:39 +02:00
// Cache for 50 minutes (3000 seconds) to allow buffer before token expires
2025-07-05 01:55:53 +02:00
Cache::put($cacheKey, $token, 3000);
2025-07-02 21:32:37 +02:00
return $token;
}
2025-07-05 01:55:53 +02:00
}