This commit is contained in:
gr
2026-11-11 13:53:14 +08:00
parent 85ffda8fd0
commit fc347bf9a6
490 changed files with 70862 additions and 386 deletions
@@ -0,0 +1,497 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\auth;
use app\adminapi\logic\LoginLogic;
use app\adminapi\service\DoctorWebConsultationPolicy;
use app\adminapi\service\AdminAccessSyncService;
use app\common\cache\AdminAuthCache;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminDept;
use app\common\model\auth\AdminJobs;
use app\common\model\auth\AdminRole;
use app\common\model\auth\AdminSession;
use app\common\model\auth\SystemRole;
use app\common\cache\AdminTokenCache;
use app\common\service\FileService;
use app\common\service\TencentImService;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
/**
* 管理员逻辑
* Class AdminLogic
* @package app\adminapi\logic\auth
*/
class AdminLogic extends BaseLogic
{
/**
* @notes 添加管理员
* @param array $params
* @author 段誉
* @date 2021/12/29 10:23
*/
public static function add(array $params)
{
Db::startTrans();
try {
$passwordSalt = Config::get('project.unique_identification');
$password = create_password($params['password'], $passwordSalt);
$defaultAvatar = config('project.default_image.admin_avatar');
$avatar = !empty($params['avatar']) ? FileService::setFileUrl($params['avatar']) : $defaultAvatar;
// 处理资质图片:如果是数组则转为JSON字符串
$qualificationImages = '';
if (isset($params['qualification_images'])) {
if (is_array($params['qualification_images'])) {
$qualificationImages = json_encode($params['qualification_images'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
$qualificationImages = $params['qualification_images'];
}
}
$admin = Admin::create([
'name' => $params['name'],
'account' => $params['account'],
'avatar' => $avatar,
'password' => $password,
'create_time' => time(),
'disable' => $params['disable'],
'multipoint_login' => $params['multipoint_login'],
// 新增字段
'gender' => $params['gender'] ?? 1,
'age' => $params['age'] ?? null,
'phone' => $params['phone'] ?? null,
'title' => $params['title'] ?? null,
'department' => $params['department'] ?? null,
'specialty' => $params['specialty'] ?? null,
'education' => $params['education'] ?? null,
'experience' => $params['experience'] ?? null,
'honors' => $params['honors'] ?? null,
'license_no' => $params['license_no'] ?? '',
'qualification_images' => $qualificationImages,
'enable_image_consult' => $params['enable_image_consult'] ?? 1,
'enable_video_consult' => $params['enable_video_consult'] ?? 1,
'enable_charge' => $params['enable_charge'] ?? 0,
]);
// 角色
self::insertRole($admin['id'], $params['role_id'] ?? []);
// 部门
self::insertDept($admin['id'], $params['dept_id'] ?? []);
// 岗位
self::insertJobs($admin['id'], $params['jobs_id'] ?? []);
// 导入医生账号到腾讯云IM
self::importDoctorAccountToIm($admin['id'], $params['name']);
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollback();
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 编辑管理员
* @param array $params
* @return bool
* @author 段誉
* @date 2021/12/29 10:43
*/
public static function edit(array $params): bool
{
Db::startTrans();
try {
// 先锁将要加入的角色,再锁账号,与角色变更收集关联账号使用相同顺序。
$submittedRoleIds = self::normalizeRoleIds($params['role_id'] ?? []);
if ($submittedRoleIds !== []) {
$roles = SystemRole::whereIn('id', $submittedRoleIds)->order('id')->lock(true)->field('id')->select();
if (count($roles) !== count($submittedRoleIds)) { throw new \RuntimeException('角色不存在或已删除'); }
}
$current = Admin::where('id', $params['id'])->lock(true)->findOrEmpty();
if ($current->isEmpty()) { throw new \RuntimeException('管理员不存在'); }
// 处理资质图片:如果是数组则转为JSON字符串
$qualificationImages = '';
if (isset($params['qualification_images'])) {
if (is_array($params['qualification_images'])) {
$qualificationImages = json_encode($params['qualification_images'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
$qualificationImages = $params['qualification_images'];
}
}
// 基础信息
$data = [
'id' => $params['id'],
'name' => $params['name'],
'account' => $params['account'],
'disable' => $params['disable'],
'multipoint_login' => $params['multipoint_login'],
// 新增字段
'gender' => $params['gender'] ?? 1,
'age' => $params['age'] ?? null,
'phone' => $params['phone'] ?? null,
'title' => $params['title'] ?? null,
'department' => $params['department'] ?? null,
'specialty' => $params['specialty'] ?? null,
'education' => $params['education'] ?? null,
'experience' => $params['experience'] ?? null,
'honors' => $params['honors'] ?? null,
'license_no' => $params['license_no'] ?? '',
'qualification_images' => $qualificationImages,
'enable_image_consult' => $params['enable_image_consult'] ?? 1,
'enable_video_consult' => $params['enable_video_consult'] ?? 1,
'enable_charge' => $params['enable_charge'] ?? 0,
];
// 头像
$data['avatar'] = !empty($params['avatar']) ? FileService::setFileUrl($params['avatar']) : '';
// 密码
if (!empty($params['password'])) {
$passwordSalt = Config::get('project.unique_identification');
$data['password'] = create_password($params['password'], $passwordSalt);
}
// 改密、停用、角色及部门变化均影响原医院和SSO终端;先写事务内撤销记录。
$roleId = AdminRole::where('admin_id', $params['id'])->column('role_id');
$editRole = self::roleIdsChanged($roleId, $submittedRoleIds);
$deptChanged = AdminAccessSyncService::ids(AdminDept::where('admin_id', $params['id'])->column('dept_id'))
!== AdminAccessSyncService::ids($params['dept_id'] ?? []);
$securityChanged = !empty($params['password']) || (int) $params['disable'] === 1 || $editRole || $deptChanged
|| (string) $current['account'] !== (string) $params['account']
|| (int) $current['multipoint_login'] !== (int) $params['multipoint_login'];
$tokens = $securityChanged ? AdminAccessSyncService::revoke([(int) $params['id']]) : [];
Admin::update($data);
// 删除旧的关联信息
AdminRole::delByUserId($params['id']);
AdminDept::delByUserId($params['id']);
AdminJobs::delByUserId($params['id']);
// 角色
self::insertRole($params['id'], $submittedRoleIds);
// 部门
self::insertDept($params['id'], $params['dept_id'] ?? []);
// 岗位
self::insertJobs($params['id'], $params['jobs_id'] ?? []);
// 导入医生账号到腾讯云IM
self::importDoctorAccountToIm($params['id'], $params['name']);
Db::commit();
AdminAccessSyncService::clearCommitted([(int) $params['id']], $tokens);
return true;
} catch (\Exception $e) {
Db::rollback();
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 删除管理员
* @param array $params
* @return bool
* @author 段誉
* @date 2021/12/29 10:45
*/
public static function delete(array $params): bool
{
Db::startTrans();
try {
$admin = Admin::where('id', $params['id'])->lock(true)->findOrEmpty();
if ($admin->root == YesNoEnum::YES) {
throw new \Exception("超级管理员不允许被删除");
}
$tokens = AdminAccessSyncService::revoke([(int) $params['id']]);
Admin::destroy($params['id']);
// 删除旧的关联信息
AdminRole::delByUserId($params['id']);
AdminDept::delByUserId($params['id']);
AdminJobs::delByUserId($params['id']);
Db::commit();
AdminAccessSyncService::clearCommitted([(int) $params['id']], $tokens);
return true;
} catch (\Exception $e) {
Db::rollback();
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 过期token
* @param $token
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2021/12/29 10:46
*/
public static function expireToken($token): bool
{
$changed = Db::transaction(static function () use ($token): bool {
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) { return false; }
Admin::where('id', (int) $candidate['admin_id'])->lock(true)->field('id')->findOrEmpty();
return AdminSession::where('token', $token)->update(['expire_time' => time() - 1, 'update_time' => time()]) > 0;
});
if ($changed) { (new AdminTokenCache())->deleteAdminInfo($token); }
return $changed;
}
/**
* @notes 查看管理员详情
* @param $params
* @return array
* @author 段誉
* @date 2021/12/29 11:07
*/
public static function detail($params, $action = 'detail'): array
{
$admin = Admin::field([
'id', 'account', 'name', 'disable', 'root',
'multipoint_login', 'avatar', 'is_paw',
'gender', 'age', 'phone', 'title', 'department',
'specialty', 'education', 'experience', 'honors',
'license_no', 'qualification_images', 'enable_image_consult', 'enable_video_consult', 'enable_charge',
'work_wechat_userid'
])->findOrEmpty($params['id'])->toArray();
// 将资质图片JSON字符串转换为数组,供前端组件使用
if (!empty($admin['qualification_images'])) {
try {
$images = json_decode($admin['qualification_images'], true);
if (is_array($images)) {
$admin['qualification_images'] = $images;
}
} catch (\Exception $e) {
// 解析失败时保持原值
Log::error('解析资质图片失败: ' . $e->getMessage());
}
}
if ($action == 'detail') {
$roleIds = AdminRole::where('admin_id', $params['id'])->column('role_id');
if (in_array(2, $roleIds)) {
$admin['diagnosis_count'] = \app\common\model\tcm\Diagnosis::where('assistant_id', $params['id'])
->whereNull('delete_time')
->count();
}
return $admin;
}
$authRoleIds = AdminRole::where('admin_id', $params['id'])->column('role_id');
$admin['role_ids'] = array_values(array_map('intval', $authRoleIds));
$admin['web_consultation_policy'] = DoctorWebConsultationPolicy::publicPolicy();
$admin['need_bind_work_wechat'] = LoginLogic::adminMustBindWorkWechat([
'root' => (int) ($admin['root'] ?? 0),
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
]);
$result['user'] = $admin;
// 当前管理员角色拥有的菜单
$result['menu'] = MenuLogic::getMenuByAdminId($params['id']);
// 当前管理员橘色拥有的按钮权限
$result['permissions'] = AuthLogic::getBtnAuthByRoleId($admin);
return $result;
}
/**
* @notes 编辑超级管理员
* @param $params
* @return Admin
* @author 段誉
* @date 2022/4/8 17:54
*/
public static function editSelf($params)
{
$data = [
'id' => $params['admin_id'],
'name' => $params['name'],
'avatar' => FileService::setFileUrl($params['avatar']),
];
if (!empty($params['password'])) {
$passwordSalt = Config::get('project.unique_identification');
$data['password'] = create_password($params['password'], $passwordSalt);
}
$tokens = [];
$result = Db::transaction(static function () use ($params, $data, &$tokens) {
$admin = Admin::where('id', $params['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) { throw new \RuntimeException('管理员不存在或已停用'); }
if (!empty($params['password'])) {
$oldPassword = $params['password_old'] ?? null;
if (!is_string($oldPassword) || !hash_equals((string) $admin['password'],
create_password($oldPassword, (string) Config::get('project.unique_identification')))) {
throw new \RuntimeException('当前密码错误');
}
$tokens = AdminAccessSyncService::revoke([(int) $params['admin_id']]);
}
return Admin::update($data);
});
AdminAccessSyncService::clearCommitted([(int) $params['admin_id']], $tokens);
return $result;
}
/**
* @notes 新增角色
* @param $adminId
* @param $roleIds
* @throws \Exception
* @author 段誉
* @date 2022/11/25 14:23
*/
public static function insertRole($adminId, $roleIds)
{
$roleIds = self::normalizeRoleIds($roleIds);
if ($roleIds !== []) {
// 角色
$roleData = [];
foreach ($roleIds as $roleId) {
$roleData[] = [
'admin_id' => $adminId,
'role_id' => $roleId,
];
}
(new AdminRole())->saveAll($roleData);
}
}
/** @return int[] */
private static function normalizeRoleIds(mixed $roleIds): array
{
if (!is_array($roleIds)) {
return [];
}
$normalized = array_values(array_unique(array_filter(
array_map('intval', $roleIds),
static fn (int $roleId): bool => $roleId > 0
)));
sort($normalized, SORT_NUMERIC);
return $normalized;
}
/**
* 角色是无序集合;新增、移除或替换都必须使现有 Token 失效,仅顺序变化不算修改。
*
* @param array<int|string,mixed> $currentRoleIds
* @param array<int|string,mixed> $submittedRoleIds
*/
private static function roleIdsChanged(array $currentRoleIds, array $submittedRoleIds): bool
{
return self::normalizeRoleIds($currentRoleIds) !== self::normalizeRoleIds($submittedRoleIds);
}
/**
* @notes 新增部门
* @param $adminId
* @param $deptIds
* @throws \Exception
* @author 段誉
* @date 2022/11/25 14:22
*/
public static function insertDept($adminId, $deptIds)
{
// 部门
if (!empty($deptIds)) {
$deptData = [];
foreach ($deptIds as $deptId) {
$deptData[] = [
'admin_id' => $adminId,
'dept_id' => $deptId
];
}
(new AdminDept())->saveAll($deptData);
}
}
/**
* @notes 新增岗位
* @param $adminId
* @param $jobsIds
* @throws \Exception
* @author 段誉
* @date 2022/11/25 14:22
*/
public static function insertJobs($adminId, $jobsIds)
{
// 岗位
if (!empty($jobsIds)) {
$jobsData = [];
foreach ($jobsIds as $jobsId) {
$jobsData[] = [
'admin_id' => $adminId,
'jobs_id' => $jobsId
];
}
(new AdminJobs())->saveAll($jobsData);
}
}
/**
* @notes 导入医生账号到腾讯云IM
* @param int $adminId 管理员ID
* @param string $name 管理员名称
* @return void
* @author AI Assistant
* @date 2026/03/02
*/
public static function importDoctorAccountToIm($adminId, $name)
{
try {
$userId = 'doctor_' . $adminId;
Log::info('开始导入医生IM账号 - admin_id: ' . $adminId . ', user_id: ' . $userId . ', name: ' . $name);
$imService = new TencentImService();
$result = $imService->importAccount($userId, $name);
if ($result) {
Log::info('医生IM账号导入成功 - admin_id: ' . $adminId . ', user_id: ' . $userId);
} else {
Log::warning('医生IM账号导入失败 - admin_id: ' . $adminId . ', user_id: ' . $userId);
}
} catch (\Exception $e) {
Log::error('导入医生IM账号异常 - admin_id: ' . $adminId . ', error: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,118 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\auth;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\auth\SystemMenu;
use app\common\model\auth\SystemRoleMenu;
use app\common\service\qywx\QywxPromotionOperatorAccess;
use app\common\service\ActiveMenuPermissions;
/**
* 权限功能类
* Class AuthLogic
* @package app\adminapi\logic\auth
*/
class AuthLogic
{
/**
* @notes 获取全部权限
* @return mixed
* @author 段誉
* @date 2022/7/1 11:55
*/
public static function getAllAuth()
{
return SystemMenu::distinct(true)
->where([
['is_disable', '=', 0],
['perms', '<>', '']
])
->column('perms');
}
/**
* @notes 获取当前管理员角色按钮权限
* @param $roleId
* @return mixed
* @author 段誉
* @date 2022/7/1 16:10
*/
public static function getBtnAuthByRoleId($admin)
{
if ($admin['root']) {
return ['*'];
}
$menuId = SystemRoleMenu::whereIn('role_id', $admin['role_id'])
->column('menu_id');
$where[] = ['is_disable', '=', 0];
$where[] = ['perms', '<>', ''];
$where[] = ['id', 'in', ActiveMenuPermissions::ids()];
$roleAuth = SystemMenu::distinct(true)
->where('id', 'in', $menuId)
->where($where)
->column('perms');
// 普通账号只返回当前有效原权限;全部剩余权限恰好获授也不能推导为可覆盖停用菜单的通配符。
return self::appendSharedPromotionPermission($roleAuth, (int) ($admin['id'] ?? 0));
}
/**
* @notes 获取管理员角色关联的菜单id(菜单,权限)
* @param int $adminId
* @return array
* @author 段誉
* @date 2022/7/1 15:56
*/
public static function getAuthByAdminId(int $adminId): array
{
$roleIds = AdminRole::where('admin_id', $adminId)->column('role_id');
$menuId = SystemRoleMenu::whereIn('role_id', $roleIds)->column('menu_id');
$permissions = SystemMenu::distinct(true)
->where([
['is_disable', '=', 0],
['perms', '<>', ''],
['id', 'in', array_unique($menuId)],
])
->whereIn('id', ActiveMenuPermissions::ids())
->column('perms');
return self::appendSharedPromotionPermission($permissions, $adminId);
}
private static function appendSharedPromotionPermission(array $permissions, int $adminId): array
{
if (in_array('*', $permissions, true)
|| in_array(QywxPromotionOperatorAccess::PAGE_PERMISSION, $permissions, true)
|| !ActiveMenuPermissions::has(QywxPromotionOperatorAccess::PAGE_PERMISSION)
|| !QywxPromotionOperatorAccess::hasSharedPagePermission($adminId)) {
return $permissions;
}
$permissions[] = QywxPromotionOperatorAccess::PAGE_PERMISSION;
return array_values(array_unique($permissions));
}
}
@@ -0,0 +1,250 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\auth;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\auth\Admin;
use app\common\model\auth\SystemMenu;
use app\common\model\auth\SystemRoleMenu;
use app\common\service\qywx\QywxPromotionOperatorAccess;
use app\adminapi\service\AdminAccessSyncService;
use think\facade\Db;
use app\common\service\ActiveMenuPermissions;
/**
* 系统菜单
* Class MenuLogic
* @package app\adminapi\logic\auth
*/
class MenuLogic extends BaseLogic
{
/**
* @notes 获取管理员对应的角色菜单
* @param $adminId
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/7/1 10:50
*/
public static function getMenuByAdminId($adminId)
{
$admin = Admin::findOrEmpty($adminId);
$where = [];
$where[] = ['type', 'in', ['M', 'C']];
$where[] = ['is_disable', '=', 0];
$where[] = ['id', 'in', ActiveMenuPermissions::ids()];
if ($admin['root'] != 1) {
$roleMenu = SystemRoleMenu::whereIn('role_id', $admin['role_id'])->column('menu_id');
if (QywxPromotionOperatorAccess::hasSharedPagePermission((int) $adminId)) {
$roleMenu = array_values(array_unique(array_merge(
array_map('intval', $roleMenu),
self::sharedPromotionMenuIds()
)));
}
$where[] = ['id', 'in', $roleMenu];
}
$menu = SystemMenu::where($where)
->order(['sort' => 'desc', 'id' => 'asc'])
->select();
return linear_to_tree($menu, 'children');
}
/** @return list<int> */
private static function sharedPromotionMenuIds(): array
{
$menus = SystemMenu::where('is_disable', 0)
->field('id,pid,perms')
->select()
->toArray();
$byId = [];
$pageIds = [];
foreach ($menus as $menu) {
$id = (int) ($menu['id'] ?? 0);
if ($id <= 0) {
continue;
}
$byId[$id] = $menu;
if ((string) ($menu['perms'] ?? '') === QywxPromotionOperatorAccess::PAGE_PERMISSION) {
$pageIds[] = $id;
}
}
$result = [];
foreach ($pageIds as $pageId) {
$chain = [];
$seen = [];
$currentId = $pageId;
while ($currentId > 0) {
if (isset($seen[$currentId]) || !isset($byId[$currentId])) {
$chain = [];
break;
}
$seen[$currentId] = true;
$chain[] = $currentId;
$currentId = (int) ($byId[$currentId]['pid'] ?? 0);
}
$result = array_merge($result, $chain);
}
return array_values(array_unique($result));
}
/**
* @notes 添加菜单
* @param array $params
* @return SystemMenu|\think\Model
* @author 段誉
* @date 2022/6/30 10:06
*/
public static function add(array $params)
{
return SystemMenu::create([
'pid' => $params['pid'],
'type' => $params['type'],
'name' => $params['name'],
'icon' => $params['icon'] ?? '',
'sort' => $params['sort'],
'perms' => $params['perms'] ?? '',
'paths' => $params['paths'] ?? '',
'component' => $params['component'] ?? '',
'selected' => $params['selected'] ?? '',
'params' => $params['params'] ?? '',
'is_cache' => $params['is_cache'],
'is_show' => $params['is_show'],
'is_disable' => $params['is_disable'],
]);
}
/**
* @notes 编辑菜单
* @param array $params
* @return SystemMenu
* @author 段誉
* @date 2022/6/30 10:07
*/
public static function edit(array $params)
{
return self::mutate((int) $params['id'], static fn () => SystemMenu::update([
'id' => $params['id'],
'pid' => $params['pid'],
'type' => $params['type'],
'name' => $params['name'],
'icon' => $params['icon'] ?? '',
'sort' => $params['sort'],
'perms' => $params['perms'] ?? '',
'paths' => $params['paths'] ?? '',
'component' => $params['component'] ?? '',
'selected' => $params['selected'] ?? '',
'params' => $params['params'] ?? '',
'is_cache' => $params['is_cache'],
'is_show' => $params['is_show'],
'is_disable' => $params['is_disable'],
]));
}
/**
* @notes 详情
* @param $params
* @return array
* @author 段誉
* @date 2022/6/30 9:54
*/
public static function detail($params)
{
return SystemMenu::findOrEmpty($params['id'])->toArray();
}
/**
* @notes 删除菜单
* @param $params
* @author 段誉
* @date 2022/6/30 9:47
*/
public static function delete($params)
{
self::mutate((int) $params['id'], static function () use ($params): void {
SystemMenu::destroy($params['id']);
SystemRoleMenu::where(['menu_id' => $params['id']])->delete();
});
}
/**
* @notes 更新状态
* @param array $params
* @return SystemMenu
* @author 段誉
* @date 2022/7/6 17:02
*/
public static function updateStatus(array $params)
{
return self::mutate((int) $params['id'], static fn () => SystemMenu::update([
'id' => $params['id'],
'is_disable' => $params['is_disable']
]));
}
private static function mutate(int $menuId, callable $operation)
{
$adminIds = [];
$tokens = [];
$result = Db::transaction(static function () use ($menuId, $operation, &$adminIds, &$tokens) {
SystemMenu::where('id', $menuId)->lock(true)->findOrEmpty();
$adminIds = AdminAccessSyncService::menuAdminIds($menuId);
$tokens = AdminAccessSyncService::revoke($adminIds);
return $operation();
});
AdminAccessSyncService::clearCommitted($adminIds, $tokens);
return $result;
}
/**
* @notes 全部数据
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/10/13 11:03
*/
public static function getAllData()
{
$data = SystemMenu::where(['is_disable' => YesNoEnum::NO])
->field('id,pid,name')
->order(['sort' => 'desc', 'id' => 'desc'])
->select()
->toArray();
return linear_to_tree($data, 'children');
}
}
@@ -0,0 +1,214 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\auth;
use app\common\{
cache\AdminAuthCache,
model\auth\SystemRole,
logic\BaseLogic,
model\auth\SystemRoleMenu
};
use think\facade\Db;
use app\adminapi\service\AdminAccessSyncService;
use app\common\model\auth\AdminRole;
/**
* 角色逻辑层
* Class RoleLogic
* @package app\adminapi\logic\auth
*/
class RoleLogic extends BaseLogic
{
/**
* @notes 添加角色
* @param array $params
* @return bool
* @author 段誉
* @date 2021/12/29 11:50
*/
public static function add(array $params): bool
{
self::$returnData = [];
Db::startTrans();
try {
$menuId = !empty($params['menu_id']) ? $params['menu_id'] : [];
$role = SystemRole::create([
'name' => $params['name'],
'desc' => $params['desc'] ?? '',
'sort' => $params['sort'] ?? 0,
'data_scope' => self::normalizeDataScope($params['data_scope'] ?? null),
]);
$data = [];
foreach ($menuId as $item) {
if (empty($item)) {
continue;
}
$data[] = [
'role_id' => $role['id'],
'menu_id' => $item,
];
}
if ($data !== []) { (new SystemRoleMenu)->insertAll($data); }
Db::commit();
// 返回本次已提交的角色编号,集团跨目录授权不能按名称或其他表的自增编号猜测。
self::$returnData = ['id' => (int) $role['id']];
return true;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 编辑角色
* @param array $params
* @return bool
* @author 段誉
* @date 2021/12/29 14:16
*/
public static function edit(array $params): bool
{
Db::startTrans();
try {
$role = SystemRole::where('id', $params['id'])->lock(true)->findOrEmpty();
if ($role->isEmpty()) { throw new \RuntimeException('角色不存在'); }
$adminIds = AdminAccessSyncService::roleAdminIds([(int) $params['id']]);
$tokens = AdminAccessSyncService::revoke($adminIds);
$menuId = !empty($params['menu_id']) ? $params['menu_id'] : [];
$roleRow = [
'id' => $params['id'],
'name' => $params['name'],
'desc' => $params['desc'] ?? '',
'sort' => $params['sort'] ?? 0,
];
// 分配权限等非编辑页提交的 edit 若不传 data_scope,不得把库里的范围覆盖成默认全部
if (array_key_exists('data_scope', $params)) {
$roleRow['data_scope'] = self::normalizeDataScope($params['data_scope'] ?? null);
}
SystemRole::update($roleRow);
// 显式空数组表示收回全部权限;省略字段表示保留原授权。
if (array_key_exists('menu_id', $params)) {
SystemRoleMenu::where(['role_id' => $params['id']])->delete();
$data = [];
foreach ($menuId as $item) {
$data[] = [
'role_id' => $params['id'],
'menu_id' => $item,
];
}
if ($data !== []) {
(new SystemRoleMenu)->insertAll($data);
}
}
Db::commit();
AdminAccessSyncService::clearCommitted($adminIds, $tokens);
return true;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 删除角色
* @param int $id
* @return bool
* @author 段誉
* @date 2021/12/29 14:16
*/
public static function delete(int $id)
{
Db::startTrans();
try {
SystemRole::where('id', $id)->lock(true)->findOrEmpty();
$adminIds = AdminAccessSyncService::roleAdminIds([$id]);
$tokens = AdminAccessSyncService::revoke($adminIds);
SystemRole::destroy(['id' => $id]);
// 原权限查询直接读关联表;软删角色时必须删除关联才能真正收回URI权限。
SystemRoleMenu::where('role_id', $id)->delete();
AdminRole::where('role_id', $id)->delete();
Db::commit();
AdminAccessSyncService::clearCommitted($adminIds, $tokens);
return true;
} catch (\Exception $error) {
Db::rollback();
self::$error = $error->getMessage();
return false;
}
}
/**
* @notes 角色详情
* @param int $id
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2021/12/29 14:17
*/
public static function detail(int $id): array
{
$detail = SystemRole::field('id,name,desc,sort,data_scope')->find($id);
$authList = $detail->roleMenuIndex()->select()->toArray();
$menuId = array_column($authList, 'menu_id');
$detail['menu_id'] = $menuId;
return $detail->toArray();
}
/**
* 规范化 data_scope:合法值 1-4,非法或缺省统一回退为 1(全部),保持与历史默认一致不增加风险。
*/
private static function normalizeDataScope($value): int
{
$v = (int) $value;
if ($v >= 1 && $v <= 4) {
return $v;
}
return 1;
}
/**
* @notes 角色数据
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/10/13 10:39
*/
public static function getAllData()
{
return SystemRole::order(['sort' => 'desc', 'id' => 'desc'])
->select()
->toArray();
}
}