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
@@ -52,7 +52,7 @@ class RoleController extends BaseAdminController
$params = (new RoleValidate())->post()->goCheck('add');
$res = RoleLogic::add($params);
if (true === $res) {
return $this->success('添加成功', [], 1, 1);
return $this->success('添加成功', RoleLogic::getReturnData(), 1, 1);
}
return $this->fail(RoleLogic::getError());
}
@@ -121,4 +121,4 @@ class RoleController extends BaseAdminController
return $this->data($result);
}
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace app\adminapi\controller\identity;
use app\adminapi\controller\BaseAdminController;
use app\adminapi\service\IdentityHospitalSsoService;
use app\common\service\JsonService;
use think\exception\HttpResponseException;
final class HospitalSsoController extends BaseAdminController
{
// The service authenticates the real source DB session; exchange authenticates its private PKCE ticket.
public array $notNeedLogin = ['issue', 'exchange'];
public function issue()
{
return $this->handoff('issue');
}
public function exchange()
{
return $this->handoff('exchange');
}
private function handoff(string $operation)
{
$headers = ['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer'];
if (!$this->request->isPost()) { return JsonService::fail('请使用POST请求')->code(405)->header($headers); }
if ($this->request->get() !== []) { return JsonService::fail('请求包含不支持的字段')->header($headers); }
$origin = (string) $this->request->header('origin', '');
if ($operation === 'exchange' && (($origin !== '' && $origin !== $this->request->domain())
|| $this->request->header('sec-fetch-site', '') === 'cross-site')) {
return JsonService::fail('登录请求来源不合法')->header($headers);
}
try {
$service = new IdentityHospitalSsoService();
$result = $operation === 'issue'
? $service->issue((string) $this->request->header('token', ''), $this->request->post())
: $service->exchange($this->request->post());
return JsonService::data($result)->header($headers);
} catch (HttpResponseException $error) { return $error->getResponse()->header($headers); }
catch (\Throwable $error) { return JsonService::fail('医院登录暂时不可用,请稍后重试')->header($headers); }
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace app\adminapi\controller\identity;
use app\adminapi\controller\BaseAdminController;
use app\adminapi\service\IdentitySessionService;
use app\adminapi\validate\LoginValidate;
use app\common\enum\AdminTerminalEnum;
use app\common\service\JsonService;
/** 独立账号后台的个人会话接口,服务内部始终核验真实数据库会话。 */
class SessionController extends BaseAdminController
{
// 首次改密/待绑定企微时也必须可用;这里仅跳过旧门禁,绝不跳过服务内认证。
public array $notNeedLogin = ['login', 'verify', 'password', 'logout'];
public function verify()
{
if (!$this->request->isPost()) {
return JsonService::fail('请使用POST请求');
}
$params = $this->request->post();
if (array_diff(array_keys($params), ['account', 'password']) !== []
|| !is_string($params['account'] ?? null) || $params['account'] === '' || strlen($params['account']) > 4096
|| str_contains($params['account'], "\0") || !is_string($params['password'] ?? null)
|| $params['password'] === '' || strlen($params['password']) > 4096 || str_contains($params['password'], "\0")) {
return JsonService::fail('登录参数不合法');
}
$params = (new LoginValidate())->post()->goCheck('verify');
return $this->data(IdentitySessionService::verify($params));
}
public function login()
{
if (!$this->request->isPost()) {
return JsonService::fail('请使用POST请求');
}
// 专用集团终端只在此入口接受;不扩大普通网页登录的终端白名单。
$terminal = $this->request->post('terminal');
$groupSession = in_array($terminal, [AdminTerminalEnum::GROUP_IDENTITY, (string) AdminTerminalEnum::GROUP_IDENTITY], true);
// verify 场景保留原限流并禁用调试免密;服务仍在账号锁内校验全部参数与当前密码。
$params = (new LoginValidate())->post()->goCheck($groupSession ? 'verify' : null);
return $this->data(IdentitySessionService::login($params));
}
public function password()
{
if (!$this->request->isPost()) {
return JsonService::fail('请使用POST请求');
}
IdentitySessionService::changePassword((string) $this->request->header('token', ''), $this->request->post());
return $this->success('密码修改成功,请重新登录');
}
public function logout()
{
if (!$this->request->isPost()) {
return JsonService::fail('请使用POST请求');
}
$params = $this->request->post();
if (array_diff(array_keys($params), ['all']) !== [] || !in_array($params['all'] ?? 0, [0, 1, '0', '1'], true)) {
return JsonService::fail('退出参数不合法');
}
IdentitySessionService::logout((string) $this->request->header('token', ''), (int) ($params['all'] ?? 0) === 1);
return $this->success('已退出登录');
}
}
@@ -1,85 +1,94 @@
<?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
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\adminapi\http\middleware;
<?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
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\adminapi\http\middleware;
use app\adminapi\logic\LoginLogic;
use app\adminapi\service\CoreAccountPermissionPolicy;
use app\common\service\pharmacy\PharmacyUploadPermissionAlias;
use app\common\service\qywx\QywxPromotionOperatorAccess;
use app\common\{
cache\AdminAuthCache,
enum\AdminTerminalEnum,
service\JsonService
};
use think\helper\Str;
/**
* 权限验证中间件
* Class AuthMiddleware
* @package app\adminapi\http\middleware
*/
class AuthMiddleware
{
/**
* @notes 权限验证
* @param $request
* @param \Closure $next
* @return mixed
* @author 令狐冲
* @date 2021/7/2 19:29
*/
public function handle($request, \Closure $next)
{
//不登录访问,无需权限验证
if ($request->controllerObject->isNotNeedLogin()) {
return $next($request);
}
// 登录 IP 绑定;客服后台服务器代查患者/订单的例外见 isTrustedRpaServerRequest
if ($request->adminInfo['login_ip'] != request()->ip()
&& !self::isTrustedRpaServerRequest(
(array) $request->adminInfo,
request()->ip(),
env('wecom_rpa.server_ips', '')
)) {
return JsonService::fail('ip地址发生变化,请重新登录', [], -1);
}
// 非 root 待绑企微:放行绑定 / 解绑 / 个人信息 / 退出(避免无菜单权限;action 与路由大小写一致)
if (LoginLogic::adminMustBindWorkWechat($request->adminInfo)) {
if (LoginLogic::isWorkWechatBindExemptActionName((string) $request->action())) {
return $next($request);
}
}
//系统默认超级管理员,无需权限验证
if (1 === $request->adminInfo['root']) {
return $next($request);
}
// 面诊进度看板:仅登录即可拉医生列表 + 预约列表(须带 progress_board=1,见 AdminLists / AppointmentLists 内限制)
if ($this->isFaceProgressBoardPublicLists($request)) {
return $next($request);
}
$adminAuthCache = new AdminAuthCache($request->adminInfo['admin_id']);
use app\common\{
cache\AdminAuthCache,
enum\AdminTerminalEnum,
service\JsonService
};
use think\helper\Str;
/**
* 权限验证中间件
* Class AuthMiddleware
* @package app\adminapi\http\middleware
*/
class AuthMiddleware
{
/**
* @notes 权限验证
* @param $request
* @param \Closure $next
* @return mixed
* @author 令狐冲
* @date 2021/7/2 19:29
*/
public function handle($request, \Closure $next)
{
//不登录访问,无需权限验证
if ($request->controllerObject->isNotNeedLogin()) {
return $next($request);
}
// 登录 IP 绑定;客服后台服务器代查患者/订单的例外见 isTrustedRpaServerRequest
if ($request->adminInfo['login_ip'] != request()->ip()
&& !self::isTrustedRpaServerRequest(
(array) $request->adminInfo,
request()->ip(),
env('wecom_rpa.server_ips', '')
)) {
return JsonService::fail('ip地址发生变化,请重新登录', [], -1);
}
// 非 root 待绑企微:放行绑定 / 解绑 / 个人信息 / 退出(避免无菜单权限;action 与路由大小写一致)
if (LoginLogic::adminMustBindWorkWechat($request->adminInfo)) {
if (LoginLogic::isWorkWechatBindExemptActionName((string) $request->action())) {
return $next($request);
}
}
//系统默认超级管理员,无需权限验证
if (1 === $request->adminInfo['root']) {
return $next($request);
}
// 面诊进度看板:仅登录即可拉医生列表 + 预约列表(须带 progress_board=1,见 AdminLists / AppointmentLists 内限制)
if ($this->isFaceProgressBoardPublicLists($request)) {
return $next($request);
}
$adminAuthCache = new AdminAuthCache($request->adminInfo['admin_id']);
// 当前访问路径
$accessUri = strtolower($request->controller() . '/' . $request->action());
$coreAliases = CoreAccountPermissionPolicy::aliases($accessUri);
if ($coreAliases !== null) {
if ($coreAliases === [] || array_intersect($coreAliases, $this->formatUrl($adminAuthCache->getAdminUri())) !== []) {
return $next($request);
}
return JsonService::fail('权限不足,无法访问或操作');
}
// 面诊回放与文字共用读取权限;未登记该接口时也不能走历史放行分支。
if ($accessUri === 'tcm.diagnosis/getcallrecords') {
$uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
@@ -118,7 +127,7 @@ class AuthMiddleware
// 全部路由
$allUri = $this->formatUrl($adminAuthCache->getAllUri());
// 判断该当前访问的uri是否存在,不存在无需验证
if (!in_array($accessUri, $allUri, true)
&& !PharmacyUploadPermissionAlias::allows($accessUri, $allUri)
@@ -127,59 +136,59 @@ class AuthMiddleware
&& in_array('tcm.diagnosis/aiassistant', $allUri, true))) {
return $next($request);
}
// 当前管理员拥有的路由权限
$AdminUris = $adminAuthCache->getAdminUri() ?? [];
$AdminUris = $this->formatUrl($AdminUris);
if (in_array($accessUri, $AdminUris) || $this->matchPermissionAlias($accessUri, $AdminUris)) {
return $next($request);
}
return JsonService::fail('权限不足,无法访问或操作');
}
/**
* @notes 格式化URL
* @param array $data
* @return array|string[]
* @author 段誉
* @date 2022/7/7 15:39
*/
public function formatUrl(array $data)
{
return array_map(function ($item) {
return strtolower(Str::camel($item));
}, $data);
}
/**
* 企业微信客服桌面软件(7)/ 手机控制台(9)的令牌会交给客服后台,由客服后台服务器
* 代查患者、订单;服务器出口 IP 与员工电脑登录时绑定的 IP 不同,按原规则每次都会被判为
* 「ip地址发生变化」。DesktopController::session 出于同一原因已免登录。
* 这里只在「RPA 终端令牌 + 请求来自 .env [WECOM_RPA] SERVER_IPS 配置的客服后台服务器 IP」
* 时跳过 IP 绑定,网页端/APP 等其他终端令牌仍保留 IP 保护;未配置时与原逻辑完全一致。
* 只跳过 IP 校验,后续菜单权限校验照常执行,客服后台拿到的仍只是该账号角色允许的数据。
*
* @param mixed $configured 逗号/空白分隔的 IP 列表,逐个精确匹配(IPv4/IPv6 字面量)
*/
public static function isTrustedRpaServerRequest(array $adminInfo, string $ip, $configured): bool
{
if (!in_array((int) ($adminInfo['terminal'] ?? 0), AdminTerminalEnum::wecomRpaTerminals(), true)) {
return false;
}
if ($ip === '' || !is_string($configured)) {
return false;
}
$trustedIps = preg_split('/[\s,]+/', trim($configured), -1, PREG_SPLIT_NO_EMPTY) ?: [];
return in_array($ip, $trustedIps, true);
}
/**
* 日常记录权限域:前端统一收口到 tcm.diagnosis/dailyRecord,
* 但待办/跟踪备注接口仍保留历史路由名,故在鉴权层做精确别名映射。
*/
// 当前管理员拥有的路由权限
$AdminUris = $adminAuthCache->getAdminUri() ?? [];
$AdminUris = $this->formatUrl($AdminUris);
if (in_array($accessUri, $AdminUris) || $this->matchPermissionAlias($accessUri, $AdminUris)) {
return $next($request);
}
return JsonService::fail('权限不足,无法访问或操作');
}
/**
* @notes 格式化URL
* @param array $data
* @return array|string[]
* @author 段誉
* @date 2022/7/7 15:39
*/
public function formatUrl(array $data)
{
return array_map(function ($item) {
return strtolower(Str::camel($item));
}, $data);
}
/**
* 企业微信客服桌面软件(7)/ 手机控制台(9)的令牌会交给客服后台,由客服后台服务器
* 代查患者、订单;服务器出口 IP 与员工电脑登录时绑定的 IP 不同,按原规则每次都会被判为
* 「ip地址发生变化」。DesktopController::session 出于同一原因已免登录。
* 这里只在「RPA 终端令牌 + 请求来自 .env [WECOM_RPA] SERVER_IPS 配置的客服后台服务器 IP」
* 时跳过 IP 绑定,网页端/APP 等其他终端令牌仍保留 IP 保护;未配置时与原逻辑完全一致。
* 只跳过 IP 校验,后续菜单权限校验照常执行,客服后台拿到的仍只是该账号角色允许的数据。
*
* @param mixed $configured 逗号/空白分隔的 IP 列表,逐个精确匹配(IPv4/IPv6 字面量)
*/
public static function isTrustedRpaServerRequest(array $adminInfo, string $ip, $configured): bool
{
if (!in_array((int) ($adminInfo['terminal'] ?? 0), AdminTerminalEnum::wecomRpaTerminals(), true)) {
return false;
}
if ($ip === '' || !is_string($configured)) {
return false;
}
$trustedIps = preg_split('/[\s,]+/', trim($configured), -1, PREG_SPLIT_NO_EMPTY) ?: [];
return in_array($ip, $trustedIps, true);
}
/**
* 日常记录权限域:前端统一收口到 tcm.diagnosis/dailyRecord,
* 但待办/跟踪备注接口仍保留历史路由名,故在鉴权层做精确别名映射。
*/
private function matchPermissionAlias(string $accessUri, array $adminUris): bool
{
// AI 助手流式端点与旧 blocking 端点共享同一权限;别名同时用于
@@ -190,7 +199,7 @@ class AuthMiddleware
}
if (PharmacyUploadPermissionAlias::isControlled($accessUri)) {
return PharmacyUploadPermissionAlias::allows($accessUri, $adminUris);
return PharmacyUploadPermissionAlias::allows($accessUri, $adminUris);
}
$prescriptionWriteAliases = [
@@ -210,55 +219,55 @@ class AuthMiddleware
&& count(array_intersect($prescriptionWriteAliases[$accessUri], $adminUris)) > 0) {
return true;
}
if (in_array('tcm.diagnosis/dailyrecord', $adminUris, true)
&& in_array($accessUri, [
'tcm.diagnosistodo/lists',
'tcm.diagnosistodo/add',
'tcm.diagnosistodo/cancel',
'tcm.diagnosis/trackingnotes',
'tcm.diagnosis/addtrackingnote',
], true)) {
return true;
}
// 导出与列表共用 PrescriptionOrderLists 数据域;角色漏勾「导出订单」子权限时仍返回 权限不足
if ($accessUri === 'tcm.prescriptionorder/export'
&& in_array('tcm.prescriptionorder/lists', $adminUris, true)) {
return true;
}
// 京东物流接口刷新:与「物流轨迹」同一数据域,复用 logisticsTrace 权限
if ($accessUri === 'tcm.prescriptionorder/logisticsjdupdate'
&& in_array('tcm.prescriptionorder/logisticstrace', $adminUris, true)) {
return true;
}
// 挂号列表批量改渠道:与单条编辑同一数据域,复用 doctor.appointment/edit
if ($accessUri === 'doctor.appointment/batcheditchannel'
&& in_array('doctor.appointment/edit', $adminUris, true)) {
return true;
}
// 自录转化统计:自媒体来源下拉,复用总览或账户消耗列表权限
if ($accessUri === 'stats.selfinput/mediasourceoptions') {
$selfInputAliases = [
'stats.selfinput/overview',
'stats.self_input/overview',
'stats.personalaccountcost/lists',
'stats.personal_account_cost/lists',
];
if (count(array_intersect($selfInputAliases, $AdminUris)) > 0) {
return true;
}
}
// 处方库列表:消费者开方页/处方库页导入共用,复用开方或处方库菜单权限
if ($accessUri === 'tcm.prescriptionlibrary/lists'
&& $this->matchPrescriptionLibraryListsPermission($adminUris)) {
return true;
}
if (in_array('tcm.diagnosis/dailyrecord', $adminUris, true)
&& in_array($accessUri, [
'tcm.diagnosistodo/lists',
'tcm.diagnosistodo/add',
'tcm.diagnosistodo/cancel',
'tcm.diagnosis/trackingnotes',
'tcm.diagnosis/addtrackingnote',
], true)) {
return true;
}
// 导出与列表共用 PrescriptionOrderLists 数据域;角色漏勾「导出订单」子权限时仍返回 权限不足
if ($accessUri === 'tcm.prescriptionorder/export'
&& in_array('tcm.prescriptionorder/lists', $adminUris, true)) {
return true;
}
// 京东物流接口刷新:与「物流轨迹」同一数据域,复用 logisticsTrace 权限
if ($accessUri === 'tcm.prescriptionorder/logisticsjdupdate'
&& in_array('tcm.prescriptionorder/logisticstrace', $adminUris, true)) {
return true;
}
// 挂号列表批量改渠道:与单条编辑同一数据域,复用 doctor.appointment/edit
if ($accessUri === 'doctor.appointment/batcheditchannel'
&& in_array('doctor.appointment/edit', $adminUris, true)) {
return true;
}
// 自录转化统计:自媒体来源下拉,复用总览或账户消耗列表权限
if ($accessUri === 'stats.selfinput/mediasourceoptions') {
$selfInputAliases = [
'stats.selfinput/overview',
'stats.self_input/overview',
'stats.personalaccountcost/lists',
'stats.personal_account_cost/lists',
];
if (count(array_intersect($selfInputAliases, $AdminUris)) > 0) {
return true;
}
}
// 处方库列表:消费者开方页/处方库页导入共用,复用开方或处方库菜单权限
if ($accessUri === 'tcm.prescriptionlibrary/lists'
&& $this->matchPrescriptionLibraryListsPermission($adminUris)) {
return true;
}
return false;
}
@@ -299,47 +308,47 @@ class AuthMiddleware
'firstvisit.wecompromotion/deletelink',
], true);
}
/**
* 处方库 lists:与开方、处方库维护菜单权限互通(避免开方页「从处方库导入」403)
*/
private function matchPrescriptionLibraryListsPermission(array $adminUris): bool
{
$aliases = [
'tcm.prescriptionlibrary/lists',
'tcm.prescription/lists',
'tcm.prescription/add',
'tcm.prescription/edit',
'tcm.prescription/detail',
'cf.prescription/lists',
'cf.prescription/add',
'cf.prescription/edit',
'cf.prescription/read',
'cf.prescription/del',
'cf.prescription/audit',
'wcf.prescription/lists',
'wcf.prescription/read',
'wcf.prescription/add',
'wcf.prescription/edit',
'wcf.prescription/delete',
];
return count(array_intersect($aliases, $adminUris)) > 0;
}
/**
* 面诊进度专用:auth.admin/lists、doctor.appointment/lists + progress_board=1,不校验菜单权限
*/
private function isFaceProgressBoardPublicLists($request): bool
{
if ((int) $request->param('progress_board', 0) !== 1) {
return false;
}
if (strtolower((string) $request->action()) !== 'lists') {
return false;
}
$c = strtolower((string) $request->controller());
return in_array($c, ['auth.admin', 'doctor.appointment'], true);
}
}
/**
* 处方库 lists:与开方、处方库维护菜单权限互通(避免开方页「从处方库导入」403)
*/
private function matchPrescriptionLibraryListsPermission(array $adminUris): bool
{
$aliases = [
'tcm.prescriptionlibrary/lists',
'tcm.prescription/lists',
'tcm.prescription/add',
'tcm.prescription/edit',
'tcm.prescription/detail',
'cf.prescription/lists',
'cf.prescription/add',
'cf.prescription/edit',
'cf.prescription/read',
'cf.prescription/del',
'cf.prescription/audit',
'wcf.prescription/lists',
'wcf.prescription/read',
'wcf.prescription/add',
'wcf.prescription/edit',
'wcf.prescription/delete',
];
return count(array_intersect($aliases, $adminUris)) > 0;
}
/**
* 面诊进度专用:auth.admin/lists、doctor.appointment/lists + progress_board=1,不校验菜单权限
*/
private function isFaceProgressBoardPublicLists($request): bool
{
if ((int) $request->param('progress_board', 0) !== 1) {
return false;
}
if (strtolower((string) $request->action()) !== 'lists') {
return false;
}
$c = strtolower((string) $request->controller());
return in_array($c, ['auth.admin', 'doctor.appointment'], true);
}
}
+19 -9
View File
@@ -47,14 +47,8 @@ class OperationLog
$params = $request->param();
//过滤密码参数
if (isset($params['password'])) {
$params['password'] = "******";
}
//过滤密钥参数
if(isset($params['app_secret'])){
$params['app_secret'] = "******";
}
// 集团账号编辑也会提交确认密码;请求和响应都不能留下可复用凭据。
$this->redactCredentials($params);
//导出数据操作进行记录
if (isset($params['export']) && $params['export'] == 2) {
@@ -81,6 +75,7 @@ class OperationLog
$maxBytes = 62000;
$decoded = json_decode($content, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
$this->redactCredentials($decoded);
$this->stripLargeLogFields($decoded);
$content = json_encode($decoded, JSON_UNESCAPED_UNICODE);
}
@@ -91,6 +86,21 @@ class OperationLog
return $content;
}
private function redactCredentials(array &$data): void
{
$secretKeys = ['password', 'password_confirm', 'old_password', 'new_password',
'password_hash', 'token', 'source_token', 'access_token', 'refresh_token',
'id_token', 'authorization', 'ticket', 'code_verifier', 'app_secret', 'client_secret'];
foreach ($data as $key => &$value) {
if (is_string($key) && in_array(strtolower($key), $secretKeys, true)) {
$value = '******';
} elseif (is_array($value)) {
$this->redactCredentials($value);
}
}
unset($value);
}
private function stripLargeLogFields(array &$data): void
{
foreach ($data as $key => &$value) {
@@ -106,4 +116,4 @@ class OperationLog
}
}
}
}
}
+41 -29
View File
@@ -21,6 +21,9 @@ 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;
/**
* 登录逻辑
@@ -118,8 +121,17 @@ class LoginLogic extends BaseLogic
*/
public function login($params)
{
return Db::transaction(static function () use ($params) {
$time = time();
$admin = Admin::where('account', '=', $params['account'])->find();
$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;
@@ -145,6 +157,7 @@ class LoginLogic extends BaseLogic
]);
return $row;
});
}
/**
@@ -213,6 +226,11 @@ class LoginLogic extends BaseLogic
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;
@@ -234,6 +252,7 @@ class LoginLogic extends BaseLogic
// 企微扫码登录即已绑定 userid
'need_bind_work_wechat' => false,
];
});
}
/**
@@ -321,38 +340,31 @@ class LoginLogic extends BaseLogic
public function changeFirstPassword($token, $password)
{
try {
// 通过 token 获取管理员信息
$adminSession = \app\common\model\auth\AdminSession::where('token', '=', $token)
->where('expire_time', '>', time())
->find();
if (!$adminSession) {
self::setError('登录已过期,请重新登录');
return false;
if (!is_string($password) || strlen($password) < 6 || strlen($password) > 32 || str_contains($password, "\0")) {
throw new \RuntimeException('密码长度须在6-32字节');
}
$admin = Admin::find($adminSession->admin_id);
if (!$admin) {
self::setError('管理员不存在');
return false;
}
// 使用系统的密码加密方式
$passwordSalt = Config::get('project.unique_identification');
$encryptedPassword = create_password($password, $passwordSalt);
// 更新密码和 is_paw 标记
$admin->password = $encryptedPassword;
$admin->is_paw = 1;
$admin->save();
// 使当前 token 过期,要求重新登录
AdminTokenService::expireToken($token);
$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;
}
}
}
}
+45 -38
View File
@@ -16,6 +16,7 @@ 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;
@@ -24,6 +25,7 @@ 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;
@@ -120,6 +122,14 @@ class AdminLogic extends BaseLogic
{
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'])) {
@@ -163,17 +173,16 @@ class AdminLogic extends BaseLogic
$data['password'] = create_password($params['password'], $passwordSalt);
}
// 禁用或更换角色后.设置token过期
// 改密、停用、角色及部门变化均影响原医院和SSO终端;先写事务内撤销记录。
$roleId = AdminRole::where('admin_id', $params['id'])->column('role_id');
$submittedRoleIds = self::normalizeRoleIds($params['role_id'] ?? []);
$editRole = self::roleIdsChanged($roleId, $submittedRoleIds);
if ($params['disable'] == 1 || $editRole) {
$tokenArr = AdminSession::where('admin_id', $params['id'])->select()->toArray();
foreach ($tokenArr as $token) {
self::expireToken($token['token']);
}
}
$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);
@@ -192,13 +201,7 @@ class AdminLogic extends BaseLogic
self::importDoctorAccountToIm($params['id'], $params['name']);
Db::commit();
// 必须在角色关联提交后删除该账号的 URI 权限缓存,避免并发请求重新写入旧权限。
try {
(new AdminAuthCache($params['id']))->clearAuthCache();
} catch (\Throwable $cacheError) {
// 数据已经提交,缓存清理失败不能把成功的编辑伪装成失败;记录后等待缓存自然过期。
Log::warning('管理员角色权限缓存清理失败:admin_id=' . $params['id'] . ',error=' . $cacheError->getMessage());
}
AdminAccessSyncService::clearCommitted([(int) $params['id']], $tokens);
return true;
} catch (\Exception $e) {
Db::rollback();
@@ -219,25 +222,20 @@ class AdminLogic extends BaseLogic
{
Db::startTrans();
try {
$admin = Admin::findOrEmpty($params['id']);
$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']);
//设置token过期
$tokenArr = AdminSession::where('admin_id', $params['id'])->select()->toArray();
foreach ($tokenArr as $token) {
self::expireToken($token['token']);
}
(new AdminAuthCache($params['id']))->clearAuthCache();
// 删除旧的关联信息
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();
@@ -259,20 +257,14 @@ class AdminLogic extends BaseLogic
*/
public static function expireToken($token): bool
{
$adminSession = AdminSession::where('token', '=', $token)
->with('admin')
->find();
if (empty($adminSession)) {
return false;
}
$time = time();
$adminSession->expire_time = $time;
$adminSession->update_time = $time;
$adminSession->save();
return (new AdminTokenCache())->deleteAdminInfo($token);
$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;
}
@@ -355,7 +347,22 @@ class AdminLogic extends BaseLogic
$data['password'] = create_password($params['password'], $passwordSalt);
}
return Admin::update($data);
$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;
}
+6 -8
View File
@@ -19,6 +19,7 @@ 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;
/**
@@ -64,20 +65,15 @@ class AuthLogic
$where[] = ['is_disable', '=', 0];
$where[] = ['perms', '<>', ''];
$where[] = ['id', 'in', ActiveMenuPermissions::ids()];
$roleAuth = SystemMenu::distinct(true)
->where('id', 'in', $menuId)
->where($where)
->column('perms');
$allAuth = SystemMenu::distinct(true)
->where($where)
->column('perms');
$hasAllAuth = array_diff($allAuth, $roleAuth);
$permissions = empty($hasAllAuth) ? ['*'] : $roleAuth;
return self::appendSharedPromotionPermission($permissions, (int) ($admin['id'] ?? 0));
// 普通账号只返回当前有效原权限;全部剩余权限恰好获授也不能推导为可覆盖停用菜单的通配符。
return self::appendSharedPromotionPermission($roleAuth, (int) ($admin['id'] ?? 0));
}
@@ -99,6 +95,7 @@ class AuthLogic
['perms', '<>', ''],
['id', 'in', array_unique($menuId)],
])
->whereIn('id', ActiveMenuPermissions::ids())
->column('perms');
return self::appendSharedPromotionPermission($permissions, $adminId);
@@ -109,6 +106,7 @@ class AuthLogic
{
if (in_array('*', $permissions, true)
|| in_array(QywxPromotionOperatorAccess::PAGE_PERMISSION, $permissions, true)
|| !ActiveMenuPermissions::has(QywxPromotionOperatorAccess::PAGE_PERMISSION)
|| !QywxPromotionOperatorAccess::hasSharedPagePermission($adminId)) {
return $permissions;
}
+29 -9
View File
@@ -21,6 +21,9 @@ 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;
/**
@@ -49,6 +52,7 @@ class MenuLogic extends BaseLogic
$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');
@@ -92,12 +96,14 @@ class MenuLogic extends BaseLogic
$result = [];
foreach ($pageIds as $pageId) {
$chain = [];
$seen = [];
$currentId = $pageId;
while ($currentId > 0) {
if (!isset($byId[$currentId])) {
if (isset($seen[$currentId]) || !isset($byId[$currentId])) {
$chain = [];
break;
}
$seen[$currentId] = true;
$chain[] = $currentId;
$currentId = (int) ($byId[$currentId]['pid'] ?? 0);
}
@@ -144,7 +150,7 @@ class MenuLogic extends BaseLogic
*/
public static function edit(array $params)
{
return SystemMenu::update([
return self::mutate((int) $params['id'], static fn () => SystemMenu::update([
'id' => $params['id'],
'pid' => $params['pid'],
'type' => $params['type'],
@@ -159,7 +165,7 @@ class MenuLogic extends BaseLogic
'is_cache' => $params['is_cache'],
'is_show' => $params['is_show'],
'is_disable' => $params['is_disable'],
]);
]));
}
@@ -184,10 +190,10 @@ class MenuLogic extends BaseLogic
*/
public static function delete($params)
{
// 删除菜单
SystemMenu::destroy($params['id']);
// 删除角色-菜单表中 与该菜单关联的记录
SystemRoleMenu::where(['menu_id' => $params['id']])->delete();
self::mutate((int) $params['id'], static function () use ($params): void {
SystemMenu::destroy($params['id']);
SystemRoleMenu::where(['menu_id' => $params['id']])->delete();
});
}
@@ -200,10 +206,24 @@ class MenuLogic extends BaseLogic
*/
public static function updateStatus(array $params)
{
return SystemMenu::update([
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;
}
+34 -9
View File
@@ -21,6 +21,8 @@ use app\common\{
model\auth\SystemRoleMenu
};
use think\facade\Db;
use app\adminapi\service\AdminAccessSyncService;
use app\common\model\auth\AdminRole;
/**
@@ -40,6 +42,7 @@ class RoleLogic extends BaseLogic
*/
public static function add(array $params): bool
{
self::$returnData = [];
Db::startTrans();
try {
$menuId = !empty($params['menu_id']) ? $params['menu_id'] : [];
@@ -61,9 +64,11 @@ class RoleLogic extends BaseLogic
'menu_id' => $item,
];
}
(new SystemRoleMenu)->insertAll($data);
if ($data !== []) { (new SystemRoleMenu)->insertAll($data); }
Db::commit();
// 返回本次已提交的角色编号,集团跨目录授权不能按名称或其他表的自增编号猜测。
self::$returnData = ['id' => (int) $role['id']];
return true;
} catch (\Exception $e) {
Db::rollback();
@@ -84,6 +89,10 @@ class RoleLogic extends BaseLogic
{
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 = [
@@ -98,7 +107,8 @@ class RoleLogic extends BaseLogic
}
SystemRole::update($roleRow);
if (!empty($menuId)) {
// 显式空数组表示收回全部权限;省略字段表示保留原授权。
if (array_key_exists('menu_id', $params)) {
SystemRoleMenu::where(['role_id' => $params['id']])->delete();
$data = [];
foreach ($menuId as $item) {
@@ -107,12 +117,13 @@ class RoleLogic extends BaseLogic
'menu_id' => $item,
];
}
(new SystemRoleMenu)->insertAll($data);
if ($data !== []) {
(new SystemRoleMenu)->insertAll($data);
}
}
(new AdminAuthCache())->deleteTag();
Db::commit();
AdminAccessSyncService::clearCommitted($adminIds, $tokens);
return true;
} catch (\Exception $e) {
Db::rollback();
@@ -130,9 +141,23 @@ class RoleLogic extends BaseLogic
*/
public static function delete(int $id)
{
SystemRole::destroy(['id' => $id]);
(new AdminAuthCache())->deleteTag();
return true;
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;
}
}
@@ -186,4 +211,4 @@ class RoleLogic extends BaseLogic
}
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use app\common\cache\AdminAuthCache;
use app\common\cache\AdminTokenCache;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\auth\AdminSession;
use app\common\model\auth\SystemMenu;
use app\common\model\auth\SystemRoleMenu;
use think\facade\Log;
/** 原账号变更:事务内锁账号并撤销会话,提交成功后才清缓存。 */
final class AdminAccessSyncService
{
public static function ids(array $ids): array
{
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn (int $id): bool => $id > 0)));
sort($ids, SORT_NUMERIC);
return $ids;
}
public static function roleAdminIds(array $roleIds): array
{
return $roleIds === [] ? [] : self::ids(AdminRole::whereIn('role_id', $roleIds)->column('admin_id'));
}
/** 菜单父节点变更也影响只获授子节点的账号。 */
public static function menuAdminIds(int $menuId): array
{
$menuIds = [$menuId];
$rows = SystemMenu::field('id,pid')->select()->toArray();
do {
$count = count($menuIds);
foreach ($rows as $row) {
if (in_array((int) $row['pid'], $menuIds, true)) { $menuIds[] = (int) $row['id']; }
}
$menuIds = self::ids($menuIds);
} while (count($menuIds) !== $count);
return self::roleAdminIds(self::ids(SystemRoleMenu::whereIn('menu_id', $menuIds)->column('role_id')));
}
/** 调用者必须已开启事务;与密码登录、SSO签发和续期共用账号锁。 */
public static function revoke(array $adminIds): array
{
$adminIds = self::ids($adminIds);
if ($adminIds === []) { return []; }
Admin::whereIn('id', $adminIds)->order('id')->lock(true)->field('id')->select();
$tokens = AdminSession::whereIn('admin_id', $adminIds)->column('token');
AdminSession::whereIn('admin_id', $adminIds)->update(['expire_time' => time() - 1, 'update_time' => time()]);
return $tokens;
}
public static function clearCommitted(array $adminIds, array $tokens): void
{
// DB是有效性的准绳;缓存故障不能把已提交操作伪报失败,也不能恢复旧会话。
foreach ($tokens as $token) {
try { (new AdminTokenCache())->deleteAdminInfo((string) $token); }
catch (\Throwable $error) { Log::warning('账号变更已提交,会话缓存清理失败'); }
}
foreach (self::ids($adminIds) as $adminId) {
try { (new AdminAuthCache($adminId))->clearAuthCache(); }
catch (\Throwable $error) { Log::warning('账号变更已提交,权限缓存清理失败:admin_id=' . $adminId); }
}
}
}
@@ -17,7 +17,9 @@ namespace app\adminapi\service;
use app\common\cache\AdminTokenCache;
use app\common\model\auth\AdminSession;
use app\common\model\auth\Admin;
use think\facade\Config;
use think\facade\Db;
/**
* 管理员token
@@ -40,6 +42,9 @@ class AdminTokenService
*/
public static function setToken($adminId, $terminal, $multipointLogin = 1)
{
return Db::transaction(static function () use ($adminId, $terminal, $multipointLogin) {
$admin = Admin::where('id', $adminId)->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) { return false; }
$time = time();
$adminSession = AdminSession::where([['admin_id', '=', $adminId], ['terminal', '=', $terminal]])->find();
@@ -70,6 +75,7 @@ class AdminTokenService
}
return $adminTokenCache->setAdminInfo($adminSession->token);
});
}
/**
@@ -84,8 +90,13 @@ class AdminTokenService
*/
public static function overtimeToken($token)
{
return Db::transaction(static function () use ($token) {
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) { return false; }
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) { return false; }
$time = time();
$adminSession = AdminSession::where('token', '=', $token)->findOrEmpty();
$adminSession = AdminSession::where('token', '=', $token)->where('expire_time', '>', $time)->lock(true)->findOrEmpty();
if ($adminSession->isEmpty()) {
return false;
}
@@ -93,7 +104,16 @@ class AdminTokenService
$adminSession->expire_time = $time + Config::get('project.admin_token.expire_duration');
$adminSession->update_time = $time;
$adminSession->save();
return (new AdminTokenCache())->setAdminInfo($adminSession->token);
$cache = new AdminTokenCache();
$cached = $cache->get('token_admin_' . $token);
if ($cached) {
// 续期不得把登录IP改绑到当前请求IP。
$cached['expire_time'] = $adminSession->expire_time;
$cache->set('token_admin_' . $token, $cached, new \DateTime(date('Y-m-d H:i:s', $adminSession->expire_time)));
return $cached;
}
return $cache->setAdminInfo($adminSession->token);
});
}
/**
@@ -108,25 +128,16 @@ class AdminTokenService
*/
public static function expireToken($token)
{
$adminSession = AdminSession::where('token', '=', $token)
->with('admin')
->findOrEmpty();
if ($adminSession->isEmpty()) {
return false;
}
//当支持多处登录的时候,服务端不注销
if ($adminSession->admin->multipoint_login === 1) {
return false;
}
$time = time();
$adminSession->expire_time = $time;
$adminSession->update_time = $time;
$adminSession->save();
return (new AdminTokenCache())->deleteAdminInfo($token);
$changed = Db::transaction(static function () use ($token): bool {
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) { return false; }
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
// 保留原退出登录在多点登录模式下不注销的语义。
if (!$admin->isEmpty() && (int) $admin['multipoint_login'] === 1) { return false; }
return AdminSession::where('token', $token)->update(['expire_time' => time() - 1, 'update_time' => time()]) > 0;
});
if ($changed) { (new AdminTokenCache())->deleteAdminInfo($token); }
return $changed;
}
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
/** 核心账号管理接口独立于可编辑菜单的URI登记,删除菜单也不能变成免鉴权接口。 */
final class CoreAccountPermissionPolicy
{
/** null=非核心接口;[]为已登录账号自己的资料或导航接口;其余为允许的原权限别名。 */
public static function aliases(string $uri): ?array
{
[$controller, $action] = array_pad(explode('/', strtolower($uri), 2), 2, '');
if (!in_array($controller, ['auth.admin', 'auth.role', 'auth.menu', 'dept.dept'], true)) { return null; }
if (($controller === 'auth.admin' && in_array($action, ['myself', 'editself', 'bindworkwechat', 'unbindworkwechat'], true))
|| ($controller === 'auth.menu' && $action === 'route')) { return []; }
$aliases = [$uri];
if ($action === 'detail') { $aliases = array_merge($aliases, [$controller . '/lists', $controller . '/edit']); }
if ($action === 'all' || ($controller === 'dept.dept' && $action === 'leaderdept')) {
$aliases = array_merge($aliases, [$controller . '/lists', $controller . '/add', $controller . '/edit']);
if (in_array($controller, ['auth.role', 'dept.dept'], true)) {
$aliases = array_merge($aliases, ['auth.admin/add', 'auth.admin/edit']);
}
if ($controller === 'auth.menu') { $aliases = array_merge($aliases, ['auth.role/add', 'auth.role/edit']); }
}
if ($controller === 'auth.menu' && $action === 'updatestatus') { $aliases[] = 'auth.menu/edit'; }
return $aliases;
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use app\adminapi\logic\LoginLogic;
use app\adminapi\http\middleware\AuthMiddleware;
use app\common\cache\AdminTokenCache;
use app\common\enum\AdminTerminalEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminSession;
use app\common\service\JsonService;
use think\facade\Config;
use think\facade\Db;
/** The hospital trusts its own live source session, never a caller-provided identity. */
final class IdentityHospitalSsoService
{
private IdentityHospitalSsoTicketStore $tickets;
public function __construct(?IdentityHospitalSsoTicketStore $tickets = null)
{
$this->tickets = $tickets ?? new IdentityHospitalSsoTicketStore(app()->getRuntimePath() . 'identity-hospital-sso');
}
public function issue(string $sourceToken, array $data): array
{
self::only($data, ['code_challenge', 'code_challenge_method']);
if (($data['code_challenge_method'] ?? null) !== 'S256'
|| !is_string($data['code_challenge'] ?? null)
|| !preg_match('/^[A-Za-z0-9_-]{43}$/D', $data['code_challenge'])) {
JsonService::throw('登录验证参数不合法');
}
if ($sourceToken === '' || strlen($sourceToken) > 512 || preg_match('/[\x00-\x20\x7f]/', $sourceToken)) {
JsonService::throw('请先登录集团工作台', [], -1);
}
return Db::transaction(function () use ($sourceToken, $data): array {
$candidate = AdminSession::where('token', $sourceToken)->findOrEmpty();
[$admin, $session] = self::lockSource($candidate, hash('sha256', $sourceToken));
self::ready($admin);
// 交接源仍受原 IP 绑定保护;目标 exchange 才允许来自医院浏览器的不同 IP。
$info = (new AdminTokenCache())->getAdminInfo($sourceToken);
$ip = request()->ip();
if (!$info || (int) ($info['admin_id'] ?? 0) !== (int) $admin['id']
|| (($info['login_ip'] ?? '') !== $ip && !AuthMiddleware::isTrustedRpaServerRequest(
(array) $info, $ip, env('wecom_rpa.server_ips', '')))) {
JsonService::throw('ip地址发生变化,请重新登录', [], -1);
}
return ['ticket' => $this->tickets->issue((int) $session['id'], hash('sha256', $sourceToken), $data['code_challenge'])];
});
}
public function exchange(array $data): array
{
self::only($data, ['ticket', 'code_verifier']);
if (!is_string($data['ticket'] ?? null) || !is_string($data['code_verifier'] ?? null)) {
JsonService::throw('登录验证参数不合法');
}
try { $record = $this->tickets->consume($data['ticket'], $data['code_verifier']); }
catch (\RuntimeException $error) { JsonService::throw('登录票据已失效,请重新从集团工作台进入'); }
$result = Db::transaction(static function () use ($record): array {
$candidate = AdminSession::where('id', $record['session_id'])->findOrEmpty();
[$admin] = self::lockSource($candidate, $record['token_hash']);
self::ready($admin);
$now = time();
$target = AdminSession::where('admin_id', (int) $admin['id'])
->where('terminal', AdminTerminalEnum::GROUP_HOSPITAL)->lock(true)->findOrEmpty();
$oldToken = $target->isEmpty() ? '' : (string) $target['token'];
$token = $oldToken;
if ($target->isEmpty() || (int) $target['expire_time'] <= $now || (int) $admin['multipoint_login'] === 0) {
// 原 admin_session.token 为 varchar(32),保持128位随机性且不修改业务表。
$token = bin2hex(random_bytes(16));
}
$values = ['token' => $token, 'expire_time' => $now + (int) Config::get('project.admin_token.expire_duration'),
'update_time' => $now];
if ($target->isEmpty()) {
AdminSession::create($values + ['admin_id' => (int) $admin['id'], 'terminal' => AdminTerminalEnum::GROUP_HOSPITAL]);
} else { $target->save($values); }
// Persist the independent session under the same account/source locks. Publish its cache only after commit.
return ['token' => $token, 'old_token' => $oldToken, 'name' => (string) $admin['name'],
'avatar' => (string) $admin['avatar']];
});
$cache = new AdminTokenCache();
if ($result['old_token'] !== '' && $result['old_token'] !== $result['token']) {
$cache->deleteAdminInfo($result['old_token']);
}
// This executes in the real hospital browser request, retaining the original per-token IP protection.
$info = $cache->setAdminInfo($result['token']);
if (!$info) { JsonService::throw('登录已失效,请重新进入', [], -1); }
return ['name' => $result['name'], 'avatar' => $result['avatar'], 'role_name' => $info['role_name'],
'token' => $result['token'], 'is_paw' => 1, 'need_bind_work_wechat' => false];
}
private static function lockSource(AdminSession $candidate, string $tokenHash): array
{
if ($candidate->isEmpty()) { JsonService::throw('集团登录已失效,请重新登录', [], -1); }
// Same order as IdentitySessionService and account changes: account row, then the exact session row.
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !empty($admin->getData('delete_time'))) {
JsonService::throw('集团登录已失效,请重新登录', [], -1);
}
$session = AdminSession::where('id', (int) $candidate['id'])->where('admin_id', (int) $admin['id'])
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
if ($session->isEmpty() || !hash_equals($tokenHash, hash('sha256', (string) $session['token']))
|| (int) $session['terminal'] === AdminTerminalEnum::GROUP_HOSPITAL) {
JsonService::throw('集团登录已失效,请重新登录', [], -1);
}
return [$admin, $session];
}
private static function ready(Admin $admin): void
{
if ((int) $admin['is_paw'] !== 1) { JsonService::throw('请先在集团工作台完成首次密码修改'); }
if (LoginLogic::adminMustBindWorkWechat(['root' => (int) $admin['root'],
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? '')])) {
JsonService::throw('请先在原后台完成企业微信绑定', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
}
}
private static function only(array $data, array $allowed): void
{
if (array_diff(array_keys($data), $allowed) !== []) { JsonService::throw('请求包含不支持的字段'); }
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use RuntimeException;
/** Private single-server handoff tickets. Neither raw source tokens nor passwords are persisted. */
final class IdentityHospitalSsoTicketStore
{
private \Closure $clock;
public function __construct(private string $directory, ?callable $clock = null)
{
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
}
public function issue(int $sessionId, string $tokenHash, string $challenge): string
{
return $this->locked(function () use ($sessionId, $tokenHash, $challenge): string {
foreach (array_slice(glob($this->directory . '/*.json') ?: [], 0, 200) as $path) {
$old = $this->read($path);
if ($old !== null && (int) ($old['expires'] ?? 0) <= ($this->clock)()) { unlink($path); }
}
$ticket = bin2hex(random_bytes(32));
$record = ['session_id' => $sessionId, 'token_hash' => $tokenHash, 'challenge' => $challenge,
'expires' => ($this->clock)() + 30];
$path = $this->path($ticket);
$file = fopen($path, 'x+b');
if ($file === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
try {
chmod($path, 0600);
$json = json_encode($record, JSON_THROW_ON_ERROR);
if (fwrite($file, $json) !== strlen($json) || !fflush($file)) {
throw new RuntimeException('Hospital handoff storage unavailable');
}
} catch (\Throwable $error) {
fclose($file);
unlink($path);
throw $error;
}
fclose($file);
return $ticket;
});
}
public function consume(string $ticket, string $verifier): array
{
if (!preg_match('/^[a-f0-9]{64}$/D', $ticket)
|| !preg_match('/^[A-Za-z0-9._~-]{43,128}$/D', $verifier)) {
throw new RuntimeException('Hospital handoff invalid');
}
return $this->locked(function () use ($ticket, $verifier): array {
$path = $this->path($ticket);
$record = $this->read($path);
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
if ($record === null || !is_int($record['expires'] ?? null) || $record['expires'] <= ($this->clock)()
|| !is_int($record['session_id'] ?? null) || $record['session_id'] < 1
|| !is_string($record['token_hash'] ?? null) || !preg_match('/^[a-f0-9]{64}$/D', $record['token_hash'])
|| !is_string($record['challenge'] ?? null) || !hash_equals($record['challenge'], $challenge)) {
throw new RuntimeException('Hospital handoff invalid');
}
// The global private lock covers open/read/delete, so simultaneous exchanges cannot replay.
if (!unlink($path)) { throw new RuntimeException('Hospital handoff consumption failed'); }
return $record;
});
}
private function read(string $path): ?array
{
if (!is_file($path) || is_link($path) || filesize($path) > 4096) { return null; }
try { $record = json_decode((string) file_get_contents($path), true, 8, JSON_THROW_ON_ERROR); }
catch (\JsonException $error) { return null; }
return is_array($record) ? $record : null;
}
private function path(string $ticket): string
{
return $this->directory . '/' . hash('sha256', $ticket) . '.json';
}
private function locked(callable $operation): mixed
{
if (is_link($this->directory) || (!is_dir($this->directory)
&& !mkdir($this->directory, 0700, true) && !is_dir($this->directory))) {
throw new RuntimeException('Hospital handoff storage unavailable');
}
chmod($this->directory, 0700);
$path = $this->directory . '/.lock';
if (is_link($path)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
$lock = fopen($path, 'c+b');
if ($lock === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
chmod($path, 0600);
try {
if (!flock($lock, LOCK_EX)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
return $operation();
} finally { flock($lock, LOCK_UN); fclose($lock); }
}
}
@@ -0,0 +1,160 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use app\adminapi\logic\LoginLogic;
use app\common\cache\AdminTokenCache;
use app\common\enum\AdminTerminalEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminSession;
use app\common\service\JsonService;
use think\facade\Config;
use think\facade\Db;
/** 共用原账号密码与原会话,不信任桥接层提供的用户编号或root标记。 */
final class IdentitySessionService
{
/** 验证外部子系统的凭据,不创建、复用、刷新或注销原系统会话。 */
public static function verify(array $params): array
{
if (array_diff(array_keys($params), ['account', 'password']) !== []) {
JsonService::throw('请求包含不支持的字段');
}
$account = $params['account'] ?? null;
$password = $params['password'] ?? null;
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")) {
JsonService::throw('登录参数不合法');
}
return Db::transaction(static function () use ($account, $password): array {
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
$salt = (string) Config::get('project.unique_identification');
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
}
return ['id' => (int) $admin['id'], 'account' => (string) $admin['account'],
'name' => (string) ($admin['name'] ?? ''), 'disable' => 0,
'requires_password_change' => (int) ($admin['is_paw'] ?? 1) === 0,
'requires_wecom_binding' => LoginLogic::adminMustBindWorkWechat([
'root' => (int) ($admin['root'] ?? 0),
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
])];
});
}
/** 与个人改密共用账号行锁,绝不信任事务前验证器的密码快照或调试免密结果。 */
public static function login(array $params): array
{
if (array_diff(array_keys($params), ['account', 'password', 'terminal']) !== []) {
JsonService::throw('请求包含不支持的字段');
}
$account = $params['account'] ?? null;
$password = $params['password'] ?? null;
$terminal = $params['terminal'] ?? null;
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")
|| (!is_int($terminal) && !is_string($terminal))
|| !in_array((string) $terminal, ['1', '2', '7', '9', (string) AdminTerminalEnum::GROUP_IDENTITY], true)) {
JsonService::throw('登录参数不合法');
}
return Db::transaction(static function () use ($account, $password, $params): array {
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
$salt = (string) Config::get('project.unique_identification');
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
}
// 原登录的资料更新和会话签发均在该账号锁释放前完成。
return (new LoginLogic())->login($params);
});
}
public static function changePassword(string $token, array $params): void
{
if (array_diff(array_keys($params), ['old_password', 'password', 'password_confirm']) !== []) {
JsonService::throw('请求包含不支持的字段');
}
$password = $params['password'] ?? null;
if (!is_string($password) || strlen($password) < 6 || strlen($password) > 32 || str_contains($password, "\0")) {
JsonService::throw('密码长度须在6-32字节');
}
if ($password !== ($params['password_confirm'] ?? null)) {
JsonService::throw('两次输入的密码不一致');
}
$tokens = Db::transaction(static function () use ($token, $params, $password): array {
[$admin] = self::lockContext($token);
$firstPassword = (int) ($admin['is_paw'] ?? 1) === 0;
if (!$firstPassword && LoginLogic::adminMustBindWorkWechat([
'root' => (int) $admin['root'], 'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
])) {
JsonService::throw('请先在原后台绑定企业微信', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
}
$salt = (string) Config::get('project.unique_identification');
if (!$firstPassword) {
$oldPassword = $params['old_password'] ?? null;
if (!is_string($oldPassword) || strlen($oldPassword) > 1024
|| !hash_equals((string) $admin['password'], create_password($oldPassword, $salt))) {
JsonService::throw('当前密码错误');
}
}
$id = (int) $admin['id'];
Admin::where('id', $id)->update([
'password' => create_password($password, $salt), 'is_paw' => 1, 'update_time' => time(),
]);
return self::expire($id, null);
});
self::clearTokens($tokens);
}
public static function logout(string $token, bool $all = false): void
{
$tokens = Db::transaction(static function () use ($token, $all): array {
[$admin] = self::lockContext($token);
return self::expire((int) $admin['id'], $all ? null : $token);
});
self::clearTokens($tokens);
}
/** 先锁账号再锁会话,避免两个会话同时改密时互相等待。 */
private static function lockContext(string $token): array
{
if ($token === '' || strlen($token) > 512 || preg_match('/[\x00-\x20\x7f]/', $token)) {
JsonService::throw('请先登录', [], -1);
}
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) {
JsonService::throw('登录已失效,请重新登录', [], -1);
}
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) {
JsonService::throw('登录已失效,请重新登录', [], -1);
}
$session = AdminSession::where('admin_id', (int) $admin['id'])->where('token', $token)
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
if ($session->isEmpty()) {
JsonService::throw('登录已失效,请重新登录', [], -1);
}
return [$admin, $session];
}
private static function expire(int $adminId, ?string $token): array
{
$query = static function () use ($adminId, $token) {
$builder = AdminSession::where('admin_id', $adminId);
return $token === null ? $builder : $builder->where('token', $token);
};
$tokens = $query()->column('token');
$query()->update(['expire_time' => time() - 1, 'update_time' => time()]);
return $tokens;
}
private static function clearTokens(array $tokens): void
{
$cache = new AdminTokenCache();
foreach ($tokens as $token) {
$cache->deleteAdminInfo((string) $token);
}
}
}
+18 -1
View File
@@ -56,10 +56,27 @@ class LoginValidate extends BaseValidate
* @date 2021/7/2 14:00
*/
public function password($password, $other, $data)
{
return $this->checkCredentialPassword($password, $data, true);
}
/** 子系统直接验密保留原限流,始终忽略本地调试免密开关。 */
public function strictPassword($password, $other, $data)
{
return $this->checkCredentialPassword($password, $data, false);
}
public function sceneVerify()
{
return $this->only(['account', 'password'])->remove('password', 'password')
->append('password', 'strictPassword');
}
private function checkCredentialPassword($password, array $data, bool $allowDebug)
{
// 本地调试:免密登录开关。须同时满足 APP_DEBUG=1 + LOCAL_DEBUG.LOGIN_SKIP_PASSWORD=true,
// 任一不满足都走原始密码校验。每次免密登录都会记一条 warning 日志,便于发现误开。
if (self::isLocalDebugLoginBypassEnabled()) {
if ($allowDebug && self::isLocalDebugLoginBypassEnabled()) {
$adminInfo = Admin::where('account', '=', $data['account'])
->field(['password,disable'])
->findOrEmpty();