gengx
This commit is contained in:
@@ -50,6 +50,8 @@ class AuthMiddleware
|
||||
|
||||
// 登录 IP 绑定;客服后台服务器代查患者/订单的例外见 isTrustedRpaServerRequest
|
||||
if ($request->adminInfo['login_ip'] != request()->ip()
|
||||
// BCR 原生应用会在 Wi-Fi/移动网络间切换;仅跳过固定 IP,继续下面全部权限检查。
|
||||
&& (int) ($request->adminInfo['terminal'] ?? 0) !== AdminTerminalEnum::BCR
|
||||
&& !self::isTrustedRpaServerRequest(
|
||||
(array) $request->adminInfo,
|
||||
request()->ip(),
|
||||
|
||||
@@ -1,106 +1,109 @@
|
||||
<?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\common\cache\AdminTokenCache;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\common\service\JsonService;
|
||||
use think\facade\Config;
|
||||
|
||||
/**
|
||||
* 登录中间件
|
||||
* Class LoginMiddleware
|
||||
* @package app\adminapi\http\middleware
|
||||
*/
|
||||
class LoginMiddleware
|
||||
{
|
||||
/**
|
||||
* @notes 登录验证
|
||||
* @param $request
|
||||
* @param \Closure $next
|
||||
* @return mixed|\think\response\Json
|
||||
* @author 令狐冲
|
||||
* @date 2021/7/1 17:33
|
||||
*/
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
$token = $request->header('token');
|
||||
//判断接口是否免登录
|
||||
$isNotNeedLogin = $request->controllerObject->isNotNeedLogin();
|
||||
|
||||
//不直接判断$isNotNeedLogin结果,使不需要登录的接口通过,为了兼容某些接口可以登录或不登录访问
|
||||
if (empty($token) && !$isNotNeedLogin) {
|
||||
//没有token并且该地址需要登录才能访问
|
||||
return JsonService::fail('请求参数缺token', [], 0, 0);
|
||||
}
|
||||
|
||||
$adminInfo = (new AdminTokenCache())->getAdminInfo($token);
|
||||
if (empty($adminInfo) && !$isNotNeedLogin) {
|
||||
//token过期无效并且该地址需要登录才能访问
|
||||
return JsonService::fail('登录超时,请重新登录', [], -1);
|
||||
}
|
||||
|
||||
//token临近过期,自动续期
|
||||
if ($adminInfo) {
|
||||
//获取临近过期自动续期时长
|
||||
$beExpireDuration = Config::get('project.admin_token.be_expire_duration');
|
||||
//token续期
|
||||
if (time() > ($adminInfo['expire_time'] - $beExpireDuration)) {
|
||||
$result = AdminTokenService::overtimeToken($token);
|
||||
//续期失败(数据表被删除导致)
|
||||
if (empty($result)) {
|
||||
return JsonService::fail('登录过期', [], -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//给request赋值,用于控制器
|
||||
$request->adminInfo = $adminInfo;
|
||||
$request->adminId = $adminInfo['admin_id'] ?? 0;
|
||||
|
||||
// 非 root 须绑定企微:免登录接口不拦截(如 getConfig),避免 init 死循环
|
||||
if (!empty($adminInfo) && LoginLogic::adminMustBindWorkWechat($adminInfo) && !$isNotNeedLogin) {
|
||||
if (!self::isWorkWechatBindExemptAction($request)) {
|
||||
return JsonService::fail(
|
||||
'请先绑定企业微信后再使用系统',
|
||||
[],
|
||||
LoginLogic::CODE_NEED_BIND_WORK_WECHAT,
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private static function isWorkWechatBindExemptAction($request): bool
|
||||
{
|
||||
if (LoginLogic::isWorkWechatBindExemptActionName((string) $request->action())) {
|
||||
return true;
|
||||
}
|
||||
// 与 AuthMiddleware 一致:未绑企微时仍允许打开面诊进度所需只读列表
|
||||
if ((int) $request->param('progress_board', 0) === 1 && strtolower((string) $request->action()) === 'lists') {
|
||||
$c = strtolower((string) $request->controller());
|
||||
|
||||
return in_array($c, ['auth.admin', 'doctor.appointment'], true);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
<?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\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\common\service\JsonService;
|
||||
|
||||
/**
|
||||
* 登录中间件
|
||||
* Class LoginMiddleware
|
||||
* @package app\adminapi\http\middleware
|
||||
*/
|
||||
class LoginMiddleware
|
||||
{
|
||||
/**
|
||||
* @notes 登录验证
|
||||
* @param $request
|
||||
* @param \Closure $next
|
||||
* @return mixed|\think\response\Json
|
||||
* @author 令狐冲
|
||||
* @date 2021/7/1 17:33
|
||||
*/
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
$token = $request->header('token');
|
||||
//判断接口是否免登录
|
||||
$isNotNeedLogin = $request->controllerObject->isNotNeedLogin();
|
||||
|
||||
//不直接判断$isNotNeedLogin结果,使不需要登录的接口通过,为了兼容某些接口可以登录或不登录访问
|
||||
if (empty($token) && !$isNotNeedLogin) {
|
||||
//没有token并且该地址需要登录才能访问
|
||||
return JsonService::fail('请求参数缺token', [], 0, 0);
|
||||
}
|
||||
|
||||
$adminInfo = (new AdminTokenCache())->getAdminInfo($token);
|
||||
if (empty($adminInfo) && !$isNotNeedLogin) {
|
||||
//token过期无效并且该地址需要登录才能访问
|
||||
return JsonService::fail('登录超时,请重新登录', [], -1);
|
||||
}
|
||||
|
||||
//token临近过期,自动续期
|
||||
if ($adminInfo) {
|
||||
//获取临近过期自动续期时长
|
||||
$beExpireDuration = AdminTokenService::renewalWindow($adminInfo['terminal'] ?? 0);
|
||||
//token续期
|
||||
if (time() > ($adminInfo['expire_time'] - $beExpireDuration)) {
|
||||
$result = AdminTokenService::overtimeToken($token);
|
||||
//续期失败(数据表被删除导致)
|
||||
if (empty($result)) {
|
||||
return JsonService::fail('登录过期', [], -1);
|
||||
}
|
||||
if ((int) ($adminInfo['terminal'] ?? 0) === AdminTerminalEnum::BCR) {
|
||||
$adminInfo = $result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//给request赋值,用于控制器
|
||||
$request->adminInfo = $adminInfo;
|
||||
$request->adminId = $adminInfo['admin_id'] ?? 0;
|
||||
|
||||
// 非 root 须绑定企微:免登录接口不拦截(如 getConfig),避免 init 死循环
|
||||
if (!empty($adminInfo) && LoginLogic::adminMustBindWorkWechat($adminInfo) && !$isNotNeedLogin) {
|
||||
if (!self::isWorkWechatBindExemptAction($request)) {
|
||||
return JsonService::fail(
|
||||
'请先绑定企业微信后再使用系统',
|
||||
[],
|
||||
LoginLogic::CODE_NEED_BIND_WORK_WECHAT,
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private static function isWorkWechatBindExemptAction($request): bool
|
||||
{
|
||||
if (LoginLogic::isWorkWechatBindExemptActionName((string) $request->action())) {
|
||||
return true;
|
||||
}
|
||||
// 与 AuthMiddleware 一致:未绑企微时仍允许打开面诊进度所需只读列表
|
||||
if ((int) $request->param('progress_board', 0) === 1 && strtolower((string) $request->action()) === 'lists') {
|
||||
$c = strtolower((string) $request->controller());
|
||||
|
||||
return in_array($c, ['auth.admin', 'doctor.appointment'], true);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,358 +1,362 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* 登录逻辑
|
||||
* 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)
|
||||
{
|
||||
$time = time();
|
||||
$admin = Admin::where('account', '=', $params['account'])->find();
|
||||
|
||||
//用户表登录信息更新
|
||||
$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;
|
||||
}
|
||||
|
||||
// 更新登录信息
|
||||
$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 {
|
||||
// 通过 token 获取管理员信息
|
||||
$adminSession = \app\common\model\auth\AdminSession::where('token', '=', $token)
|
||||
->where('expire_time', '>', time())
|
||||
->find();
|
||||
|
||||
if (!$adminSession) {
|
||||
self::setError('登录已过期,请重新登录');
|
||||
return false;
|
||||
}
|
||||
|
||||
$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);
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
self::setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* 登录逻辑
|
||||
* 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)
|
||||
{
|
||||
$time = time();
|
||||
$admin = Admin::where('account', '=', $params['account'])->find();
|
||||
|
||||
//用户表登录信息更新
|
||||
$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;
|
||||
}
|
||||
|
||||
// 更新登录信息
|
||||
$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 {
|
||||
// 通过 token 获取管理员信息
|
||||
$adminSession = \app\common\model\auth\AdminSession::where('token', '=', $token)
|
||||
->where('expire_time', '>', time())
|
||||
->find();
|
||||
|
||||
if (!$adminSession) {
|
||||
self::setError('登录已过期,请重新登录');
|
||||
return false;
|
||||
}
|
||||
|
||||
$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;
|
||||
Db::transaction(static function () use ($admin) {
|
||||
$admin->save();
|
||||
AdminTokenService::revokeBcrSessions((int) $admin->id);
|
||||
});
|
||||
|
||||
// 使当前 token 过期,要求重新登录
|
||||
AdminTokenService::expireToken($token);
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
self::setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ namespace app\adminapi\logic\auth;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\service\DoctorWebConsultationPolicy;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\common\cache\AdminAuthCache;
|
||||
use app\common\enum\YesNoEnum;
|
||||
use app\common\logic\BaseLogic;
|
||||
@@ -176,6 +177,9 @@ class AdminLogic extends BaseLogic
|
||||
}
|
||||
|
||||
Admin::update($data);
|
||||
if (isset($data['password'])) {
|
||||
AdminTokenService::revokeBcrSessions((int) $params['id']);
|
||||
}
|
||||
|
||||
// 删除旧的关联信息
|
||||
AdminRole::delByUserId($params['id']);
|
||||
@@ -355,7 +359,13 @@ class AdminLogic extends BaseLogic
|
||||
$data['password'] = create_password($params['password'], $passwordSalt);
|
||||
}
|
||||
|
||||
return Admin::update($data);
|
||||
return Db::transaction(static function () use ($data) {
|
||||
$admin = Admin::update($data);
|
||||
if (isset($data['password'])) {
|
||||
AdminTokenService::revokeBcrSessions((int) $data['id']);
|
||||
}
|
||||
return $admin;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,132 +1,177 @@
|
||||
<?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 think\facade\Config;
|
||||
|
||||
/**
|
||||
* 管理员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)
|
||||
{
|
||||
$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)
|
||||
{
|
||||
$time = time();
|
||||
$adminSession = AdminSession::where('token', '=', $token)->findOrEmpty();
|
||||
if ($adminSession->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
//延长token过期时间
|
||||
$adminSession->expire_time = $time + Config::get('project.admin_token.expire_duration');
|
||||
$adminSession->update_time = $time;
|
||||
$adminSession->save();
|
||||
return (new AdminTokenCache())->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)
|
||||
{
|
||||
$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);
|
||||
}
|
||||
|
||||
}
|
||||
<?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\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use think\facade\Config;
|
||||
|
||||
/**
|
||||
* 管理员token
|
||||
* Class AdminTokenService
|
||||
* @package app\adminapi\service
|
||||
*/
|
||||
class AdminTokenService
|
||||
{
|
||||
public static function expireDuration($terminal): int
|
||||
{
|
||||
return (int) Config::get((int) $terminal === AdminTerminalEnum::BCR
|
||||
? 'project.admin_token.bcr_expire_duration' : 'project.admin_token.expire_duration',
|
||||
(int) $terminal === AdminTerminalEnum::BCR ? 86400 * 180 : 3600 * 8);
|
||||
}
|
||||
|
||||
public static function renewalWindow($terminal): int
|
||||
{
|
||||
return (int) Config::get((int) $terminal === AdminTerminalEnum::BCR
|
||||
? 'project.admin_token.bcr_be_expire_duration' : 'project.admin_token.be_expire_duration',
|
||||
(int) $terminal === AdminTerminalEnum::BCR ? 86400 * 150 : 3600);
|
||||
}
|
||||
|
||||
/** 与改密同一事务调用;只撤销 BCR,会话有效性由 DB 决定,旧缓存不能续活。 */
|
||||
public static function revokeBcrSessions(int $adminId): void
|
||||
{
|
||||
AdminSession::where('admin_id', $adminId)->where('terminal', AdminTerminalEnum::BCR)
|
||||
->update(['expire_time' => time() - 1, 'update_time' => time()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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)
|
||||
{
|
||||
$time = time();
|
||||
$adminSession = AdminSession::where([['admin_id', '=', $adminId], ['terminal', '=', $terminal]])->find();
|
||||
|
||||
//获取token延长过期的时间
|
||||
$expireTime = $time + self::expireDuration($terminal);
|
||||
$adminTokenCache = new AdminTokenCache();
|
||||
|
||||
//token处理
|
||||
if ($adminSession) {
|
||||
if ($adminSession->expire_time < $time || $multipointLogin === 0
|
||||
|| ((int) $terminal === AdminTerminalEnum::BCR && (int) $adminSession->expire_time === $time)) {
|
||||
//清空缓存
|
||||
$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)
|
||||
{
|
||||
$time = time();
|
||||
$adminSession = AdminSession::where('token', '=', $token)->findOrEmpty();
|
||||
if ($adminSession->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if ((int) $adminSession->terminal === AdminTerminalEnum::BCR) {
|
||||
$previousExpiry = (int) $adminSession->expire_time;
|
||||
if ($previousExpiry <= $time || !Admin::where('id', $adminSession->admin_id)
|
||||
->where('disable', 0)->field('id')->find()) {
|
||||
return false;
|
||||
}
|
||||
// 比较读取时的有效期和 token;注销、改密或同端重登后不能把旧会话续活。
|
||||
// CAS 失败也可能是另一请求先续期,交给 DB 有效性校验区分。
|
||||
AdminSession::where('id', $adminSession->id)->where('token', $token)
|
||||
->where('expire_time', $previousExpiry)->where('expire_time', '>', $time)
|
||||
->update(['expire_time' => $time + self::expireDuration($adminSession->terminal), 'update_time' => $time]);
|
||||
return (new AdminTokenCache())->setAdminInfo($token);
|
||||
}
|
||||
//延长token过期时间
|
||||
$adminSession->expire_time = $time + self::expireDuration($adminSession->terminal);
|
||||
$adminSession->update_time = $time;
|
||||
$adminSession->save();
|
||||
return (new AdminTokenCache())->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)
|
||||
{
|
||||
$adminSession = AdminSession::where('token', '=', $token)
|
||||
->with('admin')
|
||||
->findOrEmpty();
|
||||
|
||||
if ($adminSession->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 其他终端保留多处登录的原有退出语义。
|
||||
// BCR 必须注销;同账号多台 BCR 复用一个 token 时,这些设备会一起失效。
|
||||
if ((int) $adminSession->terminal !== AdminTerminalEnum::BCR
|
||||
&& $adminSession->admin->multipoint_login === 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$time = time();
|
||||
if ((int) $adminSession->terminal === AdminTerminalEnum::BCR) {
|
||||
// 只注销调用者持有的 token,不能误伤并发重登后替换到同一行的新 token。
|
||||
AdminSession::where('id', $adminSession->id)->where('token', $token)
|
||||
->update(['expire_time' => $time - 1, 'update_time' => $time]);
|
||||
} else {
|
||||
$adminSession->expire_time = $time;
|
||||
$adminSession->update_time = $time;
|
||||
$adminSession->save();
|
||||
}
|
||||
|
||||
return (new AdminTokenCache())->deleteAdminInfo($token);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ class LoginValidate extends BaseValidate
|
||||
{
|
||||
protected $rule = [
|
||||
'terminal' => 'require|in:' . AdminTerminalEnum::PC . ',' . AdminTerminalEnum::MOBILE
|
||||
. ',' . AdminTerminalEnum::WECOM_RPA . ',' . AdminTerminalEnum::WECOM_RPA_MOBILE,
|
||||
. ',' . AdminTerminalEnum::WECOM_RPA . ',' . AdminTerminalEnum::WECOM_RPA_MOBILE
|
||||
. ',' . AdminTerminalEnum::BCR,
|
||||
'account' => 'require',
|
||||
'password' => 'require|password',
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user