TraceDash/app/Models/User.php

110 lines
2.6 KiB
PHP

<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Trace\Channel as TraceChannel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'provider_id',
'email',
'username',
'display_name',
'avatar',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'email',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'is_admin' => 'boolean',
];
/**
* Get the channel permissions for the user.
*
* @return HasMany
*/
public function channelPermissions() : HasMany
{
return $this->hasMany(ChannelPermission::class, 'user_provider_id', 'provider_id');
}
/**
* Determine if the user has a channel permission.
*
* @param TraceChannel $channel
* @return bool
*/
public function hasChannelPermission(TraceChannel $channel): bool
{
if ($this->isAdmin()) {
return true;
}
// If the user is the owner of the channel, they have permission.
if ($channel->channel_id === $this->provider_id) {
return true;
}
return $this->channelPermissions()->where('channel_provider_id', $channel->channel_id)->exists();
}
/**
* Get Trace\Channel models that the user has access to.
*
* @return Collection
*/
public function getTraceChannels() : Collection
{
$channels = TraceChannel::all()->sortBy('channel_login');
if (! $this->isAdmin()) {
$permissionChannelIds = $this->channelPermissions()->pluck('channel_provider_id')->toArray();
$permissionChannelIds[] = $this->provider_id;
$channels = $channels->whereIn('channel_id', $permissionChannelIds);
}
return $channels;
}
/**
* Determine if the user is an admin.
*
* @return bool
*/
public function isAdmin() : bool
{
return $this->is_admin;
}
}