TraceDash/app/Models/User.php

110 lines
2.6 KiB
PHP
Raw Normal View History

2023-11-23 19:27:43 +01:00
<?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;
2023-11-24 14:01:33 +01:00
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
2023-11-23 19:27:43 +01:00
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',
2023-11-23 19:27:43 +01:00
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'is_admin' => 'boolean',
];
/**
* Get the channel permissions for the user.
2023-11-24 14:01:33 +01:00
*
* @return HasMany
*/
2023-11-24 14:01:33 +01:00
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();
}
2023-11-24 14:01:33 +01:00
/**
* 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;
2023-11-24 14:01:33 +01:00
$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;
}
2023-11-23 19:27:43 +01:00
}