74 lines
2.4 KiB
PHP
74 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Auth;
|
|
|
|
use App\Enums\PlatformEnum;
|
|
use App\Exceptions\PlatformAuthException;
|
|
use App\Models\PlatformAccount;
|
|
use App\Modules\Lemmy\Services\LemmyApiService;
|
|
use Exception;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
class LemmyAuthService
|
|
{
|
|
/**
|
|
* @throws PlatformAuthException
|
|
*/
|
|
public static function getToken(PlatformAccount $account): string
|
|
{
|
|
$cacheKey = "lemmy_jwt_token_$account->id";
|
|
$cachedToken = Cache::get($cacheKey);
|
|
|
|
if ($cachedToken) {
|
|
return $cachedToken;
|
|
}
|
|
|
|
if (! $account->username || ! $account->password || ! $account->instance_url) {
|
|
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Missing credentials for account: ' . $account->username);
|
|
}
|
|
|
|
$api = new LemmyApiService($account->instance_url);
|
|
$token = $api->login($account->username, $account->password);
|
|
|
|
if (!$token) {
|
|
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed for account: ' . $account->username);
|
|
}
|
|
|
|
// Cache for 50 minutes (3000 seconds) to allow buffer before token expires
|
|
Cache::put($cacheKey, $token, 3000);
|
|
|
|
return $token;
|
|
}
|
|
|
|
/**
|
|
* Authenticate with Lemmy API and return user data with JWT
|
|
* @throws PlatformAuthException
|
|
*/
|
|
public function authenticate(string $instanceUrl, string $username, string $password): array
|
|
{
|
|
try {
|
|
$api = new LemmyApiService($instanceUrl);
|
|
$token = $api->login($username, $password);
|
|
|
|
if (!$token) {
|
|
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed for user: ' . $username);
|
|
}
|
|
|
|
// Get user info with the token
|
|
// For now, we'll return a basic response structure
|
|
// In a real implementation, you might want to fetch user details
|
|
return [
|
|
'jwt' => $token,
|
|
'person_view' => [
|
|
'person' => [
|
|
'id' => 0, // Would need API call to get actual user info
|
|
'display_name' => null,
|
|
'bio' => null,
|
|
]
|
|
]
|
|
];
|
|
} catch (Exception $e) {
|
|
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Authentication failed: ' . $e->getMessage());
|
|
}
|
|
}
|
|
}
|