sls/app/Models/User.php
2026-06-24 14:21:01 +05:30

88 lines
2.4 KiB
PHP

<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
#[Fillable(['name', 'email', 'password', 'role', 'microsoft_id', 'microsoft_token', 'microsoft_refresh_token', 'avatar', 'is_blocked'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
/**
* Check if user is an admin.
*/
public function isAdmin(): bool
{
return $this->role === 'admin';
}
/**
* Get the roles assigned to this user.
*/
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user');
}
/**
* Get the app overrides (allow/deny) for this user.
*/
public function overrides()
{
return $this->hasMany(UserAppOverride::class);
}
/**
* Get the authorized apps for this user, computed from roles and overrides.
*/
public function authorizedApps()
{
if ($this->isAdmin()) {
return App::orderBy('name', 'asc')->get();
}
$roleIds = $this->roles()->pluck('roles.id')->toArray();
// Get apps associated with user's roles
$roleAppIds = \DB::table('app_role')
->whereIn('role_id', $roleIds)
->pluck('app_id')
->toArray();
// Get user overrides
$overrides = $this->overrides()->get();
$allowedAppIds = $overrides->where('type', 'allow')->pluck('app_id')->toArray();
$deniedAppIds = $overrides->where('type', 'deny')->pluck('app_id')->toArray();
// Compute final allowed app IDs: (Role Apps + Allowed Overrides) - Denied Overrides
$finalAppIds = array_diff(
array_unique(array_merge($roleAppIds, $allowedAppIds)),
$deniedAppIds
);
return App::whereIn('id', $finalAppIds)->orderBy('name', 'asc')->get();
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}