mirror of
https://gitee.com/niucloud-team/niucloud.git
synced 2026-11-18 17:30:33 +00:00
2.1.0补丁修复
This commit is contained in:
parent
ce45bf0975
commit
6b7b4f0743
264
niucloud/niucloud/app/service/admin/auth/AuthService.php
Normal file
264
niucloud/niucloud/app/service/admin/auth/AuthService.php
Normal file
@ -0,0 +1,264 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | Niucloud-admin 企业快速开发的saas管理平台
|
||||
// +----------------------------------------------------------------------
|
||||
// | 官方网址:https://www.niucloud.com
|
||||
// +----------------------------------------------------------------------
|
||||
// | niucloud团队 版权所有 开源版本可自由商用
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: Niucloud Team
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace app\service\admin\auth;
|
||||
|
||||
use app\dict\site\SiteDict;
|
||||
use app\dict\sys\AppTypeDict;
|
||||
use app\model\sys\SysUserRole;
|
||||
use app\Request;
|
||||
use app\service\admin\site\SiteUserService;
|
||||
use app\service\admin\sys\MenuService;
|
||||
use app\service\admin\sys\RoleService;
|
||||
use app\service\admin\user\UserRoleService;
|
||||
use app\service\admin\user\UserService;
|
||||
use app\service\core\niucloud\CoreAuthService;
|
||||
use app\service\core\site\CoreSiteService;
|
||||
use core\base\BaseAdminService;
|
||||
use core\exception\AuthException;
|
||||
use core\exception\CommonException;
|
||||
use Exception;
|
||||
use think\facade\Cache;
|
||||
|
||||
/**
|
||||
* 用户服务层
|
||||
* Class AuthService
|
||||
* @package app\service\admin\auth
|
||||
*/
|
||||
class AuthService extends BaseAdminService
|
||||
{
|
||||
/**
|
||||
* 校验用户和传入站点是否存在从属关系
|
||||
* @param Request $request
|
||||
* @return true
|
||||
*/
|
||||
public function checkSiteAuth(Request $request)
|
||||
{
|
||||
$site_id = $request->adminSiteId();
|
||||
//todo 将站点编号转化为站点id
|
||||
$site_info = (new CoreSiteService())->getSiteCache($site_id);
|
||||
//站点不存在
|
||||
if (empty($site_info)) throw new AuthException('SITE_NOT_EXIST');
|
||||
//没有当前站点的信息
|
||||
if (!AuthService::isSuperAdmin()) {
|
||||
if (!$this->getAuthRole($site_id)) throw new AuthException('NO_SITE_PERMISSION');
|
||||
}
|
||||
|
||||
$request->siteId($site_id);
|
||||
$request->appType($site_info['app_type']);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 校验权限
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function checkRole(Request $request)
|
||||
{
|
||||
$this->checkAuthinfo($request);
|
||||
|
||||
$rule = strtolower(trim($request->rule()->getRule()));
|
||||
$method = strtolower(trim($request->method()));
|
||||
$site_info = (new AuthSiteService())->getSiteInfo();
|
||||
if ($method != 'get') {
|
||||
// throw new AuthException('演示站禁止操作');
|
||||
if ($site_info[ 'status' ] == SiteDict::EXPIRE) throw new AuthException('SITE_EXPIRE_NOT_ALLOW');
|
||||
if ($site_info[ 'status' ] == SiteDict::CLOSE) throw new AuthException('SITE_CLOSE_NOT_ALLOW');
|
||||
}
|
||||
|
||||
$menu_service = new MenuService();
|
||||
$all_menu_list = $menu_service->getAllApiList($this->app_type);
|
||||
//先判断当前访问的接口是否收到权限的限制
|
||||
$method_menu_list = $all_menu_list[$method] ?? [];
|
||||
if (!in_array($rule, $method_menu_list)) {
|
||||
$other_menu_list = $menu_service->getAllApiList($this->app_type == AppTypeDict::ADMIN ? AppTypeDict::SITE : AppTypeDict::ADMIN);
|
||||
$method_menu_list = $other_menu_list[$method] ?? [];
|
||||
if (!in_array($rule, $method_menu_list)) {
|
||||
return true;
|
||||
} else {
|
||||
throw new AuthException('NO_PERMISSION');
|
||||
}
|
||||
}
|
||||
|
||||
$auth_role_list = $this->getAuthApiList();
|
||||
if (!empty($auth_role_list[$method]) && in_array($rule, $auth_role_list[$method]))
|
||||
return true;
|
||||
|
||||
throw new AuthException('NO_PERMISSION');
|
||||
|
||||
}
|
||||
|
||||
public function checkAuthinfo(Request $request) {
|
||||
$rule = strtolower(trim($request->rule()->getRule()));
|
||||
$method = strtolower(trim($request->method()));
|
||||
|
||||
if ($method == 'get') return;
|
||||
|
||||
// niucloud/account/select、bind、cancel、token、logout:授权选择与官网登录态相关接口。
|
||||
// 授权域名校验本身依赖「已绑定的授权」,选择/更换/清除授权、以及登录/退出官网账号都是修复授权的前置动作,
|
||||
// 必须豁免,否则域名与旧授权不一致时会陷入「校验失败 -> 无法重新选择授权」的死循环
|
||||
$ignore = ['niucloud/authinfo', 'upgrade', 'niucloud/build', 'sys/cache/clear', 'niucloud/account/select', 'niucloud/account/bind', 'niucloud/account/cancel', 'niucloud/account/token', 'niucloud/account/logout'];
|
||||
foreach ($ignore as $item) {
|
||||
if (strpos($rule, $item) !== false) return;
|
||||
}
|
||||
|
||||
$authinfo = [];
|
||||
try {
|
||||
$authinfo = (new CoreAuthService())->getAuthInfo()['data'] ?? [];;
|
||||
} catch (Exception $e) {
|
||||
}
|
||||
if (empty($authinfo)) return;
|
||||
|
||||
if (!$this->isCheckDomain()) return;
|
||||
|
||||
$site_address = $authinfo['site_address'] ?? '';
|
||||
$domain = str_replace(['http://', 'https://'], '', request()->domain());
|
||||
|
||||
// 如果是站点域名不进行验证
|
||||
$site_id = (new CoreSiteService())->getSiteIdByDomain($domain);
|
||||
if (!empty($site_id)) return;
|
||||
|
||||
if (!empty($site_address) && strpos($domain, $site_address) !== false) return;
|
||||
|
||||
throw new CommonException("授权域名校验失败!请确保当前访问域名与授权码绑定的域名一致");
|
||||
}
|
||||
|
||||
private function isCheckDomain() {
|
||||
return !(request()->ip() == '127.0.0.1' || request()->host() == 'localhost');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权用户的权限信息
|
||||
* @return mixed
|
||||
*/
|
||||
public function getAuthRole(int $site_id)
|
||||
{
|
||||
$user_role_service = new UserRoleService();
|
||||
return $user_role_service->getUserRole($site_id, $this->uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前授权用户接口权限
|
||||
* @return array
|
||||
*/
|
||||
public function getAuthApiList()
|
||||
{
|
||||
if (AuthService::isSuperAdmin()) {
|
||||
$is_admin = 1;
|
||||
} else {
|
||||
$user_role_info = $this->getAuthRole($this->site_id);
|
||||
if (empty($user_role_info))
|
||||
return [];
|
||||
|
||||
$is_admin = $user_role_info['is_admin'];//是否是超级管理员组
|
||||
}
|
||||
|
||||
$menu_service = new MenuService();
|
||||
if ($is_admin) {//查询全部启用的权限
|
||||
//获取站点信息
|
||||
return (new AuthSiteService())->getApiList(1);
|
||||
} else {
|
||||
$user_role_ids = $user_role_info['role_ids'];
|
||||
$role_service = new RoleService();
|
||||
$menu_keys = $role_service->getMenuIdsByRoleIds($this->site_id, $user_role_ids);
|
||||
|
||||
return $menu_service->getApiListByMenuKeys($menu_keys, $this->app_type);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前授权用户菜单权限
|
||||
* @return array
|
||||
*/
|
||||
public function getAuthMenuList(int $is_tree = 0, $addon = 'all')
|
||||
{
|
||||
if (AuthService::isSuperAdmin()) {
|
||||
$is_admin = 1;
|
||||
} else {
|
||||
$user_role_info = $this->getAuthRole($this->site_id);
|
||||
if (empty($user_role_info))
|
||||
return [];
|
||||
$is_admin = $user_role_info['is_admin'];//是否是超级管理员组
|
||||
}
|
||||
|
||||
$menu_service = new MenuService();
|
||||
if ($is_admin) {
|
||||
// 查询全部启用的权限
|
||||
$menu_list = (new MenuService())->getAllMenuList($this->app_type, 1, $is_tree, 1);
|
||||
} else {
|
||||
$user_role_ids = $user_role_info['role_ids'];
|
||||
$role_service = new RoleService();
|
||||
$menu_keys = $role_service->getMenuIdsByRoleIds($this->site_id, $user_role_ids);
|
||||
$menu_list = $menu_service->getMenuListByMenuKeys($this->site_id, $menu_keys, $this->app_type, $is_tree, $addon);
|
||||
}
|
||||
return $menu_list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权用户信息
|
||||
*/
|
||||
public function getAuthInfo()
|
||||
{
|
||||
return (new SiteUserService())->getInfo($this->uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改用户权限
|
||||
* @param string $field
|
||||
* @param $data
|
||||
* @return bool
|
||||
*/
|
||||
public function modifyAuth(string $field, $data)
|
||||
{
|
||||
return (new SiteUserService())->modify($this->uid, $field, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改用户
|
||||
* @param array $data
|
||||
* @return true
|
||||
*/
|
||||
public function editAuth(array $data)
|
||||
{
|
||||
if (!empty($data['password'])) {
|
||||
//检测原始密码是否正确
|
||||
$user = (new UserService())->find($this->uid);
|
||||
if (!check_password($data['original_password'], $user->password))
|
||||
throw new AuthException('OLD_PASSWORD_ERROR');
|
||||
|
||||
}
|
||||
return (new UserService())->edit($this->uid, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是超级管理员
|
||||
* @return bool
|
||||
*/
|
||||
public static function isSuperAdmin()
|
||||
{
|
||||
$super_admin_uid = Cache::get('super_admin_uid');
|
||||
|
||||
if (!$super_admin_uid) {
|
||||
$super_admin_uid = (new SysUserRole())->where([
|
||||
['site_id', '=', request()->defaultSiteId()],
|
||||
['is_admin', '=', 1]
|
||||
])->value('uid');
|
||||
Cache::set('super_admin_uid', $super_admin_uid);
|
||||
}
|
||||
|
||||
return $super_admin_uid == (new self())->uid;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,478 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | Niucloud-admin 企业快速开发的saas管理平台
|
||||
// +----------------------------------------------------------------------
|
||||
// | 官方网址:https://www.niucloud.com
|
||||
// +----------------------------------------------------------------------
|
||||
// | niucloud团队 版权所有 开源版本可自由商用
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: Niucloud Team
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace app\service\admin\niucloud;
|
||||
|
||||
use app\dict\sys\ConfigKeyDict;
|
||||
use app\service\core\niucloud\CoreAuthService;
|
||||
use app\service\core\sys\CoreConfigService;
|
||||
use core\base\BaseAdminService;
|
||||
use core\exception\CommonException;
|
||||
use core\util\niucloud\BaseNiucloudClient;
|
||||
use GuzzleHttp\Client;
|
||||
use think\facade\Cache;
|
||||
use think\facade\Log;
|
||||
|
||||
/**
|
||||
* 官网账号(内嵌授权)服务层
|
||||
*
|
||||
* 说明:
|
||||
* 1. 官网账号登录与授权选择全部在官网 embed 页完成(iframe),本服务只负责
|
||||
* 生成 embed 地址、保存账号/授权元信息、以及把回传的授权凭据落到本地授权配置。
|
||||
* 2. 授权落库复用 NiucloudService::setAuthorize(),保证与现有授权业务(升级、应用下载、云编译)
|
||||
* 完全一致:authinfo 校验 -> 清理 access_token 与 authinfo 缓存 -> 写 NIUCLOUD_CONFIG。
|
||||
*/
|
||||
class NiucloudAccountService extends BaseAdminService
|
||||
{
|
||||
/**
|
||||
* 官网前端域名(embed 页所在站点)
|
||||
*/
|
||||
protected const OFFICIAL_WEB_HOST = 'https://www.niucloud.com';
|
||||
|
||||
/**
|
||||
* 官网会员接口地址(与官网前端 VITE_APP_BASE_URL 一致,用于用 refresh_token 换取新的 access token)
|
||||
* 可用环境变量 NIUCLOUD_API_PREFIX 覆盖(本地联调时指向本地官网接口)
|
||||
*/
|
||||
protected const DEFAULT_OFFICIAL_API_HOST = 'https://api.niucloud.com/api';
|
||||
|
||||
/** 续期得到的访问令牌本地缓存键(避免每次进页面都请求官网) */
|
||||
protected const ACCESS_TOKEN_CACHE_KEY = 'niucloud_web_access_token';
|
||||
|
||||
/** 距过期不足该秒数即提前续期,避免临界失效 */
|
||||
protected const TOKEN_REFRESH_AHEAD = 300;
|
||||
|
||||
public $core_config_service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->core_config_service = new CoreConfigService();
|
||||
}
|
||||
|
||||
/**
|
||||
* 官网前端域名
|
||||
*/
|
||||
public function getOfficialWebHost(): string
|
||||
{
|
||||
return rtrim(self::OFFICIAL_WEB_HOST, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 本站域名(授权绑定用,不含协议与端口)
|
||||
*/
|
||||
public function getSiteDomain(): string
|
||||
{
|
||||
return request()->host(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成本站的页面 origin(postMessage 校验用)
|
||||
*/
|
||||
public function getSiteOrigin(): string
|
||||
{
|
||||
return rtrim(request()->domain(), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成官网 embed 页地址
|
||||
*
|
||||
* @param string $mode login | authorize | switch
|
||||
* @param string $origin 父页面 origin(由前端传 window.location.origin,最准确)
|
||||
*/
|
||||
public function getEmbedUrl(string $mode = 'login', string $origin = ''): array
|
||||
{
|
||||
$mode_path = [
|
||||
'login' => 'login',
|
||||
'authorize' => 'authorize',
|
||||
'switch' => 'authorize',
|
||||
'account' => 'account'
|
||||
];
|
||||
$path = $mode_path[$mode] ?? 'login';
|
||||
$host = $origin ?: $this->getSiteOrigin();
|
||||
|
||||
$params = [
|
||||
'host' => $host,
|
||||
'domain' => $this->getSiteDomain(),
|
||||
'mode' => $mode,
|
||||
'theme' => 'light',
|
||||
// 当前产品线标识:内嵌页只展示符合本产品线的授权
|
||||
'product_key' => BaseNiucloudClient::PRODUCT
|
||||
];
|
||||
// 官网登录态:本地缓存有效则直接用,过期则由服务端用 refresh_token 自动续期后注入
|
||||
$access_token = $this->getValidAccessToken();
|
||||
if (!empty($access_token)) $params['token'] = $access_token;
|
||||
|
||||
$query = http_build_query($params);
|
||||
|
||||
return [
|
||||
'url' => $this->getOfficialWebHost() . '/embed/' . $path . '?' . $query,
|
||||
'host' => $host,
|
||||
'domain' => $this->getSiteDomain(),
|
||||
'mode' => $mode
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取账号与当前授权信息(只读本地配置,官网不可用时仍可展示)
|
||||
*
|
||||
* 授权信息统一取自系统授权配置 NIUCLOUD_CONFIG(选中授权即写入其中);
|
||||
* 官网账号配置只保留登录态(token)、会员信息与同步状态
|
||||
*/
|
||||
public function getAccountInfo(): array
|
||||
{
|
||||
$account = $this->getAccountConfig();
|
||||
$auth = $this->getAuthorizeConfig();
|
||||
|
||||
$authorization = !empty($auth['auth_code']) ? $this->buildAuthorizationFromLocal($auth) : [];
|
||||
|
||||
return [
|
||||
// 系统已存在授权即视为“已有授权”
|
||||
'bound' => !empty($authorization['auth_code']),
|
||||
// 是否已保存可用的官网登录态(前端据此决定内嵌登录页还是账号页,避免闪屏)
|
||||
'has_token' => $this->hasValidToken(),
|
||||
// 登录态有效期:优先给刷新令牌的过期时间(访问令牌由服务端自动续期)
|
||||
'token_expires_time' => (int)($account['token']['refresh_expires_time'] ?? 0) ?: (int)($account['token']['expires_time'] ?? 0),
|
||||
'member' => $account['member'] ?? [],
|
||||
'authorization' => $authorization,
|
||||
'sync' => $account['sync'] ?? []
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存官网账号登录态(内嵌页登录后回传的令牌)
|
||||
*
|
||||
* 说明:
|
||||
* - 长期保存的是 refresh_token(access token 会过期,只有刷新令牌能实现长期免登录)
|
||||
* - access token 只放缓存(短效),避免配置里长期存着一份会失效的凭据
|
||||
* - 官网旧版本未下发 refresh_token 时,退回只保存 access token,保证基本可用
|
||||
* - 不返回令牌内容,避免凭据外泄
|
||||
*/
|
||||
public function saveToken(array $data): array
|
||||
{
|
||||
$token = trim((string)($data['token'] ?? ''));
|
||||
$refresh_token = trim((string)($data['refresh_token'] ?? ''));
|
||||
if (empty($token) && empty($refresh_token)) throw new CommonException('WEB_LOGIN_TOKEN_REQUIRE');
|
||||
|
||||
$expires_time = (int)($data['expires_time'] ?? 0);
|
||||
$refresh_expires_time = (int)($data['refresh_expires_time'] ?? 0);
|
||||
|
||||
$account = $this->getAccountConfig();
|
||||
$old_token = $account['token'] ?? [];
|
||||
|
||||
$account['token'] = [
|
||||
// 长期凭据:access token 过期后用它换取新的 access token
|
||||
'refresh_token' => $refresh_token ?: ($old_token['refresh_token'] ?? ''),
|
||||
'refresh_expires_time' => $refresh_expires_time ?: (int)($old_token['refresh_expires_time'] ?? 0),
|
||||
// 兼容:官网未下发刷新令牌时,退回保存访问令牌
|
||||
'access_token' => $refresh_token ? '' : $token,
|
||||
'expires_time' => $refresh_token ? 0 : $expires_time,
|
||||
'update_time' => date('Y-m-d H:i:s')
|
||||
];
|
||||
$this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account);
|
||||
|
||||
// 登录态已变更(含切换官网账号):先清掉上一份访问令牌缓存,
|
||||
// 否则官网只回传 refresh_token 时,getValidAccessToken() 仍会优先返回上一个账号的令牌
|
||||
Cache::delete(self::ACCESS_TOKEN_CACHE_KEY);
|
||||
|
||||
// 本次登录拿到的访问令牌直接进缓存,省去一次续期请求
|
||||
if (!empty($token)) $this->cacheAccessToken($token, $expires_time);
|
||||
|
||||
return [
|
||||
'has_token' => true,
|
||||
'token_expires_time' => $expires_time
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 可用的官网访问令牌(未登录 / 登录态已失效时返回空字符串)
|
||||
*
|
||||
* 优先级:
|
||||
* 1. 本地缓存的访问令牌未过期(距过期不足 TOKEN_REFRESH_AHEAD 秒视为需续期)→ 直接返回
|
||||
* 2. 有未过期的 refresh_token → 向官网换取新的访问令牌(长期免登录的关键)
|
||||
* 3. 兼容旧数据:只保存过访问令牌且未过期 → 直接返回
|
||||
*/
|
||||
public function getValidAccessToken(): string
|
||||
{
|
||||
$auth_token = $this->getAccountConfig()['token'] ?? [];
|
||||
|
||||
// 1. 本地缓存的访问令牌
|
||||
$cached = Cache::get(self::ACCESS_TOKEN_CACHE_KEY, []);
|
||||
$cached_token = (string)($cached['token'] ?? '');
|
||||
$cached_expires = (int)($cached['expires_time'] ?? 0);
|
||||
if (!empty($cached_token) && ($cached_expires <= 0 || $cached_expires > time() + self::TOKEN_REFRESH_AHEAD)) {
|
||||
return $cached_token;
|
||||
}
|
||||
|
||||
// 2. 用刷新令牌续期
|
||||
$refresh_token = (string)($auth_token['refresh_token'] ?? '');
|
||||
if (!empty($refresh_token)) {
|
||||
$refresh_expires_time = (int)($auth_token['refresh_expires_time'] ?? 0);
|
||||
// 未记录有效期(0)时视为长期有效
|
||||
if ($refresh_expires_time > 0 && $refresh_expires_time <= time()) return '';
|
||||
|
||||
return $this->exchangeAccessToken($refresh_token);
|
||||
}
|
||||
|
||||
// 3. 兼容:仅保存过访问令牌
|
||||
$access_token = (string)($auth_token['access_token'] ?? '');
|
||||
if (empty($access_token)) return '';
|
||||
|
||||
$expires_time = (int)($auth_token['expires_time'] ?? 0);
|
||||
if ($expires_time > 0 && $expires_time <= time()) return '';
|
||||
|
||||
return $access_token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否存在可用的官网登录态(refresh_token 未过期即视为可续期)
|
||||
*/
|
||||
public function hasValidToken(): bool
|
||||
{
|
||||
return $this->getValidAccessToken() !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 官网会员接口地址
|
||||
*/
|
||||
protected function getOfficialApiHost(): string
|
||||
{
|
||||
return rtrim((string)(env('NIUCLOUD_API_PREFIX') ?: self::DEFAULT_OFFICIAL_API_HOST), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存访问令牌(TTL 与令牌有效期对齐,未记录有效期时按 2 小时缓存)
|
||||
*/
|
||||
protected function cacheAccessToken(string $token, int $expires_time): void
|
||||
{
|
||||
$ttl = $expires_time > 0 ? max(60, $expires_time - time()) : 7200;
|
||||
Cache::set(self::ACCESS_TOKEN_CACHE_KEY, [
|
||||
'token' => $token,
|
||||
'expires_time' => $expires_time
|
||||
], $ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 官网会员接口客户端
|
||||
*/
|
||||
protected function createOfficialClient(): Client
|
||||
{
|
||||
return new Client([
|
||||
'base_uri' => $this->getOfficialApiHost() . '/',
|
||||
'timeout' => 10,
|
||||
'verify' => config('niucloud.http.verify', true)
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 refresh_token 向官网换取新的访问令牌(官网内嵌页专属接口 embed/refresh)
|
||||
*
|
||||
* 失败(网络异常 / 刷新令牌失效)返回空字符串,由调用方降级为"需重新登录",
|
||||
* 不影响授权等其它功能。
|
||||
*/
|
||||
protected function exchangeAccessToken(string $refresh_token): string
|
||||
{
|
||||
try {
|
||||
$response = $this->createOfficialClient()->post('embed/refresh', [
|
||||
'form_params' => [ 'refresh_token' => $refresh_token ]
|
||||
]);
|
||||
$result = json_decode((string)$response->getBody(), true);
|
||||
} catch (\Throwable $e) {
|
||||
Log::write('官网登录态续期请求失败:' . $e->getMessage());
|
||||
return '';
|
||||
}
|
||||
|
||||
$token = (string)($result['data']['token'] ?? '');
|
||||
if (empty($token)) {
|
||||
Log::write('官网登录态续期失败:' . json_encode($result, JSON_UNESCAPED_UNICODE));
|
||||
return '';
|
||||
}
|
||||
|
||||
$this->cacheAccessToken($token, (int)($result['data']['expires_time'] ?? 0));
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知官网作废刷新令牌(官网内嵌页专属接口 embed/logout,幂等)
|
||||
*
|
||||
* 退出官网账号时调用,避免本地清掉后官网侧令牌仍可换取新的访问令牌;
|
||||
* 失败只记日志,不阻塞本地退出。
|
||||
*/
|
||||
protected function revokeRefreshToken(string $refresh_token): void
|
||||
{
|
||||
try {
|
||||
$this->createOfficialClient()->post('embed/logout', [
|
||||
'form_params' => [ 'refresh_token' => $refresh_token ]
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::write('官网刷新令牌作废失败:' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 选用授权:选中即写入系统授权配置(NIUCLOUD_CONFIG)并生效
|
||||
*
|
||||
* 说明:
|
||||
* - 复用现有授权校验链路:官网 authinfo 二次校验 -> 清理 authinfo/access_token 缓存 -> 写 NIUCLOUD_CONFIG
|
||||
* - 校验不通过(授权码无效 / 官网不可达)会直接抛出异常,**不写入任何配置**
|
||||
* - 不改动官网侧授权域名
|
||||
*/
|
||||
public function saveSelectedAuth(array $data): array
|
||||
{
|
||||
$this->applyAuthorization($data);
|
||||
|
||||
return $this->getAccountInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定授权(与选用授权等价,保留接口兼容)
|
||||
*/
|
||||
public function bindAuthorization(array $data): array
|
||||
{
|
||||
$this->applyAuthorization($data);
|
||||
|
||||
return $this->getAccountInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消选用授权:清空系统授权配置(NIUCLOUD_CONFIG),系统回到“未授权”状态
|
||||
*
|
||||
* 说明:
|
||||
* - 只清系统已选授权,不影响官网账号登录态(token / 会员信息保留),也不删除官网账号下的授权记录
|
||||
* - 幂等:本来就没有授权时同样返回成功
|
||||
* - 清空后依赖授权的功能(升级、应用下载、云编译等)会回到未授权状态
|
||||
*
|
||||
* @param array $data 入参仅用于记录日志(auth_code 可选)
|
||||
*/
|
||||
public function cancelSelectedAuth(array $data = []): array
|
||||
{
|
||||
(new NiucloudService())->clearAuthorize();
|
||||
|
||||
$account = $this->getAccountConfig();
|
||||
$account['sync'] = [
|
||||
'last_sync_time' => date('Y-m-d H:i:s'),
|
||||
'last_sync_status' => 'cancel'
|
||||
];
|
||||
$this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account);
|
||||
|
||||
return $this->getAccountInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用授权:把授权码/密钥写入系统授权配置 NIUCLOUD_CONFIG(选用 / 绑定共用)
|
||||
*
|
||||
* - 先校验后写:校验失败直接抛错,原有授权配置保持不变
|
||||
* - 授权信息只落 NIUCLOUD_CONFIG;官网账号配置仅更新同步状态
|
||||
*/
|
||||
protected function applyAuthorization(array $data): void
|
||||
{
|
||||
$auth_code = $data['auth_code'] ?? '';
|
||||
$auth_secret = $data['auth_secret'] ?? '';
|
||||
if (empty($auth_code) || empty($auth_secret)) throw new CommonException('AUTH_NOT_EXISTS');
|
||||
|
||||
// 复用现有链路(含 authinfo 二次校验、缓存清理),不信任前端直接落库
|
||||
(new NiucloudService())->setAuthorize([
|
||||
'auth_code' => $auth_code,
|
||||
'auth_secret' => $auth_secret
|
||||
]);
|
||||
|
||||
$account = $this->getAccountConfig();
|
||||
// 授权信息已统一存于 NIUCLOUD_CONFIG,清掉历史遗留的副本
|
||||
unset($account['authorization']);
|
||||
$account['sync'] = [
|
||||
'last_sync_time' => date('Y-m-d H:i:s'),
|
||||
'last_sync_status' => 'success'
|
||||
];
|
||||
$this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account);
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出官网账号会话(仅清除账号信息,不解除本地授权)
|
||||
*/
|
||||
public function logout(): bool
|
||||
{
|
||||
$account = $this->getAccountConfig();
|
||||
// 主动作废官网侧的刷新令牌(失败不阻塞本地退出)
|
||||
$refresh_token = (string)($account['token']['refresh_token'] ?? '');
|
||||
if (!empty($refresh_token)) $this->revokeRefreshToken($refresh_token);
|
||||
|
||||
unset($account['member'], $account['token']);
|
||||
// 一并清掉续期得到并缓存的访问令牌
|
||||
Cache::delete(self::ACCESS_TOKEN_CACHE_KEY);
|
||||
$account['sync'] = [
|
||||
'last_sync_time' => date('Y-m-d H:i:s'),
|
||||
'last_sync_status' => 'logout'
|
||||
];
|
||||
$this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步当前授权状态(读官网 authinfo,失败不抛出,仅记录状态)
|
||||
*/
|
||||
public function syncState(): array
|
||||
{
|
||||
$auth_info = [];
|
||||
try {
|
||||
$auth_info = (new CoreAuthService())->getAuthInfo()['data'] ?? [];
|
||||
} catch (\Throwable $e) {
|
||||
$auth_info = [];
|
||||
}
|
||||
|
||||
$account = $this->getAccountConfig();
|
||||
$account['sync'] = [
|
||||
'last_sync_time' => date('Y-m-d H:i:s'),
|
||||
'last_sync_status' => empty($auth_info) ? 'fail' : 'success'
|
||||
];
|
||||
|
||||
// 官网记录的授权域名是否与本站一致:仅记录到同步信息里便于排查(授权信息本身在 NIUCLOUD_CONFIG)
|
||||
if (!empty($auth_info)) {
|
||||
$account['sync']['address_type'] = $auth_info['address_type'] ?? false;
|
||||
}
|
||||
|
||||
$this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account);
|
||||
|
||||
return $this->getAccountInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* 官网账号配置
|
||||
*/
|
||||
protected function getAccountConfig(): array
|
||||
{
|
||||
$config = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG);
|
||||
return $config['value'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地授权配置
|
||||
*/
|
||||
protected function getAuthorizeConfig(): array
|
||||
{
|
||||
$config = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG);
|
||||
return $config['value'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 由系统授权配置构造授权信息(NIUCLOUD_CONFIG 只存 auth_code / auth_secret)
|
||||
*/
|
||||
protected function buildAuthorizationFromLocal(array $auth): array
|
||||
{
|
||||
return [
|
||||
'auth_code' => $auth['auth_code'] ?? '',
|
||||
'site_address' => '',
|
||||
'company_name' => '',
|
||||
'product_key_name' => '',
|
||||
'source' => 'manual',
|
||||
'update_time' => ''
|
||||
];
|
||||
}
|
||||
}
|
||||
151
niucloud/niucloud/app/service/admin/niucloud/NiucloudService.php
Normal file
151
niucloud/niucloud/app/service/admin/niucloud/NiucloudService.php
Normal file
@ -0,0 +1,151 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | Niucloud-admin 企业快速开发的saas管理平台
|
||||
// +----------------------------------------------------------------------
|
||||
// | 官方网址:https://www.niucloud.com
|
||||
// +----------------------------------------------------------------------
|
||||
// | niucloud团队 版权所有 开源版本可自由商用
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: Niucloud Team
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace app\service\admin\niucloud;
|
||||
|
||||
use app\dict\sys\ConfigKeyDict;
|
||||
use app\service\core\niucloud\CoreAuthService;
|
||||
use app\service\core\niucloud\CoreModuleService;
|
||||
use app\service\core\sys\CoreConfigService;
|
||||
use core\base\BaseAdminService;
|
||||
use core\exception\CommonException;
|
||||
use think\facade\Cache;
|
||||
|
||||
/**
|
||||
* 消息管理服务层
|
||||
*/
|
||||
class NiucloudService extends BaseAdminService
|
||||
{
|
||||
public $core_config_service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->core_config_service = new CoreConfigService();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 授权信息
|
||||
* @param $data
|
||||
* @return \app\model\sys\SysConfig|bool|\think\Model
|
||||
*/
|
||||
public function setAuthorize($data){
|
||||
|
||||
$data = [
|
||||
'auth_code' => $data['auth_code'],
|
||||
'auth_secret' => $data['auth_secret']
|
||||
];
|
||||
// 校验前先清缓存,否则更换授权码/密钥时校验会读到旧授权的数据:
|
||||
// 1) authinfo 缓存是全局 key(不含授权码),不清会直接命中旧授权的信息,新授权码根本没被官网校验就落库
|
||||
// 2) access_token 与授权码绑定,留着旧 token 会让校验请求带上旧授权的令牌
|
||||
Cache::delete("authinfo");
|
||||
$service = (new CoreAuthService($data['auth_code'], $data['auth_secret']));
|
||||
$service->clearAccessToken();
|
||||
$auth_info = $service->getAuthInfo()['data'] ?? [];
|
||||
if (empty($auth_info)) throw new CommonException('AUTH_NOT_EXISTS');
|
||||
return $this->core_config_service->setConfig(0,ConfigKeyDict::NIUCLOUD_CONFIG, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除授权信息(取消选用授权)
|
||||
*
|
||||
* 与 setAuthorize() 对称:删除 NIUCLOUD_CONFIG 配置并清理 authinfo / access_token 缓存,
|
||||
* 避免升级、应用下载、云编译等依赖授权的功能仍读到已被取消的授权。
|
||||
* 幂等:本就没有授权时同样不报错。
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function clearAuthorize()
|
||||
{
|
||||
// 先取出旧授权,用于清理其 access_token 缓存(旧授权已失效时清理失败不影响取消动作)
|
||||
$old = $this->getAuthorize();
|
||||
if (!empty($old['auth_code']) && !empty($old['auth_secret'])) {
|
||||
try {
|
||||
(new CoreAuthService($old['auth_code'], $old['auth_secret']))->clearAccessToken();
|
||||
} catch (\Throwable $e) {
|
||||
// 忽略:旧授权凭据已失效
|
||||
}
|
||||
}
|
||||
|
||||
Cache::delete("authinfo");
|
||||
$this->core_config_service->clearConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权信息
|
||||
* @return mixed|string[]
|
||||
*/
|
||||
public function getAuthorize(){
|
||||
$info = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG);
|
||||
if(empty($info))
|
||||
{
|
||||
$info = [];
|
||||
$info['value'] = [
|
||||
'auth_code' => '',
|
||||
'auth_secret' => ''
|
||||
];
|
||||
}
|
||||
return $info['value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取框架最新版本
|
||||
*/
|
||||
public function getFrameworkLastVersion() {
|
||||
return (new CoreModuleService())->getFrameworkLastVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取框架版本更新记录
|
||||
*/
|
||||
public function getFrameworkVersionList() {
|
||||
return (new CoreModuleService())->getFrameworkVersionList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取应用/插件的版本更新记录
|
||||
*/
|
||||
public function getAppVersionList($app_key) {
|
||||
return (new CoreModuleService())->getAppVersionList($app_key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 本地服务器地址
|
||||
* @param $data
|
||||
* @return \app\model\sys\SysConfig|bool|\think\Model
|
||||
*/
|
||||
public function setLocalCloudCompileConfig($data){
|
||||
$data = [
|
||||
'baseUri' => $data['url'],
|
||||
'isOpen' => $data['is_open'],
|
||||
];
|
||||
return $this->core_config_service->setConfig(0,'LOCAL_CLOUD_COMPILE_CONFIG', $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 本地服务器地址
|
||||
* @param $data
|
||||
* @return \app\model\sys\SysConfig|bool|array|\think\Model
|
||||
*/
|
||||
public function getLocalCloudCompileConfig(){
|
||||
$config = $this->core_config_service->getConfig(0,'LOCAL_CLOUD_COMPILE_CONFIG')['value'] ?? [];
|
||||
return [
|
||||
'baseUri' => $config['baseUri'] ?? '',
|
||||
'isOpen' => $config['isOpen'] ?? 0,
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
1757
niucloud/niucloud/vendor/topthink/think-orm/src/db/BaseQuery.php
vendored
Normal file
1757
niucloud/niucloud/vendor/topthink/think-orm/src/db/BaseQuery.php
vendored
Normal file
File diff suppressed because it is too large
Load Diff
372
niucloud/niucloud/vendor/topthink/think-orm/src/model/relation/OneToOne.php
vendored
Normal file
372
niucloud/niucloud/vendor/topthink/think-orm/src/model/relation/OneToOne.php
vendored
Normal file
@ -0,0 +1,372 @@
|
||||
<?php
|
||||
|
||||
// +----------------------------------------------------------------------
|
||||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2006~2025 http://thinkphp.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: liu21st <liu21st@gmail.com>
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace think\model\relation;
|
||||
|
||||
use Closure;
|
||||
use think\db\BaseQuery as Query;
|
||||
use think\db\exception\DbException as Exception;
|
||||
use think\db\exception\InvalidArgumentException;
|
||||
use think\helper\Str;
|
||||
use think\model\contract\Modelable as Model;
|
||||
use think\model\Relation;
|
||||
|
||||
/**
|
||||
* 一对一关联基础类.
|
||||
*/
|
||||
abstract class OneToOne extends Relation
|
||||
{
|
||||
/**
|
||||
* JOIN类型.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $joinType = 'INNER';
|
||||
|
||||
/**
|
||||
* 绑定的关联属性.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $bindAttr = [];
|
||||
|
||||
/**
|
||||
* 关联名.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $relation;
|
||||
|
||||
/**
|
||||
* 获取一对多关联的最新一条数据.
|
||||
*
|
||||
* @param string $field 排序字段
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function firstOfMany(string $field = '')
|
||||
{
|
||||
return $this->first($field);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一对多关联的最旧一条数据.
|
||||
*
|
||||
* @param string $field 排序字段
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function lastOfMany(string $field = '')
|
||||
{
|
||||
return $this->last($field);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置join类型.
|
||||
*
|
||||
* @param string $type JOIN类型
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function joinType(string $type)
|
||||
{
|
||||
$this->joinType = $type;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预载入关联查询(JOIN方式).
|
||||
*
|
||||
* @param Query $query 查询对象
|
||||
* @param string $relation 关联名
|
||||
* @param mixed $field 关联字段
|
||||
* @param string $joinType JOIN方式
|
||||
* @param Closure $closure 闭包条件
|
||||
* @param bool $first
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function eagerly(Query $query, string $relation, $field = true, string $joinType = '', ?Closure $closure = null, bool $first = false): void
|
||||
{
|
||||
$name = Str::snake(class_basename($this->parent));
|
||||
|
||||
if ($first) {
|
||||
$table = $query->getTable();
|
||||
$query->table([$table => $name]);
|
||||
|
||||
if ($query->getOption('field')) {
|
||||
$masterField = $query->getOption('field');
|
||||
$query->removeOption('field');
|
||||
} else {
|
||||
$masterField = true;
|
||||
}
|
||||
|
||||
$query->tableField($masterField, $table, $name);
|
||||
}
|
||||
|
||||
// 预载入封装
|
||||
$joinTable = $this->query->getTable();
|
||||
// think-orm 3.x → 4.x 兼容:恢复 JOIN 别名使用「关联名原样」
|
||||
// 4.x 改为 Str::snake($relation),会把别名从 goodsSku 变成 goods_sku,
|
||||
// 导致业务代码 where/field 里的 goodsSku.xxx 关系名前缀与别名不匹配,
|
||||
// 报 SQLSTATE[42S22] 1054 Unknown column 'goodsSku.xxx'。
|
||||
$joinAlias = $relation;
|
||||
$joinType = $joinType ?: $this->joinType;
|
||||
if (true !== $field) {
|
||||
$joinField = $field;
|
||||
} elseif ($this->query->getOption('field')) {
|
||||
$joinField = $this->query->getOption('field');
|
||||
} else {
|
||||
$joinField = $field;
|
||||
}
|
||||
|
||||
$query->via($joinAlias);
|
||||
|
||||
if ($this instanceof BelongsTo) {
|
||||
$foreignKeyExp = $this->foreignKey;
|
||||
|
||||
if (!str_contains($foreignKeyExp, '.')) {
|
||||
$foreignKeyExp = $name . '.' . $this->foreignKey;
|
||||
}
|
||||
|
||||
$joinOn = $foreignKeyExp . '=' . $joinAlias . '.' . $this->localKey;
|
||||
} else {
|
||||
$foreignKeyExp = $this->foreignKey;
|
||||
|
||||
if (!str_contains($foreignKeyExp, '.')) {
|
||||
$foreignKeyExp = $joinAlias . '.' . $this->foreignKey;
|
||||
}
|
||||
|
||||
$joinOn = $name . '.' . $this->localKey . '=' . $foreignKeyExp;
|
||||
}
|
||||
|
||||
if ($closure) {
|
||||
// 备份主查询字段:闭包里的 field 属于主查询,不能当作关联 JOIN 字段。
|
||||
// 否则 tableField() 会把已带表前缀的主查询字段当作关联字段全部跳过,
|
||||
// 导致 JOIN 表的所有字段都不会被 SELECT,关联数据始终为空。
|
||||
$masterField = $query->getOption('field');
|
||||
$masterField = $masterField ? (array) $masterField : [];
|
||||
|
||||
// 执行闭包查询(附加筛选条件,兼容 3.x 在闭包中写 field 的用法)
|
||||
$closure($query);
|
||||
|
||||
// 闭包里的 field 属于主查询(含 real_name as related_name 这类别名),
|
||||
// 合并回主查询字段;关联表字段仍按全字段追加,保证关联数据可取。
|
||||
$closureField = $query->getOption('field');
|
||||
if (!empty($closureField)) {
|
||||
foreach ((array) $closureField as $key => $item) {
|
||||
if (is_int($key)) {
|
||||
if (!in_array($item, $masterField, true)) {
|
||||
$masterField[] = $item;
|
||||
}
|
||||
} else {
|
||||
$masterField[$key] = $item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($masterField)) {
|
||||
$query->removeOption('field');
|
||||
} else {
|
||||
$query->setOption('field', $masterField);
|
||||
}
|
||||
}
|
||||
|
||||
$query->join([$joinTable => $joinAlias], $joinOn, $joinType)
|
||||
->tableField($joinField, $joinTable, $joinAlias, $joinAlias . '__');
|
||||
}
|
||||
|
||||
/**
|
||||
* 预载入关联查询(数据集).
|
||||
*
|
||||
* @param array $resultSet
|
||||
* @param string $relation
|
||||
* @param array $subRelation
|
||||
* @param Closure $closure
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
abstract protected function eagerlySet(array &$resultSet, string $relation, array $subRelation = [], ?Closure $closure = null);
|
||||
|
||||
/**
|
||||
* 预载入关联查询(数据).
|
||||
*
|
||||
* @param Model $result
|
||||
* @param string $relation
|
||||
* @param array $subRelation
|
||||
* @param Closure $closure
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
abstract protected function eagerlyOne(Model $result, string $relation, array $subRelation = [], ?Closure $closure = null);
|
||||
|
||||
/**
|
||||
* 预载入关联查询(数据集).
|
||||
*
|
||||
* @param array $resultSet 数据集
|
||||
* @param string $relation 当前关联名
|
||||
* @param array $subRelation 子关联名
|
||||
* @param Closure $closure 闭包
|
||||
* @param array $cache 关联缓存
|
||||
* @param bool $join 是否为JOIN方式
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function eagerlyResultSet(array &$resultSet, string $relation, array $subRelation = [], ?Closure $closure = null, array $cache = [], bool $join = false): void
|
||||
{
|
||||
if ($join) {
|
||||
// 模型JOIN关联组装
|
||||
foreach ($resultSet as $result) {
|
||||
$this->match($this->model, $relation, $result);
|
||||
}
|
||||
} else {
|
||||
// IN查询
|
||||
$this->eagerlySet($resultSet, $relation, $subRelation, $closure, $cache);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预载入关联查询(数据).
|
||||
*
|
||||
* @param Model $result 数据对象
|
||||
* @param string $relation 当前关联名
|
||||
* @param array $subRelation 子关联名
|
||||
* @param Closure $closure 闭包
|
||||
* @param array $cache 关联缓存
|
||||
* @param bool $join 是否为JOIN方式
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function eagerlyResult(Model $result, string $relation, array $subRelation = [], ?Closure $closure = null, array $cache = [], bool $join = false): void
|
||||
{
|
||||
if ($join) {
|
||||
// 模型JOIN关联组装
|
||||
$this->match($this->model, $relation, $result);
|
||||
} else {
|
||||
// IN查询
|
||||
$this->eagerlyOne($result, $relation, $subRelation, $closure, $cache);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存(新增)当前关联数据对象
|
||||
*
|
||||
* @param array|Model $data 数据 可以使用数组 关联模型对象
|
||||
* @param bool $replace 是否自动识别更新和写入
|
||||
*
|
||||
* @return Model|false
|
||||
*/
|
||||
public function save(array | Model $data, bool $replace = true)
|
||||
{
|
||||
$model = $this->make();
|
||||
|
||||
return $model->replace($replace)->save($data) ? $model : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建关联对象实例.
|
||||
*
|
||||
* @param array|Model $data
|
||||
*
|
||||
* @return Model
|
||||
*/
|
||||
public function make(array | Model $data = []): Model
|
||||
{
|
||||
if ($data instanceof Model) {
|
||||
$data = $data->getData();
|
||||
}
|
||||
|
||||
// 保存关联表数据
|
||||
$data[$this->foreignKey] = $this->parent->{$this->localKey};
|
||||
|
||||
return (new $this->model($data))->setSuffix($this->getModel()->getSuffix());
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定关联表的属性到父模型属性.
|
||||
*
|
||||
* @param array $attr 要绑定的属性列表
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function bind(array $attr)
|
||||
{
|
||||
$this->bindAttr = $attr;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一对一 关联模型预查询拼装.
|
||||
*
|
||||
* @param string $model 模型名称
|
||||
* @param string $relation 关联名
|
||||
* @param Model $result 模型对象实例
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function match(string $model, string $relation, Model $result): void
|
||||
{
|
||||
$data = $result->getRelation($relation);
|
||||
// JOIN 未匹配时关联表字段全为 null,应视为没有关联数据,避免生成空关联对象
|
||||
if (!empty($data) && !empty(array_filter($data, fn ($value) => null !== $value))) {
|
||||
if ($this->bindAttr) {
|
||||
$result->bindRelationAttr($data, $this->bindAttr);
|
||||
} else {
|
||||
$relationModel = new $model($data);
|
||||
$result->setRelation($relation, $relationModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 一对一 关联模型预查询(IN方式).
|
||||
*
|
||||
* @param array $where 关联预查询条件
|
||||
* @param string $key 关联键名
|
||||
* @param array $subRelation 子关联
|
||||
* @param Closure $closure
|
||||
* @param array $cache 关联缓存
|
||||
* @param bool $collection 是否数据集查询
|
||||
* @return array
|
||||
*/
|
||||
protected function eagerlyWhere(array $where, string $key, array $subRelation = [], ?Closure $closure = null, array $cache = [], bool $collection = false)
|
||||
{
|
||||
// 预载入关联查询 支持嵌套预载入
|
||||
if ($closure) {
|
||||
$this->baseQuery = true;
|
||||
$closure($this->query);
|
||||
}
|
||||
|
||||
if ($collection) {
|
||||
$this->query->removeOption('limit');
|
||||
} else {
|
||||
$this->query->limit(1);
|
||||
}
|
||||
|
||||
$list = $this->query
|
||||
->where($where)
|
||||
->with($subRelation)
|
||||
->cache($cache[0] ?? false, $cache[1] ?? null, $cache[2] ?? null)
|
||||
->lazy();
|
||||
|
||||
// 组装模型数据
|
||||
$data = [];
|
||||
foreach ($list as $set) {
|
||||
if (!isset($data[$set->$key])) {
|
||||
$data[$set->$key] = $set;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user