Files
fewo-stommer/app/Models/User.php
T
LarsandCursor 8ebc1a3878 Assign the existing site to one landlord so stommer.info can run tenancy.
Seebad 0.3 stays in this release. With a single landlord every host still reaches the default website.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:00:11 +02:00

230 lines
6.5 KiB
PHP

<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\AdminMode;
use App\Enums\UserRole;
use App\Tenancy\TenantContext;
use Database\Factories\UserFactory;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthentication;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthenticationRecovery;
use Filament\Auth\MultiFactor\App\Contracts\HasAppAuthentication;
use Filament\Auth\MultiFactor\App\Contracts\HasAppAuthenticationRecovery;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
#[Fillable(['name', 'email', 'role', 'admin_mode', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable implements FilamentUser, HasAppAuthentication, HasAppAuthenticationRecovery
{
/** @use HasFactory<UserFactory> */
use HasFactory, InteractsWithAppAuthentication, InteractsWithAppAuthenticationRecovery, Notifiable;
protected static function booted(): void
{
static::saved(function (User $user): void {
$user->attachCurrentRole();
});
}
/**
* The operator panel is only for operators. The landlord admin needs a role there, or the operator flag.
* Password and two-factor belong to the account and are not a per-landlord setting.
*/
public function canAccessPanel(Panel $panel): bool
{
if ($panel->getId() === 'operator') {
return (bool) $this->is_operator;
}
return $this->currentRole() !== null || (bool) $this->is_operator;
}
/**
* The admin menu this user sees; without an explicit choice administrators get the expert mode.
*/
public function adminMode(): AdminMode
{
return $this->admin_mode ?? ($this->hasRole(UserRole::Admin) ? AdminMode::Expert : AdminMode::Simple);
}
public function hasRole(UserRole ...$roles): bool
{
return in_array($this->currentRole(), $roles, true);
}
/**
* Role inside the landlord that is current. The operator acts as administrator of whichever landlord is open.
* With exactly one landlord, the old account role still applies until a membership exists.
*/
public function currentRole(): ?UserRole
{
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null) {
if ($this->is_operator) {
return UserRole::Admin;
}
$role = $this->roleOn($tenantId);
if ($role !== null) {
return $role;
}
if ($this->role !== null && Tenant::query()->count() === 1) {
return $this->role;
}
return null;
}
if ($this->role !== null) {
return $this->role;
}
if ($this->is_operator) {
return UserRole::Admin;
}
$memberships = $this->tenants()->get();
if ($memberships->count() === 1) {
return $this->roleFromPivot($memberships->first()?->pivot?->role);
}
return null;
}
public function roleOn(int $tenantId): ?UserRole
{
$membership = $this->tenants()->where('tenants.id', $tenantId)->first();
return $this->roleFromPivot($membership?->pivot?->role);
}
/**
* Copy the account role onto the current landlord. Does nothing without a role or a landlord.
*/
public function attachCurrentRole(?Tenant $tenant = null): void
{
if ($this->role === null) {
return;
}
$tenant ??= app(TenantContext::class)->get();
if ($tenant === null) {
return;
}
$alreadyMember = $this->tenants()->where('tenants.id', $tenant->id)->exists();
if ($alreadyMember) {
if ($this->wasChanged('role')) {
$this->tenants()->updateExistingPivot($tenant->id, ['role' => $this->role->value]);
}
return;
}
$this->tenants()->attach($tenant->id, ['role' => $this->role->value]);
}
/**
* Password and two-factor stay on the account. A landlord admin may reset them only when the
* account belongs to no other landlord. Otherwise only the operator may.
*/
public function mayResetCredentials(?User $other): bool
{
if ($this->is_operator) {
return true;
}
if (! $this->hasRole(UserRole::Admin)) {
return false;
}
if ($other === null) {
return true;
}
return $other->tenants()->count() < 2;
}
/**
* Another landlord this account belongs to, when that landlord has its own domain.
*/
public function otherTenantAdminUrl(): ?string
{
$current = app(TenantContext::class)->id();
$other = $this->tenants()->where('tenants.id', '!=', $current)->first();
if ($other === null) {
return null;
}
$domain = $other->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
if (! is_string($domain) || $domain === '') {
return null;
}
return 'https://'.$domain.'/admin';
}
public function showsTenantSwitch(): bool
{
return $this->otherTenantAdminUrl() !== null;
}
public function revokeCurrentTenant(): void
{
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null) {
$this->tenants()->detach($tenantId);
}
}
/**
* @return BelongsToMany<Tenant, $this>
*/
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class)->withPivot('role')->withTimestamps();
}
private function roleFromPivot(mixed $role): ?UserRole
{
if ($role instanceof UserRole) {
return $role;
}
return is_string($role) ? UserRole::tryFrom($role) : null;
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'role' => UserRole::class,
'admin_mode' => AdminMode::class,
'is_operator' => 'boolean',
];
}
}