Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
LemmyAuthService
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 1
 getToken
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3namespace App\Services\Auth;
4
5use App\Enums\PlatformEnum;
6use App\Exceptions\PlatformAuthException;
7use App\Models\PlatformAccount;
8use App\Modules\Lemmy\Services\LemmyApiService;
9use Illuminate\Support\Facades\Cache;
10
11class LemmyAuthService
12{
13    /**
14     * @throws PlatformAuthException
15     */
16    public static function getToken(PlatformAccount $account): string
17    {
18        $cacheKey = "lemmy_jwt_token_$account->id";
19        $cachedToken = Cache::get($cacheKey);
20
21        if ($cachedToken) {
22            return $cachedToken;
23        }
24
25        if (! $account->username || ! $account->password || ! $account->instance_url) {
26            throw new PlatformAuthException(PlatformEnum::LEMMY, 'Missing credentials for account: ' . $account->username);
27        }
28
29        $api = new LemmyApiService($account->instance_url);
30        $token = $api->login($account->username, $account->password);
31
32        if (!$token) {
33            throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed for account: ' . $account->username);
34        }
35
36        // Cache for 50 minutes (3000 seconds) to allow buffer before token expires
37        Cache::put($cacheKey, $token, 3000);
38
39        return $token;
40    }
41}