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,124 @@
<?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\controller\auth;
use app\adminapi\{
logic\auth\RoleLogic,
lists\auth\RoleLists,
validate\auth\RoleValidate,
controller\BaseAdminController
};
/**
* 角色控制器
* Class RoleController
* @package app\adminapi\controller\auth
*/
class RoleController extends BaseAdminController
{
/**
* @notes 查看角色列表
* @return \think\response\Json
* @author 段誉
* @date 2021/12/29 11:49
*/
public function lists()
{
return $this->dataLists(new RoleLists());
}
/**
* @notes 添加权限
* @return \think\response\Json
* @author 段誉
* @date 2021/12/29 11:49
*/
public function add()
{
$params = (new RoleValidate())->post()->goCheck('add');
$res = RoleLogic::add($params);
if (true === $res) {
return $this->success('添加成功', RoleLogic::getReturnData(), 1, 1);
}
return $this->fail(RoleLogic::getError());
}
/**
* @notes 编辑角色
* @return \think\response\Json
* @author 段誉
* @date 2021/12/29 14:18
*/
public function edit()
{
$params = (new RoleValidate())->post()->goCheck('edit');
$res = RoleLogic::edit($params);
if (true === $res) {
return $this->success('编辑成功', [], 1, 1);
}
return $this->fail(RoleLogic::getError());
}
/**
* @notes 删除角色
* @return \think\response\Json
* @author 段誉
* @date 2021/12/29 14:18
*/
public function delete()
{
$params = (new RoleValidate())->post()->goCheck('del');
RoleLogic::delete($params['id']);
return $this->success('删除成功', [], 1, 1);
}
/**
* @notes 查看角色详情
* @return \think\response\Json
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2021/12/29 14:18
*/
public function detail()
{
$params = (new RoleValidate())->goCheck('detail');
$detail = RoleLogic::detail($params['id']);
return $this->data($detail);
}
/**
* @notes 获取角色数据
* @return \think\response\Json
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/10/13 10:39
*/
public function all()
{
$result = RoleLogic::getAllData();
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('已退出登录');
}
}
@@ -0,0 +1,354 @@
<?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']);
// 当前访问路径
$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() ?? []);
if (in_array('tcm.diagnosis/huifang', $uris, true)
|| in_array('tcm.diagnosis/getcallrecords', $uris, true)) {
return $next($request); // 控制器还会校验当前诊单的数据域。
}
return JsonService::fail('权限不足,无法查看面诊记录');
}
// This group must never use the legacy unregistered-route bypass.
if (str_starts_with($accessUri, 'tcm.followupaudio/')) {
$allowed = ['capabilities', 'uploadsession', 'uploadchunk', 'uploadcomplete',
'create', 'lists', 'detail', 'savedraft', 'apply', 'retry', 'audio', 'delete', 'reextract'];
$action = substr($accessUri, strlen('tcm.followupaudio/'));
$uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
if (in_array($action, $allowed, true) && in_array('tcm.diagnosis/edit', $uris, true)
&& in_array('tcm.diagnosis/followupaudio', $uris, true)
&& ($action !== 'delete' || in_array('tcm.followupaudio/delete', $uris, true))) {
return $next($request); // The service also checks the current patient scope and daily permissions.
}
return JsonService::fail('权限不足,无法访问或操作');
}
// 获客助手的子接口多数不是独立菜单权限。整组动作统一绑定页面权限,
// 共享操作人的动态页面权限也必须先经过这一层,再由业务层校验具体方案。
if (str_starts_with($accessUri, 'firstvisit.wecompromotion/')) {
$adminUris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
if ($this->isKnownWecomPromotionAction($accessUri)
&& in_array(strtolower(QywxPromotionOperatorAccess::PAGE_PERMISSION), $adminUris, true)) {
return $next($request);
}
return JsonService::fail('权限不足,无法访问或操作');
}
// 全部路由
$allUri = $this->formatUrl($adminAuthCache->getAllUri());
// 判断该当前访问的uri是否存在,不存在无需验证
if (!in_array($accessUri, $allUri, true)
&& !PharmacyUploadPermissionAlias::allows($accessUri, $allUri)
&& !$this->isCriticalPrescriptionWrite($accessUri)
&& !(in_array($accessUri, ['tcm.diagnosis/aiassistantstream', 'tcm.diagnosis/cancelaiassistant'], true)
&& 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,
* 但待办/跟踪备注接口仍保留历史路由名,故在鉴权层做精确别名映射。
*/
private function matchPermissionAlias(string $accessUri, array $adminUris): bool
{
// AI 助手流式端点与旧 blocking 端点共享同一权限;别名同时用于
// allUri 判定和当前管理员权限判定,确保在 SSE headers 前完成鉴权。
if (in_array($accessUri, ['tcm.diagnosis/aiassistantstream', 'tcm.diagnosis/cancelaiassistant'], true)
&& in_array('tcm.diagnosis/aiassistant', $adminUris, true)) {
return true;
}
if (PharmacyUploadPermissionAlias::isControlled($accessUri)) {
return PharmacyUploadPermissionAlias::allows($accessUri, $adminUris);
}
$prescriptionWriteAliases = [
'tcm.prescription/add' => [
'tcm.prescription/add', 'cf.prescription/add',
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
],
'tcm.prescription/edit' => [
'tcm.prescription/edit', 'cf.prescription/edit',
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
],
'tcm.prescription/delete' => ['tcm.prescription/delete', 'cf.prescription/del'],
'tcm.prescription/void' => ['tcm.prescription/void', 'cf.prescription/del', 'cf.prescription/audit'],
'tcm.prescription/audit' => ['tcm.prescription/audit', 'cf.prescription/audit'],
];
if (isset($prescriptionWriteAliases[$accessUri])
&& 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;
}
return false;
}
private function isCriticalPrescriptionWrite(string $accessUri): bool
{
return in_array($accessUri, [
'tcm.prescription/add',
'tcm.prescription/edit',
'tcm.prescription/delete',
'tcm.prescription/void',
'tcm.prescription/audit',
], true);
}
private function isKnownWecomPromotionAction(string $accessUri): bool
{
return in_array($accessUri, [
'firstvisit.wecompromotion/tagoptions',
'firstvisit.wecompromotion/createtag',
'firstvisit.wecompromotion/uploadwelcomemedia',
'firstvisit.wecompromotion/overview',
'firstvisit.wecompromotion/savepool',
'firstvisit.wecompromotion/batchupdatepools',
'firstvisit.wecompromotion/savewidget',
'firstvisit.wecompromotion/batchsetoperators',
'firstvisit.wecompromotion/deletepool',
'firstvisit.wecompromotion/savelink',
'firstvisit.wecompromotion/savemember',
'firstvisit.wecompromotion/togglemember',
'firstvisit.wecompromotion/syncmemberrange',
'firstvisit.wecompromotion/checkapipermission',
'firstvisit.wecompromotion/syncremotelinks',
'firstvisit.wecompromotion/remotelinkdetail',
'firstvisit.wecompromotion/deleteremotelink',
'firstvisit.wecompromotion/synccustomers',
'firstvisit.wecompromotion/customerstatistics',
'firstvisit.wecompromotion/togglelink',
'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);
}
}
@@ -0,0 +1,119 @@
<?php
namespace app\adminapi\listener;
use ReflectionClass;
use think\Exception;
class OperationLog
{
/**
* @notes 管理员操作日志
* @param $response
* @return bool|void
* @throws \ReflectionException
* @author 段誉
* @date 2022/4/8 17:09
*/
public function handle($response)
{
$request = request();
//需要登录的接口,无效访问时不记录
if (!$request->controllerObject->isNotNeedLogin() && empty($request->adminInfo)) {
return;
}
//不记录日志操作
if (strtolower(str_replace('.', '\\', $request->controller())) === 'setting\system\log') {
return;
}
//获取操作注解
$notes = '';
try {
$re = new ReflectionClass($request->controllerObject);
$doc = $re->getMethod($request->action())->getDocComment();
if (empty($doc)) {
throw new Exception('请给控制器方法注释');
}
preg_match('/\s(\w+)/u', $re->getMethod($request->action())->getDocComment(), $values);
$notes = $values[0];
} catch (Exception $e) {
$notes = $notes ?: '无法获取操作名称,请给控制器方法注释';
}
$params = $request->param();
// 集团账号编辑也会提交确认密码;请求和响应都不能留下可复用凭据。
$this->redactCredentials($params);
//导出数据操作进行记录
if (isset($params['export']) && $params['export'] == 2) {
$notes .= '-数据导出';
}
//记录日志
$systemLog = new \app\common\model\OperationLog();
$systemLog->admin_id = $request->adminInfo['admin_id'] ?? 0;
$systemLog->admin_name = $request->adminInfo['name'] ?? '';
$systemLog->action = $notes;
$systemLog->account = $request->adminInfo['account'] ?? '';
$systemLog->url = $request->url(true);
$systemLog->type = $request->isGet() ? 'GET' : 'POST';
$systemLog->params = json_encode($params, true);
$systemLog->ip = $request->ip();
$systemLog->result = $this->shortenOperationLogResult((string) $response->getContent());
return $systemLog->save();
}
/** MySQL TEXT 上限约 64KB,列表接口常含 base64 签名导致超长 */
private function shortenOperationLogResult(string $content): string
{
$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);
}
if (strlen($content) > $maxBytes) {
$content = substr($content, 0, $maxBytes) . '...[truncated]';
}
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) {
if (is_array($value)) {
$this->stripLargeLogFields($value);
continue;
}
if (! is_string($key)) {
continue;
}
if (in_array($key, ['doctor_signature', 'tongue_image'], true) && is_string($value) && strlen($value) > 200) {
$value = '[omitted:' . strlen($value) . ' bytes]';
}
}
}
}
@@ -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();
}
}
@@ -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); }
}
}
}
@@ -0,0 +1,143 @@
<?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\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
* Class AdminTokenService
* @package app\adminapi\service
*/
class AdminTokenService
{
/**
* @notes 设置或更新管理员token
* @param $adminId //管理员id
* @param $terminal //多终端名称
* @param $multipointLogin //是否支持多处登录
* @return false|mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/2 20:25
*/
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();
//获取token延长过期的时间
$expireTime = $time + Config::get('project.admin_token.expire_duration');
$adminTokenCache = new AdminTokenCache();
//token处理
if ($adminSession) {
if ($adminSession->expire_time < $time || $multipointLogin === 0) {
//清空缓存
$adminTokenCache->deleteAdminInfo($adminSession->token);
//如果token过期或账号设置不支持多处登录,更新token
$adminSession->token = create_token($adminId);
}
$adminSession->expire_time = $expireTime;
$adminSession->update_time = $time;
$adminSession->save();
} else {
//找不到在该终端的token记录,创建token记录
$adminSession = AdminSession::create([
'admin_id' => $adminId,
'terminal' => $terminal,
'token' => create_token($adminId),
'expire_time' => $expireTime
]);
}
return $adminTokenCache->setAdminInfo($adminSession->token);
});
}
/**
* @notes 延长token过期时间
* @param $token
* @return array|false|mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/5 14:25
*/
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)->where('expire_time', '>', $time)->lock(true)->findOrEmpty();
if ($adminSession->isEmpty()) {
return false;
}
//延长token过期时间
$adminSession->expire_time = $time + Config::get('project.admin_token.expire_duration');
$adminSession->update_time = $time;
$adminSession->save();
$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);
});
}
/**
* @notes 设置token为过期
* @param $token
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/5 14:31
*/
public static function expireToken($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);
}
}
}
@@ -0,0 +1,164 @@
<?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\validate;
use app\common\enum\AdminTerminalEnum;
use app\common\model\auth\Admin;
use app\common\cache\AdminAccountSafeCache;
use app\common\service\ConfigService;
use app\common\validate\BaseValidate;
use think\facade\Config;
use think\facade\Log;
/**
* 登录验证
* Class LoginValidate
* @package app\adminapi\validate
*/
class LoginValidate extends BaseValidate
{
protected $rule = [
'terminal' => 'require|in:' . AdminTerminalEnum::PC . ',' . AdminTerminalEnum::MOBILE
. ',' . AdminTerminalEnum::WECOM_RPA . ',' . AdminTerminalEnum::WECOM_RPA_MOBILE,
'account' => 'require',
'password' => 'require|password',
];
protected $message = [
'account.require' => '请输入账号',
'password.require' => '请输入密码'
];
/**
* @notes @notes 密码验证
* @param $password
* @param $other
* @param $data
* @return bool|string
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @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 ($allowDebug && self::isLocalDebugLoginBypassEnabled()) {
$adminInfo = Admin::where('account', '=', $data['account'])
->field(['password,disable'])
->findOrEmpty();
if ($adminInfo->isEmpty()) {
return '账号不存在';
}
if ((int)($adminInfo['disable'] ?? 0) === 1) {
return '账号已禁用';
}
Log::warning(sprintf(
'[LOCAL_DEBUG] login bypass password: account=%s, ip=%s',
(string)($data['account'] ?? ''),
(string)request()->ip()
));
return true;
}
// 登录限制
$config = [
'login_restrictions' => ConfigService::get('admin_login', 'login_restrictions'),
'password_error_times' => ConfigService::get('admin_login', 'password_error_times'),
'limit_login_time' => ConfigService::get('admin_login', 'limit_login_time'),
];
$adminAccountSafeCache = new AdminAccountSafeCache();
if ($config['login_restrictions'] == 1) {
$adminAccountSafeCache->count = $config['password_error_times'];
$adminAccountSafeCache->minute = $config['limit_login_time'];
}
//后台账号安全机制,连续输错后锁定,防止账号密码暴力破解
if ($config['login_restrictions'] == 1 && !$adminAccountSafeCache->isSafe()) {
return '密码连续' . $adminAccountSafeCache->count . '次输入错误,请' . $adminAccountSafeCache->minute . '分钟后重试';
}
$adminInfo = Admin::where('account', '=', $data['account'])
->field(['password,disable'])
->findOrEmpty();
if ($adminInfo->isEmpty()) {
return '账号不存在';
}
if ($adminInfo['disable'] === 1) {
return '账号已禁用';
}
if (empty($adminInfo['password'])) {
$adminAccountSafeCache->record();
return '账号不存在';
}
$passwordSalt = Config::get('project.unique_identification');
if ($adminInfo['password'] !== create_password($password, $passwordSalt)) {
$adminAccountSafeCache->record();
return '密码错误';
}
$adminAccountSafeCache->relieve();
return true;
}
/**
* 是否启用"本地调试免密登录"。
*
* 双重闸门:
* 1. APP_DEBUG 必须为 true(即应用本身处于调试模式)
* 2. LOCAL_DEBUG.LOGIN_SKIP_PASSWORD 必须显式为 true / 1 / yes / on
*
* 任何一条不满足都返回 false,强制走原始密码校验。这样即使误把
* LOGIN_SKIP_PASSWORD 配进生产,只要 APP_DEBUG=0 仍然安全。
*/
private static function isLocalDebugLoginBypassEnabled(): bool
{
$appDebug = strtolower((string) env('app_debug', '0'));
if (!in_array($appDebug, ['1', 'true', 'yes', 'on'], true)) {
return false;
}
$flag = strtolower((string) env('local_debug.login_skip_password', ''));
return in_array($flag, ['1', 'true', 'yes', 'on'], true);
}
}