This commit is contained in:
mzl
2025-07-18 17:32:42 +08:00
parent 94938d0586
commit 228408149b
23 changed files with 1880 additions and 1008 deletions
-155
View File
@@ -1,155 +0,0 @@
<?php
namespace app\common\service;
use app\common\logic\AuthLogic;
use app\common\model\User;
use support\Cache;
class AuthService_bak
{
// 缓存 Key
protected static function cacheKey(int $userId): string
{
return "user_resources_{$userId}";
}
/**
* 获取用户所有资源(目录/菜单/权限),合并角色+直接分配,并缓存
*/
public static function getUserResources(int $userId)
{
$cacheKey = self::cacheKey($userId);
$cached = Cache::get($cacheKey);
if ($cached !== null) {
return $cached;
}
$user = User::with(['roles.resources', 'resources'])->find($userId);
if (!$user) {
return collect();
}
// 合并:角色资源 + 用户直接资源
$all = collect();
foreach ($user->roles as $role) {
$all = $all->merge($role->resources);
}
$all = $all->merge($user->resources);
$unique = $all->unique('id')->values();
Cache::set($cacheKey, $unique, 3600);
return $unique;
}
/**
* 构建目录/菜单树,并给每个菜单节点挂载权限列表和打开方式
*/
public static function getMenuTree(int $userId): array
{
$resources = self::getUserResources($userId);
$menus = $resources
->filter(fn($r) => in_array($r->type, ['directory','menu']))
->values();
return self::buildTree($menus, $resources);
}
protected static function buildTree($nodes, $allResources, int $parentId = 0): array
{
$tree = [];
foreach ($nodes as $node) {
if ($node->parent_id !== $parentId) continue;
// 子节点
$children = self::buildTree($nodes, $allResources, $node->id);
// 本级权限列表
$authList = $allResources
->filter(fn($r) => $r->type === 'permission' && $r->parent_id === $node->id)
->map(fn($r) => [
'id' => $r->id,
'title' => $r->name,
'auth_mark' => $r->code,
])->values()->all();
$tree[] = [
'id' => $node->id,
'name' => $node->name,
'path' => $node->url,
'meta' => [
'title' => $node->name,
'icon' => $node->icon,
'keepAlive' => true,
'authList' => $authList,
// 新增打开方式字段
'openType' => $node->open_type, // 'internal' | 'external' | 'iframe'
],
'children' => $children,
];
}
return $tree;
}
/**
* 获取用户所有权限 code(仅 type=permission)
*/
public static function getPermissionCodes(int $userId): array
{
return self::getUserResources($userId)
->filter(fn($res) => $res->type === 'permission')
->pluck('code')
->unique()
->values()
->all();
}
/** 清除缓存(角色/资源变更时调用) */
public static function clearCache(int $userId): void
{
Cache::delete(self::cacheKey($userId));
}
public function login(array $data): array
{
$loginType = $data['login_type'] ?? 'upwd';
$logic = new AuthLogic();
return match ($loginType) {
'feishu' => $logic->feishuLogin($data),
'qrcode' => $logic->qrCodeLogin($data),
default => $logic->uPwdLogin($data),
};
}
/**
* 用户注册
*
* @param array $data
* @return User
*/
public function register(array $data): User
{
return (new AuthLogic())->register($data);
}
public function verifyToken(string $token): array
{
return (new AuthLogic())->verifyToken($token);
}
public function refreshToken(string $refreshToken): array
{
return (new AuthLogic())->refreshToken($refreshToken);
}
public function logout(?string $token)
{
(new AuthLogic())->logout($token);
}
public function blockToken(string $token)
{
(new AuthLogic())->blockToken($token);
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
namespace app\common\service;
use app\common\logic\BaseCrudLogic;
use support\Request;
class CrudService
{
protected BaseCrudLogic $logic;
public function __construct(BaseCrudLogic $logic)
{
$this->logic = $logic;
}
/**
* 列表接口
* 支持前端直接传递:
* - filter_* → where
* - sort_by, order
* - fields (逗号分隔)
* - with (逗号分隔)
* - withFields (relation:field,field;...)
* - dataLimitType, dataLimitField
* - limit, page
* - complex_query=1 则调用 complexQuery()
*/
public function list(Request $request): array
{
$p = $request->get();
// 复杂查询开关
if (!empty($p['complex_query']) && method_exists($this, 'complexQuery')) {
return $this->complexQuery($p);
}
// 1. 构造 where
$where = [];
foreach ($p as $k => $v) {
if (strpos($k, 'filter_') === 0 && $v !== '') {
$col = substr($k, 7);
// 简单等值或 like
$where[$col] = strpos($v, '%') !== false ? ['like', $v] : $v;
}
}
// 2. 构造其他配置
$config = [
'where' => $where,
'order' => [($p['sort_by'] ?? 'id') => ($p['order'] ?? 'desc')],
'fields' => !empty($p['fields']) ? explode(',', $p['fields']) : [],
'with' => !empty($p['with']) ? explode(',', $p['with']) : [],
'withFields' => $this->parseWithFields($p['withFields'] ?? ''),
'dataLimit' => !empty($p['dataLimitType']) ? [
'type' => $p['dataLimitType'],
'field' => $p['dataLimitField'] ?? 'admin_id'
] : [],
];
$limit = (int)($p['limit'] ?? 15);
$page = (int)($p['page'] ?? 1);
$pager = $this->logic->list($config, $limit, $page);
return ['total' => $pager->total(), 'data' => $pager->items()];
}
/**
* 详情
*/
public function show($id)
{
return $this->logic->show($id, []);
}
/**
* 创建
*/
public function store(Request $request)
{
$data = $request->post();
$dataLimit = $this->getDataLimitFromRequest($request);
return $this->logic->create($data, $dataLimit);
}
/**
* 更新
*/
public function update(Request $request)
{
$key = $this->logic->modelClass::make()->getKeyName();
$id = (int)$request->post($key);
$data= $request->post();
$dataLimit = $this->getDataLimitFromRequest($request);
return $this->logic->updateByPk($id, $data, $dataLimit);
}
/**
* 删除
*/
public function destroy(Request $request)
{
$key = $this->logic->modelClass::make()->getKeyName();
$ids = (array)$request->post($key, []);
return $this->logic->deleteByPk($ids);
}
/** ---------- helpers ---------- */
/**
* 解析 withFields 参数 "rel:field,field;rel2:..."
*/
protected function parseWithFields(string $str): array
{
if (!$str) return [];
$out = [];
foreach (explode(';', $str) as $pair) {
[$rel, $flds] = explode(':', $pair);
$out[$rel] = explode(',', $flds);
}
return $out;
}
/**
* 从请求里读取 dataLimitType/Field
*/
protected function getDataLimitFromRequest(Request $req): array
{
$type = $req->get('dataLimitType');
if (!$type) return [];
return [
'type' => $type,
'field' => $req->get('dataLimitField', 'admin_id'),
];
}
/**
* 子类可重写,做复杂联表查询等
*/
protected function complexQuery(array $params): array
{
throw new \LogicException('请在子类实现 complexQuery 方法');
}
}