Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 6m10s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Failing after 6m3s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 7m33s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 7m25s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m28s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m27s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m26s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m27s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 44s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m12s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
282 lines
9.4 KiB
PHP
282 lines
9.4 KiB
PHP
<?php
|
||
|
||
namespace App\Models;
|
||
|
||
use App\Push\AppDevice;
|
||
use App\Push\PushSubscription;
|
||
use App\Support\Abilities;
|
||
use App\Support\Audit;
|
||
use App\Support\Avatars;
|
||
use App\Support\Covers;
|
||
use App\Support\Permissions\Permissions;
|
||
use App\Support\Permissions\PermissionSet;
|
||
use App\Support\ProfileFields;
|
||
use App\Support\Settings;
|
||
use Database\Factories\UserFactory;
|
||
use Filament\Models\Contracts\FilamentUser;
|
||
use Filament\Models\Contracts\HasAvatar;
|
||
use Filament\Panel;
|
||
use Illuminate\Auth\Notifications\ResetPassword;
|
||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||
use Illuminate\Database\Eloquent\Builder;
|
||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||
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\Foundation\Auth\User as Authenticatable;
|
||
use Illuminate\Notifications\Notifiable;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Schema;
|
||
use Illuminate\Support\Str;
|
||
use Laravel\Sanctum\HasApiTokens;
|
||
|
||
#[Fillable([
|
||
'name', 'first_name', 'last_name', 'email', 'password',
|
||
'job_title', 'department', 'location', 'phone', 'mobile', 'about', 'custom_fields', 'manager_id',
|
||
'is_active', 'theme',
|
||
])]
|
||
#[Hidden(['password', 'remember_token'])]
|
||
class User extends Authenticatable implements FilamentUser, HasAvatar
|
||
{
|
||
/** @use HasFactory<UserFactory> */
|
||
use HasApiTokens, HasFactory, Notifiable;
|
||
|
||
public const THEMES = ['system', 'light', 'dark'];
|
||
|
||
protected static function booted(): void
|
||
{
|
||
// Protokoll: Konten anlegen, ändern (ohne Werte von Passwörtern), löschen
|
||
static::created(fn (User $user) => Audit::log('user.created', ['user' => $user->id, 'email' => $user->email]));
|
||
static::deleted(fn (User $user) => Audit::log('user.deleted', ['user' => $user->id, 'email' => $user->email]));
|
||
static::updated(function (User $user) {
|
||
$changed = array_values(array_diff(array_keys($user->getChanges()), ['updated_at', 'remember_token', 'last_login_at', 'avatar_path', 'cover_path']));
|
||
|
||
if ($changed !== []) {
|
||
Audit::log('user.updated', ['user' => $user->id, 'fields' => $changed, 'is_active' => $user->wasChanged('is_active') ? $user->is_active : null]);
|
||
}
|
||
});
|
||
|
||
// Deaktiviert: alle Zugänge sofort beenden (Sitzungen, „Angemeldet bleiben“, API, Push)
|
||
static::updated(function (User $user) {
|
||
if ($user->wasChanged('is_active') && ! $user->is_active) {
|
||
$user->revokeAccess();
|
||
}
|
||
});
|
||
|
||
// Der Anzeigename folgt Vor- und Nachname, solange beide gepflegt sind.
|
||
static::saving(function (User $user): void {
|
||
$fullName = trim($user->first_name.' '.$user->last_name);
|
||
|
||
if ($fullName !== '') {
|
||
$user->name = $fullName;
|
||
}
|
||
});
|
||
}
|
||
|
||
protected function casts(): array
|
||
{
|
||
return [
|
||
'email_verified_at' => 'datetime',
|
||
'last_login_at' => 'datetime',
|
||
'custom_fields' => 'array',
|
||
'password' => 'hashed',
|
||
'is_active' => 'boolean',
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Admin-Backend: für alle mit irgendeinem Recht (z. B. Redaktion einer
|
||
* Kategorie). Was sie dort sehen, regeln die Policies der einzelnen Seiten.
|
||
*/
|
||
public function canAccessPanel(Panel $panel): bool
|
||
{
|
||
return $this->canAccessAdmin();
|
||
}
|
||
|
||
/**
|
||
* Backend (/admin) nur für Rechte, die dort gepflegt werden. Wer nur Redaktionsrechte
|
||
* hat (Beiträge schreiben, Seiten bearbeiten …), arbeitet vollständig im Portal.
|
||
*/
|
||
public function canAccessAdmin(): bool
|
||
{
|
||
if (! $this->is_active) {
|
||
return false;
|
||
}
|
||
|
||
$permissions = $this->permissions();
|
||
$abilities = app(Abilities::class);
|
||
|
||
return $permissions->isSuperuser()
|
||
|| collect(array_keys($permissions->global))->merge(array_keys($permissions->objects))
|
||
->contains(fn (string $ability) => $abilities->needsBackend($ability));
|
||
}
|
||
|
||
public function permissions(): PermissionSet
|
||
{
|
||
return app(Permissions::class)->for($this);
|
||
}
|
||
|
||
/**
|
||
* @return HasMany<UserIdentity, $this>
|
||
*/
|
||
public function identities(): HasMany
|
||
{
|
||
return $this->hasMany(UserIdentity::class);
|
||
}
|
||
|
||
/**
|
||
* @return BelongsTo<User, $this>
|
||
*/
|
||
public function manager(): BelongsTo
|
||
{
|
||
return $this->belongsTo(User::class, 'manager_id');
|
||
}
|
||
|
||
/**
|
||
* @return HasMany<User, $this>
|
||
*/
|
||
public function reports(): HasMany
|
||
{
|
||
return $this->hasMany(User::class, 'manager_id');
|
||
}
|
||
|
||
/**
|
||
* Profilfelder, die ein Identity Provider pflegt – im Portal nur lesbar.
|
||
*
|
||
* @return list<string>
|
||
*/
|
||
/**
|
||
* Felder, die die Person im Profil nicht selbst ändern darf: vom Anmeldedienst gepflegte,
|
||
* die E-Mail-Adresse (Anmeldung, Verknüpfung, IT-Service) und – solange nicht freigegeben –
|
||
* Abteilung und Standort, weil sie bestimmen, wer welche Inhalte sieht.
|
||
*
|
||
* @return list<string>
|
||
*/
|
||
public function lockedProfileFields(): array
|
||
{
|
||
$selfOrg = (bool) app(Settings::class)->get(ProfileFields::SELF_EDIT_ORG, false);
|
||
|
||
return array_values(array_unique([...$this->managedFields(), 'email', ...($selfOrg ? [] : ['department', 'location'])]));
|
||
}
|
||
|
||
public function managedFields(): array
|
||
{
|
||
return $this->identities()->with('provider')->get()
|
||
->filter(fn (UserIdentity $identity) => $identity->provider?->enabled)
|
||
->flatMap(fn (UserIdentity $identity) => $identity->provider->syncedFields())
|
||
->unique()->values()->all();
|
||
}
|
||
|
||
/**
|
||
* @return BelongsToMany<Role, $this>
|
||
*/
|
||
public function roles(): BelongsToMany
|
||
{
|
||
return $this->belongsToMany(Role::class)->withPivot('source', 'source_ref', 'created_at');
|
||
}
|
||
|
||
public function hasRole(string $slug): bool
|
||
{
|
||
return $this->roles()->where('slug', $slug)->exists();
|
||
}
|
||
|
||
public function isAdministrator(): bool
|
||
{
|
||
return $this->permissions()->isSuperuser();
|
||
}
|
||
|
||
/**
|
||
* Manuell vergebene Rollen setzen. Rollen aus Identity-Provider-Gruppen
|
||
* (Quelle „idp“) bleiben unberührt – Rollen sind additiv.
|
||
*
|
||
* @param list<int> $roleIds
|
||
*/
|
||
public function syncManualRoles(array $roleIds): void
|
||
{
|
||
$current = $this->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all();
|
||
|
||
foreach (array_diff($current, $roleIds) as $roleId) {
|
||
$this->roles()->wherePivot('source', 'manual')->detach($roleId);
|
||
}
|
||
|
||
foreach (array_diff($roleIds, $current) as $roleId) {
|
||
$this->roles()->attach($roleId, ['source' => 'manual', 'created_at' => now()]);
|
||
}
|
||
|
||
if (array_diff($roleIds, $current) || array_diff($current, $roleIds)) {
|
||
Audit::log('user.roles_changed', ['user' => $this->id, 'added' => array_values(array_diff($roleIds, $current)), 'removed' => array_values(array_diff($current, $roleIds))]);
|
||
}
|
||
|
||
Permissions::flush();
|
||
}
|
||
|
||
public function getFilamentAvatarUrl(): ?string
|
||
{
|
||
return $this->avatarUrl(96);
|
||
}
|
||
|
||
public function avatarUrl(int $size = 256): ?string
|
||
{
|
||
return app(Avatars::class)->url($this, $size);
|
||
}
|
||
|
||
/** Eigenes Titelbild im Profil (ohne: Standardbild aus dem Erscheinungsbild) */
|
||
public function coverUrl(): ?string
|
||
{
|
||
return app(Covers::class)->url($this);
|
||
}
|
||
|
||
/**
|
||
* @return Attribute<string, never>
|
||
*/
|
||
protected function initials(): Attribute
|
||
{
|
||
return Attribute::get(function (): string {
|
||
$parts = preg_split('/\s+/', trim($this->name)) ?: [];
|
||
$first = Str::substr($parts[0] ?? '', 0, 1);
|
||
$last = count($parts) > 1 ? Str::substr(end($parts), 0, 1) : '';
|
||
|
||
return Str::upper($first.$last) ?: '?';
|
||
});
|
||
}
|
||
|
||
/**
|
||
* @param Builder<User> $query
|
||
*/
|
||
public function scopeActive(Builder $query): void
|
||
{
|
||
$query->where('is_active', true);
|
||
}
|
||
|
||
/**
|
||
* Alle bestehenden Zugänge beenden: Sitzungen, „Angemeldet bleiben“, API-Tokens, Push-Abos.
|
||
*/
|
||
public function revokeAccess(bool $keepCurrentSession = false): void
|
||
{
|
||
$this->forceFill(['remember_token' => Str::random(60)])->saveQuietly();
|
||
$this->tokens()->delete();
|
||
PushSubscription::query()->where('user_id', $this->id)->delete();
|
||
AppDevice::query()->where('user_id', $this->id)->delete();
|
||
|
||
if (Schema::hasTable(config('session.table', 'sessions'))) {
|
||
DB::table(config('session.table', 'sessions'))->where('user_id', $this->id)
|
||
->when($keepCurrentSession && session()->isStarted(), fn ($q) => $q->where('id', '!=', session()->getId()))
|
||
->delete();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Keine Reset-Mail für deaktivierte Konten und für Konten, die sich nur über
|
||
* einen Anmeldedienst anmelden (sie sollen kein lokales Passwort bekommen).
|
||
*/
|
||
public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void
|
||
{
|
||
if (! $this->is_active || ($this->password === null && $this->identities()->exists())) {
|
||
return;
|
||
}
|
||
|
||
$this->notify(new ResetPassword($token));
|
||
}
|
||
}
|