Remove external subscription system

This commit is contained in:
2026-07-18 14:03:03 +02:00
parent bcd15d8569
commit a04d58c60f
12 changed files with 31 additions and 351 deletions
@@ -1,109 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Log;
class SyncSubscriptionKeys extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:sync-subscription-keys';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sync local users against active subscription keys';
/**
* Execute the console command.
*/
public function handle()
{
$endpoint = config('services.subscription_service_host');
if (!$endpoint) {
$this->error('Missing endpoint.');
return self::FAILURE;
}
$response = Http::asJson()
->acceptJson()
->timeout(20)
->retry(3, 1000)
->post($endpoint.'/api/membership/keys', [
'payload' => base64_encode(Crypt::encryptString('get-active-keys')),
]);
if (! $response->successful()) {
$this->error('Subscription API request failed: HTTP ' . $response->status());
return self::FAILURE;
}
try {
$decrypted = Crypt::decryptString(base64_decode($response->json('payload')));
$activeKeys = json_decode($decrypted, true, flags: JSON_THROW_ON_ERROR);
} catch (DecryptException $e) {
$this->error('Could not decrypt API response.');
return self::FAILURE;
} catch (\JsonException $e) {
$this->error('API returned invalid JSON.');
return self::FAILURE;
}
if (! is_array($activeKeys)) {
$this->error('API response payload was not an array.');
return self::FAILURE;
}
$activeKeys = collect($activeKeys)
->filter(fn ($key) => is_string($key) && $key !== '')
->values()
->all();
$this->markInactiveUsers($activeKeys);
$this->markActiveUsers($activeKeys);
return self::SUCCESS;
}
private function markInactiveUsers(array $activeKeys)
{
User::query()
->whereNotNull('subscription_key')
->whereNotIn('subscription_key', $activeKeys)
->chunk(100, function ($users) {
foreach($users as $user) {
if ($user->hasRole(UserRole::SUPPORTER)) {
Log::info("Removed Supporter Role from {$user->name}");
$user->removeRole(UserRole::SUPPORTER);
}
}
});
}
private function markActiveUsers(array $activeKeys)
{
User::query()
->whereNotNull('subscription_key')
->whereIn('subscription_key', $activeKeys)
->chunk(100, function ($users) {
foreach($users as $user) {
if (!$user->hasRole(UserRole::SUPPORTER)) {
Log::info("Added Supporter Role for {$user->name}");
$user->addRole(UserRole::SUPPORTER);
}
}
});
}
}
@@ -95,16 +95,6 @@ class ProfileController extends Controller
]);
}
/**
* Display the user's subscription page.
*/
public function subscription(Request $request): View
{
return view('profile.subscription', [
'user' => $request->user(),
]);
}
/**
* Update user settings.
*/
-75
View File
@@ -1,75 +0,0 @@
<?php
namespace App\Livewire;
use App\Enums\UserRole;
use App\Models\User;
use App\Services\SubscriptionService;
use Livewire\Component;
use Livewire\Attributes\Computed;
use Illuminate\Support\Facades\RateLimiter;
class UserSubscription extends Component
{
public $userId = 0;
public $subscriptionKey = '';
public $isActive = false;
protected $rules = [
'subscriptionKey' => 'required|string|size:48',
];
public function mount(User $user)
{
$this->userId = $user ? $user->id : auth()->user()->id;
$this->subscriptionKey = $user->subscription_key ?? '';
$this->isActive = $user->hasRole(UserRole::SUPPORTER) ?? false;
}
public function applyKey(SubscriptionService $subscriptionService)
{
$this->validate();
$rateLimitKey = "apply-subscription:{$this->userId}";
$rateLimitMinutes = 60 * 5; // 5 minutes
// Rate Limit to prevent users trying random keys
if (RateLimiter::tooManyAttempts($rateLimitKey, 1)) {
$seconds = RateLimiter::availableIn($rateLimitKey);
$this->addError('subscriptionKey', "Too many attempts. Try again in {$seconds} seconds.");
return;
}
RateLimiter::hit($rateLimitKey, $rateLimitMinutes);
// Check if token is already being used
$alreadyUsed = User::where('subscription_key', $this->subscriptionKey)
->whereNot('id', $this->userId)
->exists();
if ($alreadyUsed) {
$this->addError('subscriptionKey', 'Key already used!');
return;
}
$user = User::where('id', $this->userId)->firstOrFail();
// Verify token
$success = $subscriptionService->checkSubscriptionStatus($user, $this->subscriptionKey);
if (!$success) {
$this->addError('subscriptionKey', 'Invalid Key! If you believe this is a bug, please report this to the admin!');
return;
}
$user->subscription_key = $this->subscriptionKey;
$user->save();
$this->isActive = true;
}
public function render()
{
return view('livewire.user-subscription');
}
}
-2
View File
@@ -31,7 +31,6 @@ class User extends Authenticatable implements HasPasskeys
// Discord
'discord_id',
'discord_avatar',
'subscription_key',
];
/**
@@ -42,7 +41,6 @@ class User extends Authenticatable implements HasPasskeys
protected $hidden = [
'password',
'remember_token',
'subscription_key',
];
/**
-79
View File
@@ -1,79 +0,0 @@
<?php
namespace App\Services;
use App\Enums\UserRole;
use App\Models\User;
use Exception;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class SubscriptionService
{
private function generateEncryptedPayload(string $subscriptionKey): string
{
return base64_encode(Crypt::encryptString(json_encode([
'subscription_access_key' => $subscriptionKey,
'timestamp' => now()->timestamp,
'nonce' => Str::uuid()->toString(),
], JSON_THROW_ON_ERROR)));
}
/**
* Gets the subscription status from the subscription service.
*/
private function getSubscriptionStatus(string $subscriptionKey): array | null
{
try {
$payload = $this->generateEncryptedPayload($subscriptionKey);
$response = Http::post(config('services.subscription_service_host').'/api/membership/verify', [
'payload' => $payload,
]);
if (! $response->successful()) {
logger()->error('Subscription Service API error', [
'status' => $response->status(),
'body' => $response->body(),
]);
return null;
}
$encryptedResponse = $response->json('payload');
$json = json_decode(
Crypt::decryptString($encryptedResponse),
true,
flags: JSON_THROW_ON_ERROR
);
return $json;
} catch (Exception $e) {
logger()->error('getSubscriptionStatus Exception', [
'details' => $e,
]);
}
return null;
}
public function checkSubscriptionStatus(User $user, string $subscriptionKey): bool
{
$subscriptionStatus = $this->getSubscriptionStatus($subscriptionKey);
if (!$subscriptionStatus) {
return false;
}
if ($subscriptionStatus['valid'] === true &&
$subscriptionStatus['active'] === true) {
$user->addRole(UserRole::SUPPORTER);
return true;
}
$user->removeRole(UserRole::SUPPORTER);
return true;
}
}