Add external subscription system
This commit is contained in:
70
app/Livewire/UserSubscription.php
Normal file
70
app/Livewire/UserSubscription.php
Normal file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
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 = '';
|
||||
|
||||
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 ?? '';
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.user-subscription');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user