llmbackend/app/Models/Admin.php
2024-12-04 12:54:46 +08:00

101 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
/**
* 管理员角色常量
*/
public const ROLE_SUPER = 'super';
public const ROLE_ADMIN = 'admin';
/**
* 有效的角色列表
*/
public const VALID_ROLES = [
self::ROLE_SUPER,
self::ROLE_ADMIN,
];
protected $table = 'admins';
protected $fillable = [
'username',
'email',
'password',
'role',
];
protected $hidden = [
'password',
];
protected $casts = [
'role' => 'string',
];
public function clients(): BelongsToMany
{
return $this->belongsToMany(Client::class, 'admin_client')
->withTimestamp('assigned_at');
}
/**
* 检查是否是超级管理员
*/
public function isSuperAdmin(): bool
{
return $this->role === self::ROLE_SUPER;
}
/**
* 检查是否是普通管理员
*/
public function isAdmin(): bool
{
return $this->role === self::ROLE_ADMIN;
}
/**
* 检查是否有效的管理员(包括超级管理员和普通管理员)
*/
public function isValidAdmin(): bool
{
return in_array($this->role, self::VALID_ROLES, true);
}
/**
* 检查是否可以管理指定的客户
*/
public function canManageClient(int $clientId): bool
{
if ($this->isSuperAdmin()) {
return true;
}
return $this->clients()->where('client_id', $clientId)->exists();
}
/**
* 检查是否可以管理指定的LLM提供商
*/
public function canManageLlmProvider(int $providerId): bool
{
if ($this->isSuperAdmin()) {
return true;
}
// 普通管理员只能管理与其关联客户绑定的LLM提供商
return $this->clients()
->whereHas('llmProvider', function ($query) use ($providerId) {
$query->where('id', $providerId);
})
->exists();
}
}