-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathLicenseController.php
More file actions
97 lines (79 loc) · 2.89 KB
/
LicenseController.php
File metadata and controls
97 lines (79 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace App\Http\Controllers\Api;
use App\Enums\LicenseSource;
use App\Enums\Subscription;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\LicenseResource;
use App\Jobs\CreateAnystackLicenseJob;
use App\Jobs\UpdateAnystackLicenseExpiryJob;
use App\Models\License;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Enum;
class LicenseController extends Controller
{
public function index(Request $request)
{
$email = $request->query('email');
$user = User::where('email', $email)->firstOrFail();
if ($request->has('source')) {
$licenses = $user->licenses()->where('source', $request->query('source'))->get();
}
return LicenseResource::collection($licenses ?? $user->licenses);
}
public function store(Request $request)
{
$validated = $request->validate([
'email' => 'required|email',
'name' => 'required|string|max:255',
'subscription' => ['required', new Enum(Subscription::class)],
]);
// Find or create user
$user = User::firstOrCreate(
['email' => $validated['email']],
[
'name' => $validated['name'],
'password' => Hash::make(Str::random(32)), // Random password
]
);
// Create the license via job
$subscription = Subscription::from($validated['subscription']);
CreateAnystackLicenseJob::dispatchSync(
user: $user,
subscription: $subscription,
subscriptionItemId: null, // No subscription item for API-created licenses
firstName: null, // Set to null as requested
lastName: null, // Set to null as requested
source: LicenseSource::Bifrost
);
// Since we're using dispatchSync, the job has completed by this point
// Find the created license
$license = License::where('user_id', $user->id)
->with('user')
->where('policy_name', $subscription->value)
->where('source', LicenseSource::Bifrost)
->latest()
->firstOrFail();
return new LicenseResource($license);
}
public function show(string $key)
{
$license = License::where('key', $key)
->with('user')
->firstOrFail();
return new LicenseResource($license);
}
public function renew(string $key): LicenseResource
{
$license = License::where('key', $key)
->with('user')
->firstOrFail();
// Update Anystack first, then update database with new expiry date
UpdateAnystackLicenseExpiryJob::dispatchSync($license);
// Refresh to get the updated expiry date
$license->refresh();
return new LicenseResource($license);
}
}