-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathCreateNewUser.php
More file actions
81 lines (69 loc) · 2.38 KB
/
CreateNewUser.php
File metadata and controls
81 lines (69 loc) · 2.38 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
<?php
namespace App\Actions\Fortify;
use App\Models\Organization;
use App\Models\User;
use App\Services\DemoBackupService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules;
public function __construct(
private readonly DemoBackupService $demoBackupService
) {}
/**
* Validate and create a newly registered user.
*
* Only the first user can register via this route.
* All other users must be invited by an admin.
*
* @param array<string, string> $input
*/
public function create(array $input): User
{
// Only allow registration if no users exist (first admin)
if (User::count() > 0) {
abort(403, 'Registration is closed. Please contact an administrator for an invitation.');
}
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'password' => $this->passwordRules(),
])->validate();
$createDemoBackup = ! empty($input['create_demo_backup']);
// Ensure main org exists (migration creates it, but handle fresh install)
$mainOrg = Organization::firstOrCreate(
['is_main' => true],
['name' => 'Main']
);
// First user is always super_admin
$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => $input['password'],
'super_admin' => true,
'invitation_accepted_at' => now(),
]);
// Attach to main org as admin
$user->organizations()->attach($mainOrg->id, ['role' => User::ROLE_ADMIN]);
if ($createDemoBackup) {
try {
$this->demoBackupService->createDemoBackup();
} catch (\Throwable $e) {
// Log the error but don't fail registration
Log::warning('Failed to create demo backup during registration', [
'error' => $e->getMessage(),
]);
}
}
return $user;
}
}