-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathCompanyController.php
More file actions
518 lines (420 loc) · 17.8 KB
/
Copy pathCompanyController.php
File metadata and controls
518 lines (420 loc) · 17.8 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
<?php
namespace Fleetbase\Http\Controllers\Internal\v1;
use Fleetbase\Exports\CompanyExport;
use Fleetbase\Http\Controllers\FleetbaseController;
use Fleetbase\Http\Requests\AdminRequest;
use Fleetbase\Http\Requests\ExportRequest;
use Fleetbase\Http\Resources\Organization;
use Fleetbase\Http\Resources\User as UserResource;
use Fleetbase\Models\Company;
use Fleetbase\Models\CompanyUser;
use Fleetbase\Models\ExtensionInstall;
use Fleetbase\Models\Invite;
use Fleetbase\Models\User;
use Fleetbase\Support\Auth;
use Fleetbase\Support\TwoFactorAuth;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
class CompanyController extends FleetbaseController
{
/**
* The resource to query.
*
* @var string
*/
public $resource = 'company';
/**
* Find company by public_id or invitation code.
*
* @return \Illuminate\Http\Response
*/
public function findCompany(string $id)
{
$id = trim($id);
$isPublicId = Str::startsWith($id, ['company_']);
if ($isPublicId) {
$company = Company::where('public_id', $id)->first();
} else {
$invite = Invite::where(['uri' => $id, 'reason' => 'join_company'])->with(['subject'])->first();
if ($invite) {
$company = $invite->subject;
}
}
return new Organization($company);
}
/**
* Get the current organization's two factor authentication settings.
*
* @return \Illuminate\Http\Response
*/
public function getTwoFactorSettings()
{
$company = Auth::getCompany();
if (!$company) {
return response()->error('No company session found', 401);
}
$twoFaSettings = TwoFactorAuth::getTwoFaSettingsForCompany($company);
return response()->json($twoFaSettings->value);
}
/**
* Save the two factor authentication settings for the current company.
*
* @param Request $request the HTTP request
*
* @return \Illuminate\Http\Response
*/
public function saveTwoFactorSettings(Request $request)
{
$twoFaSettings = $request->array('twoFaSettings');
$company = Auth::getCompany();
if (!$company) {
return response()->error('No company session found', 401);
}
if (isset($twoFaSettings['enabled']) && $twoFaSettings['enabled'] === false) {
$twoFaSettings['enforced'] = false;
}
TwoFactorAuth::saveTwoFaSettingsForCompany($company, $twoFaSettings);
return response()->json(['message' => 'Two-Factor Authentication saved successfully']);
}
/**
* Get all users for a company.
*
* @param string $id The company id
*
* @return \Illuminate\Http\Response
*/
public function users(string $id, Request $request)
{
$searchQuery = $request->searchQuery();
$limit = $request->input(['limit', 'nestedLimit'], 20);
$paginate = $request->boolean('paginate');
$exclude = $request->array('exclude');
// Start user query
$usersQuery = CompanyUser::whereHas('company',
function ($query) use ($id) {
$query->where('public_id', $id);
$query->orWhere('uuid', $id);
}
)
->whereHas('user')
->whereNotIn('user_uuid', $exclude)
->with(['user']);
// Search query
if ($searchQuery) {
$usersQuery->whereHas('user', function ($query) use ($searchQuery) {
$query->search($searchQuery);
});
}
// Sort query
$usersQuery->applySortFromRequest($request);
// paginate results
if ($paginate) {
$users = $usersQuery->fastPaginate($limit);
// fix results
$transformedItems = $users->getCollection()->map(function ($companyUser) {
return $companyUser->user;
});
// replace in pagination
$users->setCollection($transformedItems);
return response()->json([
'users' => UserResource::collection($users->getCollection()),
'meta' => [
'current_page' => $users->currentPage(),
'from' => $users->firstItem(),
'last_page' => $users->lastPage(),
'path' => $users->path(),
'per_page' => $users->perPage(),
'to' => $users->lastItem(),
'total' => $users->total(),
],
]);
}
// get users
$users = $usersQuery->get();
// fix results
$users = $users->map(function ($companyUser) {
$companyUser->loadMissing('user');
return $companyUser->user;
});
return UserResource::collection($users);
}
public function extensions(string $id, AdminRequest $request): JsonResponse
{
$company = $this->resolveAdminCompany($id);
if (!$company) {
return response()->json(['error' => 'Organization not found.'], 404);
}
$extensions = ExtensionInstall::where('company_uuid', $company->uuid)
->with('extension')
->latest('created_at')
->get()
->filter(fn ($install) => $install->extension !== null)
->map(function ($install) {
$extension = $install->extension;
return [
'id' => $install->uuid,
'uuid' => $install->uuid,
'extension_id' => $extension->extension_id,
'name' => $extension->display_name ?: $extension->name,
'description' => $extension->description,
'icon' => $extension->fa_icon ?: 'puzzle-piece',
'slug' => $extension->slug,
'key' => $extension->key,
'version' => $extension->version,
'status' => $extension->status ?: 'installed',
'installed_at' => $install->created_at,
];
})
->values();
return response()->json(['extensions' => $extensions]);
}
public function setAdminStatus(string $id, AdminRequest $request): JsonResponse
{
$company = $this->resolveAdminCompany($id);
$status = $request->input('status');
if (!$company) {
return response()->json(['error' => 'Organization not found.'], 404);
}
if (!in_array($status, ['active', 'inactive', 'suspended'], true)) {
return response()->json(['error' => 'Invalid organization status.'], 422);
}
$oldStatus = $company->status;
$company->status = $status === 'active' ? null : $status;
$company->save();
$this->logAdminCompanyActivity($request, $company, 'Organization status changed', [
'old' => ['status' => $oldStatus],
'attributes' => ['status' => $company->status ?: 'active'],
], 'updated');
return response()->json(['company' => new Organization($company->refresh())]);
}
public function setAdminOnboarding(string $id, AdminRequest $request): JsonResponse
{
$company = $this->resolveAdminCompany($id);
if (!$company) {
return response()->json(['error' => 'Organization not found.'], 404);
}
$completed = $request->boolean('completed');
$oldValue = $company->onboarding_completed_at;
$company->onboarding_completed_at = $completed ? now() : null;
$company->onboarding_completed_by_uuid = $completed ? $request->user()->uuid : null;
$company->save();
$this->logAdminCompanyActivity($request, $company, $completed ? 'Organization onboarding marked complete' : 'Organization onboarding marked incomplete', [
'old' => ['onboarding_completed_at' => $oldValue],
'attributes' => ['onboarding_completed_at' => $company->onboarding_completed_at],
], 'updated');
return response()->json(['company' => new Organization($company->refresh())]);
}
public function transferOwnershipAdmin(string $id, AdminRequest $request): JsonResponse
{
$company = $this->resolveAdminCompany($id);
$newOwnerId = $request->input('newOwner');
if (!$company) {
return response()->json(['error' => 'Organization not found.'], 404);
}
$newOwner = $company->getCompanyUser($newOwnerId);
if (!$newOwner) {
return response()->json(['error' => 'The new owner is not a member of this organization.'], 422);
}
$oldOwnerUuid = $company->owner_uuid;
$company->assignOwner($newOwner);
$this->logAdminCompanyActivity($request, $company, 'Organization ownership transferred', [
'old' => ['owner_uuid' => $oldOwnerUuid],
'attributes' => ['owner_uuid' => $newOwner->uuid],
], 'updated');
return response()->json([
'status' => 'ok',
'newOwner' => new UserResource($newOwner),
'company' => new Organization($company->refresh()),
]);
}
public function activateAdminUser(string $id, string $userId, AdminRequest $request): JsonResponse
{
return $this->setAdminCompanyUserStatus($id, $userId, $request, 'active');
}
public function deactivateAdminUser(string $id, string $userId, AdminRequest $request): JsonResponse
{
return $this->setAdminCompanyUserStatus($id, $userId, $request, 'inactive');
}
public function verifyAdminUser(string $id, string $userId, AdminRequest $request): JsonResponse
{
[$company, $user, $companyUser, $error] = $this->resolveAdminCompanyUser($id, $userId);
if ($error) {
return $error;
}
$user->manualVerify();
$this->logAdminCompanyActivity($request, $company, 'Organization user verified', [
'attributes' => ['user_uuid' => $user->uuid, 'email_verified_at' => $user->email_verified_at],
], 'updated', $user);
return response()->json([
'message' => 'User verified',
'user' => new UserResource($user->refresh()),
]);
}
public function removeAdminUser(string $id, string $userId, AdminRequest $request): JsonResponse
{
[$company, $user, $companyUser, $error] = $this->resolveAdminCompanyUser($id, $userId);
if ($error) {
return $error;
}
if ($company->owner_uuid === $user->uuid) {
return response()->json(['error' => 'Transfer ownership before removing the organization owner.'], 422);
}
$companyUser->delete();
$nextCompany = $user->companies()->where('companies.uuid', '!=', $company->uuid)->first();
if ($nextCompany && $user->company_uuid === $company->uuid) {
$user->update(['company_uuid' => $nextCompany->uuid]);
}
event(new UserRemovedFromCompany($user, $company));
$this->logAdminCompanyActivity($request, $company, 'Organization user removed', [
'attributes' => ['user_uuid' => $user->uuid, 'email' => $user->email],
], 'deleted', $user);
return response()->json(['message' => 'User removed']);
}
/**
* Export the users to excel or csv.
*
* @return \Illuminate\Http\Response
*/
public function export(ExportRequest $request)
{
$format = $request->input('format', 'xlsx');
$selections = $request->array('selections');
$fileName = trim(Str::slug('company-' . date('Y-m-d-H:i')) . '.' . $format);
return Excel::download(new CompanyExport($selections), $fileName);
}
private function setAdminCompanyUserStatus(string $id, string $userId, AdminRequest $request, string $status): JsonResponse
{
[$company, $user, $companyUser, $error] = $this->resolveAdminCompanyUser($id, $userId);
if ($error) {
return $error;
}
if ($status === 'inactive' && $company->owner_uuid === $user->uuid) {
return response()->json(['error' => 'Transfer ownership before deactivating the organization owner.'], 422);
}
$oldStatus = $companyUser->status;
$companyUser->status = $status;
$companyUser->save();
if ($status === 'active') {
$user->activate();
}
$this->logAdminCompanyActivity($request, $company, $status === 'active' ? 'Organization user activated' : 'Organization user deactivated', [
'old' => ['status' => $oldStatus],
'attributes' => ['status' => $status, 'user_uuid' => $user->uuid],
], 'updated', $user);
return response()->json([
'message' => $status === 'active' ? 'User activated' : 'User deactivated',
'status' => $status,
'user' => new UserResource($user->refresh()),
]);
}
private function resolveAdminCompany(string $id): ?Company
{
return Company::where('uuid', $id)->orWhere('public_id', $id)->first();
}
private function resolveAdminCompanyUser(string $companyId, string $userId): array
{
$company = $this->resolveAdminCompany($companyId);
if (!$company) {
return [null, null, null, response()->json(['error' => 'Organization not found.'], 404)];
}
$user = User::where('uuid', $userId)->orWhere('public_id', $userId)->first();
if (!$user) {
return [$company, null, null, response()->json(['error' => 'User not found.'], 404)];
}
$companyUser = CompanyUser::where(['company_uuid' => $company->uuid, 'user_uuid' => $user->uuid])->first();
if (!$companyUser) {
return [$company, $user, null, response()->json(['error' => 'User is not a member of this organization.'], 404)];
}
return [$company, $user, $companyUser, null];
}
private function logAdminCompanyActivity(AdminRequest $request, Company $company, string $description, array $properties = [], string $event = 'updated', ?User $subject = null): void
{
$activity = activity('admin')
->causedBy($request->user())
->performedOn($subject ?? $company)
->withProperties($properties)
->event($event)
->log($description);
$activity->company_id = $company->uuid;
$activity->save();
}
/**
* Transfer ownership of company to another member, and make them the Administrator.
*
* @return \Illuminate\Http\Response
*/
public function transferOwnership(Request $request)
{
$companyId = $request->input('company');
$newOwnerId = $request->input('newOwner');
$leave = $request->boolean('leave');
// Get and validate organization
$company = Company::where('uuid', $companyId)->first();
if (!$company) {
return response()->error('No organization found to transfer ownership for.');
}
// Get and validate the new owner
$newOwner = $company->getCompanyUser($newOwnerId);
if (!$newOwner) {
return response()->error('The new owner provided could not be found for transfer of ownership.');
}
// Change the company owner
$company->assignOwner($newOwner);
// If the current user has opted to leave, remove them from the organization
if ($leave) {
$currentUser = $request->user();
if ($currentUser) {
$currentCompanyUser = $company->getCompanyUserPivot($currentUser);
if ($currentCompanyUser) {
$currentCompanyUser->delete();
}
// Switch organization
$nextOrganization = $currentUser->companies()->where('companies.uuid', '!=', $company->uuid)->first();
if ($nextOrganization) {
$currentUser->setCompany($nextOrganization);
}
}
}
return response()->json([
'status' => 'ok',
'newOwner' => $newOwner,
'currentUserLeft' => $leave,
]);
}
/**
* Remove the current user, or user selected via request param from an organization.
*
* @return \Illuminate\Http\Response
*/
public function leaveOrganization(Request $request)
{
$companyId = $request->input('company');
$currentUserId = $request->input('user');
$currentUser = Str::isUuid($currentUserId) ? User::where('uuid', $currentUserId)->first() : Auth::getUserFromSession($request);
// If not current user - error
if (!$currentUser) {
return response()->error('Unable to leave organization.');
}
// Get and validate organization
$company = Company::where('uuid', $companyId)->first();
if (!$company) {
return response()->error('No organization found for user to leave.');
}
$currentCompanyUser = $company->getCompanyUserPivot($currentUser);
if (!$currentCompanyUser) {
return response()->error('User selected to leave organization is not a member of this organization.');
}
// Remove user from organization
$currentCompanyUser->delete();
// Switch organization
$nextOrganization = $currentUser->companies()->where('companies.uuid', '!=', $company->uuid)->first();
if ($nextOrganization) {
$currentUser->setCompany($nextOrganization);
}
return response()->json([
'status' => 'ok',
]);
}
}