55 lines
1.4 KiB
PHP
55 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Arr;
|
|
|
|
class TenantAuth
|
|
{
|
|
/**
|
|
* Resolve the tenant admin user associated with the current request.
|
|
*
|
|
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
|
|
*/
|
|
public static function resolveAdminUser(Request $request): User
|
|
{
|
|
$decoded = (array) $request->attributes->get('decoded_token', []);
|
|
$tenantId = $request->attributes->get('tenant_id')
|
|
?? $request->input('tenant_id')
|
|
?? Arr::get($decoded, 'tenant_id');
|
|
|
|
if (! $tenantId) {
|
|
throw (new ModelNotFoundException)->setModel(User::class);
|
|
}
|
|
|
|
$userId = Arr::get($decoded, 'user_id');
|
|
|
|
if ($userId) {
|
|
$user = User::query()
|
|
->whereKey($userId)
|
|
->where('tenant_id', $tenantId)
|
|
->first();
|
|
|
|
if ($user) {
|
|
return $user;
|
|
}
|
|
}
|
|
|
|
$user = User::query()
|
|
->where('tenant_id', $tenantId)
|
|
->whereIn('role', ['tenant_admin', 'admin'])
|
|
->orderByDesc('email_verified_at')
|
|
->orderBy('id')
|
|
->first();
|
|
|
|
if (! $user) {
|
|
throw (new ModelNotFoundException)->setModel(User::class);
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
}
|