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,370 @@
<?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;
use app\common\logic\BaseLogic;
use app\common\model\auth\Admin;
use app\adminapi\service\AdminTokenService;
use app\common\service\FileService;
use think\facade\Config;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Db;
use app\adminapi\service\AdminAccessSyncService;
use app\common\service\JsonService;
/**
* 登录逻辑
* Class LoginLogic
* @package app\adminapi\logic
*/
class LoginLogic extends BaseLogic
{
/** 非 root 未绑定企微时接口返回,与 axios 约定一致 */
public const CODE_NEED_BIND_WORK_WECHAT = 10;
/**
* 企业微信网页授权 / 扫码绑定所需配置是否齐全
*/
public static function isWorkWechatOAuthConfigured(): bool
{
$corpId = (string) env('work_wechat.corp_id', '');
$secret = (string) env('work_wechat.secret', '');
$agentId = (string) env('work_wechat.agent_id', '');
return $corpId !== '' && $secret !== '' && $agentId !== '';
}
/**
* .env 是否开启「非 root 须绑定企微」。
* 推荐在 [work_wechat] 下写 FORCE_BIND_LOGIN=true;勿在节内写 WORK_WECHAT_FORCE_BIND_LOGIN(会变成双前缀键读不到)。
*/
public static function isForceBindWorkWechatFromEnv(): bool
{
$candidates = [
env('WORK_WECHAT_FORCE_BIND_LOGIN', false),
env('work_wechat.force_bind_login', false),
env('work_wechat.work_wechat_force_bind_login', false),
];
$v = false;
foreach ($candidates as $c) {
if ($c !== false && $c !== null && $c !== '') {
$v = $c;
break;
}
}
if (is_bool($v)) {
return $v;
}
$v = strtolower(trim((string) $v));
return in_array($v, ['1', 'true', 'yes', 'on'], true);
}
/**
* .env 开启强制绑定 + 企微 OAuth 已配置 + 非 root + 未绑定 work_wechat_userid
*
* @param array{root?:int|string,work_wechat_userid?:string} $adminInfo
*/
public static function adminMustBindWorkWechat(array $adminInfo): bool
{
if (!self::isForceBindWorkWechatFromEnv()) {
return false;
}
if (!self::isWorkWechatOAuthConfigured()) {
return false;
}
if ((int) ($adminInfo['root'] ?? 0) === 1) {
return false;
}
return trim((string) ($adminInfo['work_wechat_userid'] ?? '')) === '';
}
/**
* 开启「须绑定企微」时,这些 action 仍须放行(与 $request->action() 比较,不区分大小写)。
* 路由/网关若把 action 变成全小写,严格 in_array('bindWorkWechat') 会失败,导致绑定接口被误判为 code=10,扫码页反复刷新。
*/
public static function isWorkWechatBindExemptActionName(string $action): bool
{
$a = strtolower(trim($action));
return in_array($a, [
'bindworkwechat',
'unbindworkwechat',
'myself',
'logout',
], true);
}
/**
* @notes 管理员账号登录
* @param $params
* @return false|mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/6/30 17:00
*/
public function login($params)
{
return Db::transaction(static function () use ($params) {
$time = time();
$admin = Admin::where('account', '=', $params['account'])->lock(true)->findOrEmpty();
// 原网页调试开关只在原入口双门禁同时满足时保留;集团接口在外层始终复核真实密码。
$debug = in_array(strtolower((string) env('app_debug', '0')), ['1', 'true', 'yes', 'on'], true)
&& in_array(strtolower((string) env('local_debug.login_skip_password', '')), ['1', 'true', 'yes', 'on'], true);
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || (!$debug
&& !hash_equals((string) $admin['password'], create_password((string) ($params['password'] ?? ''),
(string) Config::get('project.unique_identification'))))) {
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
}
//用户表登录信息更新
$admin->login_time = $time;
$admin->login_ip = request()->ip();
$admin->save();
//设置token
$adminInfo = AdminTokenService::setToken($admin->id, $params['terminal'], $admin->multipoint_login);
//返回登录信息
$avatar = $admin->avatar ? $admin->avatar : Config::get('project.default_image.admin_avatar');
$avatar = FileService::getFileUrl($avatar);
$row = [
'name' => $adminInfo['name'],
'avatar' => $avatar,
'role_name' => $adminInfo['role_name'],
'token' => $adminInfo['token'],
'is_paw' => $admin->is_paw ?? 1, // 0=需要修改密码,1=正常
];
$row['need_bind_work_wechat'] = self::adminMustBindWorkWechat([
'root' => (int) ($admin->root ?? 0),
'work_wechat_userid' => (string) ($admin->work_wechat_userid ?? ''),
]);
return $row;
});
}
/**
* 从 auth/getuserinfo 响应解析企业成员 userid。
* 非通讯录成员时接口可能只返回 openid / external_userid,无 userid。
*/
public static function workWechatUserIdFromAuthResponse(array $response): string
{
return trim((string) ($response['userid'] ?? $response['UserId'] ?? ''));
}
/**
* @notes 企业微信授权登录
*/
public function workWechatLogin($params)
{
$code = $params['code'];
$terminal = $params['terminal'] ?? 1;
$corpId = env('work_wechat.corp_id', '');
$secret = env('work_wechat.secret', '');
if (empty($corpId) || empty($secret)) {
self::setError('企业微信未配置');
return false;
}
// 获取 access_token
$accessToken = self::getWorkWechatAccessToken($corpId, $secret);
if (!$accessToken) {
return false;
}
// 用 code 换取用户身份
$url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token={$accessToken}&code={$code}";
$response = self::httpGet($url);
if (!$response || $response['errcode'] != 0) {
$errMsg = $response['errmsg'] ?? '未知错误';
Log::error('企业微信获取用户身份失败: ' . $errMsg);
self::setError('企业微信授权失败: ' . $errMsg);
return false;
}
$wxUserId = self::workWechatUserIdFromAuthResponse($response);
if ($wxUserId === '') {
$hasOpenId = trim((string) ($response['openid'] ?? $response['OpenId'] ?? '')) !== '';
self::setError(
$hasOpenId
? '当前身份非企业通讯录成员(或未同步到通讯录),无法用此账号登录后台,请使用企业内成员账号或联系管理员将你加入通讯录'
: '未获取到企业微信成员 userid,请检查自建应用 Secret、可信域名是否与当前扫码应用一致'
);
return false;
}
// 通过 work_wechat_userid 匹配管理员(SoftDelete trait 自动排除已删除记录)
$admin = Admin::where('work_wechat_userid', '=', $wxUserId)->find();
if (!$admin) {
self::setError('该企业微信账号未绑定管理员,请联系管理员绑定(UserId: ' . $wxUserId . ')');
return false;
}
if ($admin->disable === 1) {
self::setError('账号已被禁用');
return false;
}
return Db::transaction(static function () use ($admin, $terminal, $wxUserId) {
$admin = Admin::where('id', $admin->id)->where('work_wechat_userid', $wxUserId)->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) {
JsonService::throw('账号已停用或绑定已变更', [], -1);
}
// 更新登录信息
$time = time();
$admin->login_time = $time;
$admin->login_ip = request()->ip();
$admin->save();
// 设置 token
$adminInfo = AdminTokenService::setToken($admin->id, $terminal, $admin->multipoint_login);
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
$avatar = FileService::getFileUrl($avatar);
return [
'name' => $adminInfo['name'],
'avatar' => $avatar,
'role_name' => $adminInfo['role_name'],
'token' => $adminInfo['token'],
'is_paw' => $admin->is_paw ?? 1, // 0=需要修改密码,1=正常
// 企微扫码登录即已绑定 userid
'need_bind_work_wechat' => false,
];
});
}
/**
* @notes 获取企业微信 access_token(带缓存),供外部(如绑定流程)调用
*/
public static function getWorkWechatAccessTokenStatic(string $corpId, string $secret)
{
return self::getWorkWechatAccessToken($corpId, $secret);
}
/**
* @notes 获取企业微信 access_token(带缓存)
*/
private static function getWorkWechatAccessToken(string $corpId, string $secret)
{
$cacheKey = 'work_wechat_access_token_' . md5($corpId . $secret);
$cached = Cache::get($cacheKey);
if ($cached) {
return $cached;
}
$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpId}&corpsecret={$secret}";
$response = self::httpGet($url);
if (!$response || $response['errcode'] != 0) {
$errMsg = $response['errmsg'] ?? '未知错误';
Log::error('获取企业微信access_token失败: ' . $errMsg);
self::setError('获取企业微信凭证失败: ' . $errMsg);
return false;
}
$accessToken = $response['access_token'];
Cache::set($cacheKey, $accessToken, $response['expires_in'] - 200);
return $accessToken;
}
/**
* @notes HTTP GET 请求
*/
private static function httpGet(string $url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
curl_close($ch);
if ($result === false) {
return null;
}
return json_decode($result, true);
}
/**
* @notes 退出登录
* @param $adminInfo
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/5 14:34
*/
public function logout($adminInfo)
{
//token不存在,不注销
if (!isset($adminInfo['token'])) {
return false;
}
//设置token过期
return AdminTokenService::expireToken($adminInfo['token']);
}
/**
* @notes 首次登录修改密码
* @param string $token
* @param string $password
* @return bool
*/
public function changeFirstPassword($token, $password)
{
try {
if (!is_string($password) || strlen($password) < 6 || strlen($password) > 32 || str_contains($password, "\0")) {
throw new \RuntimeException('密码长度须在6-32字节');
}
$adminId = 0;
$tokens = Db::transaction(static function () use ($token, $password, &$adminId): array {
$candidate = \app\common\model\auth\AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) { throw new \RuntimeException('登录已过期,请重新登录'); }
$adminId = (int) $candidate['admin_id'];
$admin = Admin::where('id', $adminId)->lock(true)->findOrEmpty();
$active = \app\common\model\auth\AdminSession::where('token', $token)->where('admin_id', $adminId)
->where('expire_time', '>', time())->lock(true)->count();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !$active) {
throw new \RuntimeException('登录已过期,请重新登录');
}
if ((int) $admin['is_paw'] !== 0) { throw new \RuntimeException('首次密码已设置,请使用个人改密'); }
$admin->password = create_password($password, (string) Config::get('project.unique_identification'));
$admin->is_paw = 1;
$admin->save();
return AdminAccessSyncService::revoke([$adminId]);
});
AdminAccessSyncService::clearCommitted([$adminId], $tokens);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
}
@@ -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();
}
}