netgescon-day0/app/Models/User.php

207 lines
6.2 KiB
PHP
Executable File

<?php
namespace App\Models;
// Import necessari
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable; // Per la funzionalità di impersonificazione
use Illuminate\Notifications\Notifiable; // Per la gestione dei ruoli e permessi
use Illuminate\Support\Facades\Crypt;
use Lab404\Impersonate\Models\Impersonate;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail, FilamentUser
{
// Aggiungi il trait Impersonate
use HasApiTokens, HasFactory, Notifiable, Impersonate, HasRoles; // Aggiungi HasRoles qui
protected $fillable = [
'name',
'email',
'password',
'email_verified_at',
'expires_at',
'is_active',
'registration_status',
'requested_role',
'subscription_plan_id',
'approved_by_user_id',
'approved_at',
'rejected_at',
'rejection_reason',
'two_factor_secret',
'two_factor_recovery_codes',
'two_factor_confirmed_at',
'pbx_extension',
'pbx_popup_enabled',
'pbx_click_to_call_enabled',
];
protected $hidden = ['password', 'remember_token', 'two_factor_secret', 'two_factor_recovery_codes'];
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'expires_at' => 'datetime',
'is_active' => 'boolean',
'approved_at' => 'datetime',
'rejected_at' => 'datetime',
'two_factor_confirmed_at' => 'datetime',
'pbx_popup_enabled' => 'boolean',
'pbx_click_to_call_enabled' => 'boolean',
'password' => 'hashed',
];
}
public function hasTwoFactorEnabled(): bool
{
return ! empty($this->two_factor_secret) && $this->two_factor_confirmed_at !== null;
}
public function getTwoFactorSecretDecrypted(): ?string
{
if (! $this->two_factor_secret) {
return null;
}
try {
return Crypt::decryptString($this->two_factor_secret);
} catch (\Throwable) {
return null;
}
}
public function getTwoFactorRecoveryCodes(): array
{
if (! $this->two_factor_recovery_codes) {
return [];
}
try {
return json_decode(Crypt::decryptString($this->two_factor_recovery_codes), true, 512, JSON_THROW_ON_ERROR);
} catch (\Throwable) {
return [];
}
}
public function subscriptionPlan(): BelongsTo
{
return $this->belongsTo(SubscriptionPlan::class, 'subscription_plan_id');
}
public function approver(): BelongsTo
{
return $this->belongsTo(User::class, 'approved_by_user_id');
}
public function isPendingApproval(): bool
{
return $this->registration_status === 'pending';
}
/**
* Ritorna true se l'utente è scaduto.
*/
public function isExpired(): bool
{
return $this->expires_at !== null && now()->greaterThan($this->expires_at);
}
/**
* Get the amministratore record associated with the user.
*/
public function amministratore(): HasOne
{
return $this->hasOne(Amministratore::class, 'user_id');
}
public function soggetto(): HasOne
{
return $this->hasOne(Soggetto::class, 'email', 'email');
}
public function tickets(): HasMany
{
return $this->hasMany(Ticket::class, 'aperto_da_user_id');
}
/**
* Stabili assegnati al collaboratore tramite pivot
*/
public function stabiliAssegnati(): BelongsToMany
{
return $this->belongsToMany(Stabile::class, 'collaboratore_stabile', 'user_id', 'stabile_id')
->withPivot(['ruolo', 'permessi'])
->withTimestamps();
}
/**
* Regola per il pacchetto: definisce se l'utente ATTUALE
* ha il permesso di impersonare altri.
*/
public function canImpersonate(): bool
{
// Solo il Super-Admin può farlo.
return $this->hasRole('super-admin');
}
/**
* Regola per il pacchetto: definisce se questo specifico
* utente PUÒ ESSERE impersonato.
*/
public function canBeImpersonated(): bool
{
// Possono essere impersonati gli utenti operativi (amministratore/collaboratore/admin)
return $this->hasAnyRole(['admin', 'amministratore', 'collaboratore']);
}
public function canAccessPanel(Panel $panel): bool
{
if ($panel->getId() !== 'admin-filament') {
return false;
}
if ($this->isExpired()) {
return false;
}
if (array_key_exists('is_active', $this->attributes) && $this->is_active === false) {
return false;
}
if (array_key_exists('registration_status', $this->attributes) && $this->registration_status !== null && $this->registration_status !== 'approved') {
return false;
}
return $this->hasAnyRole([
'super-admin',
'admin',
'amministratore',
'collaboratore',
'fornitore',
'condomino',
'inquilino',
'proprietario',
]);
}
// public function roles()
// {
// return $this->belongsToMany(\App\Models\Role::class, 'role_user')->withTimestamps();
// // Relazione legacy rimossa: ora i ruoli sono gestiti solo tramite Spatie/Permission
// }
// public function hasRole($role, $stabileId = null)
// {
// return $this->roles()->where('name', $role)
// ->when($stabileId, fn($q) => $q->wherePivot('stabile_id', $stabileId))
// ->exists();
// }
}