Compare commits

...

11 Commits

Author SHA1 Message Date
5890122a37 fix : readme update 2025-09-18 17:26:45 +08:00
b405585bc7 fix : readme update 2025-09-17 17:18:39 +08:00
5d2f32b22b fix : readme update 2025-09-17 17:18:18 +08:00
082c15d697 fix : first finish 2025-09-17 16:17:55 +08:00
21331655f9 fix : common request 2025-09-16 18:07:10 +08:00
be0d0913b6 fix : update path And request 2025-09-16 15:14:47 +08:00
c1d8f02491 fix : update menu 2025-09-16 14:30:37 +08:00
2613b031ae feat : admin log 2025-09-16 14:30:12 +08:00
a6d6738ab2 feat : admin role finish 2025-09-16 10:38:45 +08:00
b1713d8476 feat : admin role unfinish 2025-09-15 18:56:34 +08:00
5ed0e2d4f5 feat : admin menu 2025-09-15 17:09:00 +08:00
57 changed files with 2124 additions and 265 deletions

View File

@@ -1,22 +1,25 @@
APP_NAME=sfyy APP_NAME=ctext
APP_ENV=dev APP_ENV=dev
APP_DEBUG=false APP_DEBUG=false
APP_URL=http://127.0.0.1:9501 APP_URL=http://127.0.0.1:9501
JWT_SECRET=azOVxsOWt3r0ozZNz8Ss429ht0T8z6OpeIJAIwNp6X0xqrbEY2epfIWyxtC1qSNM8eD6/LQ/SahcQi2ByXa/2A== JWT_SECRET=azOVxsOWt3r0ozZNz8Ss429ht0T8z6OpeIJAIwNp6X0xqrbEY2epfIWyxtC1qSNM8eD6/LQ/SahcQi2ByXa/2A==
JWT_ADMIN_SECRET=azOVxsOWt3r0ozZNz8Ss429ht0T8z6OpeIJAIwNp6X0xqrbEY2epfIWyxtC1qSNM8eD6/LQ/SahcQi2ByXa/2Aaa
# [ide]
DEVTOOL_IDE=phpstorm
DB_DRIVER=mysql DB_DRIVER=mysql
DB_HOST=s2.gnip.vip DB_HOST=127.0.0.1
DB_PORT=20191 DB_PORT=3306
DB_DATABASE=mineadmin DB_DATABASE=xxx
DB_USERNAME=hhl DB_USERNAME=username
DB_PASSWORD=hhltest DB_PASSWORD=password
DB_CHARSET=utf8mb4 DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_unicode_ci DB_COLLATION=utf8mb4_unicode_ci
DB_PREFIX= DB_PREFIX=
REDIS_HOST=s2.gnip.vip REDIS_HOST=127.0.0.1
REDIS_AUTH=hhltest REDIS_AUTH=
REDIS_PORT=4379 REDIS_PORT=6379
REDIS_DB=0 REDIS_DB=0

223
README.md
View File

@@ -1,6 +1,6 @@
## 仓库 ## 仓库
- [sfyy_server](https://codeup.aliyun.com/67039465d8d1ada68263f984/hhl/rewrite/hyperf_service.git) - git远程仓库地址 - [hyperf_rbac_framework_server_ctexthuang](https://gitee.com/ctexthuang/hyperf_rbac_framework_server_ctexthuang.git) - git远程仓库地址
## 特性 ## 特性
@@ -27,9 +27,7 @@
- 获取代码 - 获取代码
```bash ```bash
git clone https://codeup.aliyun.com/67039465d8d1ada68263f984/hhl/rewrite/hyperf_service.git git clone https://gitee.com/ctexthuang/hyperf_rbac_framework_server_ctexthuang.git
mkdir uploads
``` ```
- vendor - vendor
@@ -50,22 +48,32 @@ php bin/hyperf.php start
- command 函数 - command 函数
```bash ```bash
#框架自有 #框架自有 php bin/hyperf.php + 以下
php bin/hyperf.php gen:controller LoginController gen:amqp-consumer Create a new amqp consumer class
php bin/hyperf.php gen:model UserModel gen:amqp-producer Create a new amqp producer class
php bin/hyperf.php gen:request LoginRequest gen:aspect Create a new aspect class
php bin/hyperf.php gen:command TestCommand gen:class Create a new class
php bin/hyperf.php gen:job TestJob gen:command Create a new command class
php bin/hyperf.php gen:listener TestListener gen:constant Create a new constant class
php bin/hyperf.php gen:middleware AuthMiddleware gen:controller Create a new controller class
php bin/hyperf.php gen:amqp-consumer DemoConsumer gen:job Create a new job class
php bin/hyperf.php gen:amqp-producer DemoProducer gen:kafka-consumer Create a new kafka consumer class
php bin/hyperf.php gen:constant ErrorCode --type enum gen:listener Create a new listener class
gen:middleware Create a new middleware class
gen:migration Generate a new migration file
gen:model Create new model classes.
gen:nats-consumer Create a new nats consumer class
gen:nsq-consumer Create a new nsq consumer class
gen:process Create a new process class
gen:repository Create a new repository class
gen:request Create a new form request class
gen:resource create a new resource
gen:seeder Create a new seeder class
gen:service Create a new service class
#新增命令 #新增命令
php bin/hyperf.php gen:service LoginService php bin/hyperf.php gen:service LoginService
php bin/hyperf.php gen:cron OssTask php bin/hyperf.php gen:repository OssRepository
php bin/hyperf.php gen:event TestEvent
``` ```
## Git 贡献提交规范 ## Git 贡献提交规范
@@ -86,9 +94,6 @@ php bin/hyperf.php gen:event TestEvent
- `wip` 开发中 - `wip` 开发中
- `types` 类型 - `types` 类型
## cache
不允许使用序列化,为跨语言做准备
## 日志(合理安排) ## 日志(合理安排)
| 分组名称 | 用途 | 日志级别 | 保留天数 | 备注 | | 分组名称 | 用途 | 日志级别 | 保留天数 | 备注 |
|---------|---------|------------|------|----------| |---------|---------|------------|------|----------|
@@ -98,4 +103,180 @@ php bin/hyperf.php gen:event TestEvent
| request | 请求访问日志 | INFO | 15 | 记录所有请求 | | request | 请求访问日志 | INFO | 15 | 记录所有请求 |
| cron | 定时任务日志 | INFO | 30 | 定时任务执行记录 | | cron | 定时任务日志 | INFO | 30 | 定时任务执行记录 |
| payment | 支付相关日志 | INFO | 90 | 重要财务数据 | | payment | 支付相关日志 | INFO | 90 | 重要财务数据 |
| audit | 审计日志 | INFO | 365 | 重要操作记录 | | audit | 审计日志 | INFO | 365 | 重要操作记录 |\
```php
//注入这个类
use App\Lib\Log\Logger;
$this->logger->cache()->error(...),
```
## 缓存
```php
//注入这个类
use App\Cache\Redis\RedisCache
$this->redis->with($poolName)->exists($key)
//$poolName 配置在 config/autoload/redis.php 在 default下面追加即可 看官网
//lua调用涉及多文件请看示例
$this->redis->with($poolName ?? 'default')->lua(RateLimit::class)->check($argument);
//lua()里面是App\Cache\Redis\Lua\*文件 后面跟的方法是 该文件的方法
//我做了返回类型补全 可以直接IDE跳转查看参数
```
## tips
1.AdminService类必须继承BaseAdminService
```php
//例子 app/Service/Admin/AdminUser/UserService
class UserService extends \App\Service\Admin\BaseAdminService {
}
//由于在 app/Controller/Admin/AdminUserController 中 service 是 注解注入的 所以 BaseAdminService只会实例化一次单例
class AdminUserController extends AbstractController
{
/**
* @var UserService
*/
#[Inject]
protected UserService $service;
/**
* @return array
*/
#[RequestMapping(path: "getInfo", methods: "GET")]
public function getInfo(): array
{
return $this->service->handle();
}
}
//所以在service中获取上下文的数据必须重置获取而不能存入BaseService属性中拿取
//假设在 Api目录中写 BaseApiService请务必注意
class UserService extends \App\Service\Admin\BaseAdminService {
/**
* @param string $name
* @return \current_admin_id|mixed
*/
public function __get(string $name)
{
if ($name === 'adminId') return Context::get('current_admin_id',0);
if (!property_exists($this, $name)) throw new ErrException('属性未定义');
return $this->$name;
}
}
class UserService extends BaseAdminService{
public function handle()
{
return $this->adminId;
}
}
// 或者在controller中实例化去调用
class AdminUserController extends AbstractController
{
/**
* @return array
*/
#[RequestMapping(path: "getInfo", methods: "GET")]
public function getInfo(): array
{
return (new UserService)->handle();
}
}
```
2.controller必须增加ResponseFormat注解
```php
//示例 : app/Controller/Admin/AdminUserController
#[Controller(prefix: "admin/adminUser")]
#[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
#[Middleware(middleware: PermissionMiddleware::class, priority: 99)]
class AdminUserController extends \App\Controller\AbstractController{
}
//因为在涉及到公有抛出 ErrException或者 验证器抛出 的时候 会根据不同的注解 返回不同的 Return
class BaseErrExceptionHandler extends ExceptionHandler{
public function handle()
{
// 从注解获取响应格式(优先于路径解析)
$format = $this->request->getAttribute('response_format') ?? $this->repairResponseFormatByPath();
// 动态选择策略
$returnClass = match ($format) {
'admin', 'common' => AdminReturn::class,
'api' => ApiReturn::class,
default => null,
};
}
}
// 通过切面存入
class ResponseFormatAspect extends AbstractAspect
{
// 获取注解定义的格式
$annotation = $proceedingJoinPoint->getAnnotationMetadata()->class[ResponseFormat::class]
?? $proceedingJoinPoint->getAnnotationMetadata()->method[ResponseFormat::class] ?? null;
if ($annotation) {
// 将注解格式存入请求属性(覆盖中间件的默认值)
$request = $proceedingJoinPoint->arguments['request'] ?? null;
if ($request instanceof Request) {
$request->withAttribute('response_format', $annotation->format);
}
}
}
```
3.token的使用要分模块
```php
//示例 app/Service/Admin/Login/LoginService
use App\Service\BaseTokenService $tokenService
class LoginService extends \App\Service\Admin\BaseAdminService{
public function handle()
{
$jwtHandle = $this->tokenService->setJwt('admin')->getJwt();
return $this->adminReturn->success('success',[
'access_token' => $jwtHandle->builderAccessToken((string) $adminInfo->id)->toString(),
'refresh_token' => $jwtHandle->builderRefreshToken((string) $adminInfo->id)->toString(),
'expire_at' => (int) $jwtHandle->getConfig('ttl', 0),
]);
}
}
//setJwt函数里面类似$poolName 设置在 config/autoload/jwt.php 未设置属性可复用 default 设置
```
4.引入 Repository层架构 解放 model层压力 model 只管理数据模型和关联
```php
//详细请看app/Common/Repository 文件下的文件 示例 app/Service/Admin/Login/LoginService
class LoginService extends \App\Service\Admin\BaseAdminService{
/**
* 需要提前注入
* @var AdminUserRepository
*/
#[Inject]
protected AdminUserRepository $userRepository;
public function handle()
{
$adminInfo = $this->userRepository->findByUserName((string)$this->request->input('username'));
}
}
```
5.公用类都在 app/Common 下面 包括 `Interface``Macros``Repository``Trait`
6.后台权限注解 #[Permission] 和 #[PermissionMiddleware]

View File

@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace App\Aspect;
use App\Common\Repository\AdminUserRepository;
use App\Common\Trait\ClientIpTrait;
use App\Common\Trait\ClientOsTrait;
use App\Lib\Log\Logger;
use App\Model\AdminUserLoginLog;
use App\Service\Admin\Login\LoginService;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;
use Hyperf\HttpServer\Contract\RequestInterface;
use Throwable;
#[Aspect]
class AdminLoginLogAspect extends AbstractAspect
{
use ClientIpTrait;
use ClientOsTrait;
/**
* 切入类
* @var array|\class-string[]
*/
public array $classes = [
LoginService::class,
];
/**
* @var bool
*/
private bool $loginSuccess = false;
/**
* @var string
*/
private string $loginMsg = '';
/**
* @param Logger $logger
* @param RequestInterface $request
* @param AdminUserRepository $adminUserRepository
* @param AdminUserLoginLog $adminUserLoginLogModel
*/
public function __construct(
protected readonly Logger $logger,
protected RequestInterface $request,
protected readonly AdminUserRepository $adminUserRepository,
protected readonly AdminUserLoginLog $adminUserLoginLogModel,
) {}
/**
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws Exception
* @throws Throwable
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
// 写日志
try {
$res = $proceedingJoinPoint->process();
$this->loginSuccess = true;
$this->loginMsg = 'success';
} catch (Throwable $throwable) {
$this->loginSuccess = false;
$this->loginMsg = $throwable->getMessage();
throw $throwable;
} finally {
$this->writeLoginLog();
}
// 返回
return $res;
}
/**
* @return void
*/
private function writeLoginLog(): void
{
$userInfo = $this->adminUserRepository->findByUserName($this->request->input('username'));
$context = [
'username' => $this->request->input('username',''),
'password' => $this->request->input('password',''),
'user_info' => $userInfo?->toArray() ?? [],
'ip' => $this->getClientIp(),
'os' => $this->getClientOs(),
'browser' => $this->request->header('User-Agent') ?: 'unknown',
];
Coroutine::create(function () use ($userInfo, $context) {
$this->logger->request()->info('admin_login_log', $context);
$this->adminUserLoginLogModel->create([
'admin_user_id' => $userInfo?->id ?? 0,
'username' => $userInfo?->username ?? '',
'ip' => current($context['ip']) ?: '0.0.0.0',
'os' => $context['os'],
'browser' => $context['browser'] ?? '',
'status' => $this->loginSuccess ? 1 : 2,
'message' => $this->loginMsg,
]);
});
}
}

View File

@@ -1,82 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Aspect;
use App\Lib\Log\Logger;
use App\Lib\Return\AdminReturn;
use App\Trait\ClientIpTrait;
use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Aop\ProceedingJoinPoint;
#[Aspect]
class AdminReturnAspect extends AbstractAspect
{
use ClientIpTrait;
/**
* 切入类
* @var array|\class-string[]
*/
public array $classes = [
AdminReturn::class,
];
/**
* @var int
*/
protected int $adminId = 0;
/**
* @param Logger $logger
* @param RequestInterface $request
*/
public function __construct(
protected readonly Logger $logger,
protected readonly RequestInterface $request,
) {
$this->adminId = Context::get('current_admin_id',0);
}
public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
// 直接从方法参数获取请求数据
$requestData = $proceedingJoinPoint->getArguments()[0] ?? [];
// 执行原方法并获取返回值
$responseData = $proceedingJoinPoint->process();
// 写日志
$this->writeLog($requestData, $responseData);
// 返回
return $requestData;
}
/**
* @param array $requestData
* @param array $responseData
* @return void
*/
private function writeLog(array $requestData = [], array $responseData = []): void
{
Coroutine::create(function () use ($requestData, $responseData) {
$context = [
'user_id' => $this->adminId,
'method' => $this->request->getMethod(),
'router' => $this->request->getUri(),
'ip' => $this->getClientIp(),
'request_data' => $requestData,
'response_data' => $responseData,
];
$this->logger->request()->info('admin_request_log', $context);
});
}
}

View File

@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace App\Aspect;
use App\Common\Trait\AdminUserTrait;
use App\Common\Trait\ClientIpTrait;
use App\Lib\Log\Logger;
use App\Lib\Return\AdminReturn;
use App\Model\AdminUser;
use App\Model\AdminUserOperationLog;
use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;
use Hyperf\HttpServer\Contract\RequestInterface;
#[Aspect]
class AdminReturnLogAspect extends AbstractAspect
{
use ClientIpTrait;
use AdminUserTrait;
/**
* 切入类
* @var array|\class-string[]
*/
public array $classes = [
AdminReturn::class,
];
/**
* @var int
*/
protected int $adminId = 0;
/**
* @var ?AdminUser
*/
protected ?AdminUser $adminUserInfo = null;
/**
* @param Logger $logger
* @param RequestInterface $request
* @param AdminUserOperationLog $adminUserOperationLogModel
*/
public function __construct(
protected readonly Logger $logger,
protected RequestInterface $request,
protected readonly AdminUserOperationLog $adminUserOperationLogModel,
) {
$this->adminId = Context::get('current_admin_id',0);
if ($this->adminId > 0) $this->adminUserInfo = $this->getAdminUserInfo($this->adminId);
}
/**
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws Exception
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
// 直接从方法参数获取请求数据
$requestData = $proceedingJoinPoint->getArguments()[0] ?? [];
// 执行原方法并获取返回值
$responseData = $proceedingJoinPoint->process();
// 没登录不记录日志
if ($this->adminId <= 0) return $responseData;
// 写日志
$this->writeOperationLog($requestData, $responseData);
// 返回
return $responseData;
}
/**
* @param array $requestData
* @param array $responseData
* @return void
*/
private function writeOperationLog(array $requestData = [], array $responseData = []): void
{
$context = [
'user_id' => $this->adminId,
'method' => $this->request->getMethod(),
'router' => $this->request->getUri(),
'ip' => $this->getClientIp(),
'request_data' => $requestData,
'response_data' => $responseData,
];
Coroutine::create(function () use ($requestData, $responseData, $context) {
$this->logger->request()->info('admin_request_log', $context);
$this->adminUserOperationLogModel->create([
'admin_user_id' => $this->adminId,
'username' => $this->adminUserInfo?->username ?? '',
'method' => $context['method'],
'router' => $context['router'],
'service_name' => $context['service_name'] ?? '',
'ip' => current($context['ip']) ?: '0.0.0.0',
]);
});
}
}

View File

@@ -163,7 +163,7 @@ abstract class BaseScript
]; ];
$logStrategy = match(true) { $logStrategy = match(true) {
!$success => $this->logger->cache()->error(...), !$success => $this->logger->error()->error(...),
$this->debugMode => $this->logger->cache()->debug(...), $this->debugMode => $this->logger->cache()->debug(...),
default => fn() => null // 不记录 default => fn() => null // 不记录
}; };

View File

@@ -2,6 +2,7 @@
namespace App\Cache\Redis; namespace App\Cache\Redis;
use App\Cache\Redis\Lua\RateLimit;
use App\Lib\Log\Logger; use App\Lib\Log\Logger;
use Hyperf\Contract\ConfigInterface; use Hyperf\Contract\ConfigInterface;
use Hyperf\Redis\RedisFactory; use Hyperf\Redis\RedisFactory;
@@ -9,6 +10,7 @@ use Hyperf\Redis\RedisProxy;
/** /**
* @mixin RedisProxy * @mixin RedisProxy
* @template T
*/ */
class RedisCache class RedisCache
{ {
@@ -53,10 +55,11 @@ class RedisCache
} }
/** /**
* @param string $scriptClass * @template TReturn
* @return mixed * @param class-string<TReturn> $scriptClass
* @return TReturn
*/ */
public function lua(string $scriptClass): mixed public function lua(string $scriptClass)
{ {
$poolName = $this->poolName ?? 'default'; $poolName = $this->poolName ?? 'default';
$key = $poolName . ':' . $scriptClass; $key = $poolName . ':' . $scriptClass;

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace App\Interface; namespace App\Common\Interface;
use Lcobucci\JWT\UnencryptedToken; use Lcobucci\JWT\UnencryptedToken;

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace App\Interface; namespace App\Common\Interface;
use Lcobucci\JWT\UnencryptedToken; use Lcobucci\JWT\UnencryptedToken;

View File

@@ -0,0 +1,80 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Common\Repository;
use App\Constants\Model\AdminUser\AdminMenuStatusCode;
use App\Model\AdminMenu;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
final class AdminMenuRepository extends BaseRepository
{
/**
* @param AdminMenu $model
*/
public function __construct(protected readonly AdminMenu $model) {}
/**
* @return bool
*/
public function enablePageOrderBy(): bool
{
return false;
}
/**
* @param array $params
* @return Collection
*/
public function list(array $params = []): Collection
{
return $this->perQuery($this->getQuery(), $params)->orderBy('sort')->get();
}
/**
* @param Builder $query
* @param array $params
* @return Builder
*/
public function handleSearch(Builder $query, array $params): Builder
{
$whereInName = static function (Builder $query, array|string $code) {
$query->whereIn('name', Arr::wrap($code));
};
return $query
->when(Arr::get($params, 'sortable'), static function (Builder $query, array $sortable) {
$query->orderBy(key($sortable), current($sortable));
})
->when(Arr::get($params, 'code'), $whereInName)
->when(Arr::get($params, 'name'), $whereInName)
->when(Arr::get($params, 'children'), static function (Builder $query) {
$query->with('children');
})->when(Arr::get($params, 'status'), static function (Builder $query, AdminMenuStatusCode $status) {
$query->where('status', $status);
})
->when(Arr::has($params, 'parent_id'), static function (Builder $query) use ($params) {
$query->where('parent_id', Arr::get($params, 'parent_id'));
});
}
/**
* @return Builder[]|\Hyperf\Database\Model\Collection
*/
public function allTree(): \Hyperf\Database\Model\Collection|array
{
return $this->model
->newQuery()
->where('parent_id', 0)
->with('children')
->get();
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Common\Repository;
use App\Model\AdminRole;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Builder;
final class AdminRoleRepository extends BaseRepository
{
public function __construct(protected readonly AdminRole $model) {}
/**
* @param Builder $query
* @param array $params
* @return Builder
*/
public function handleSearch(Builder $query, array $params): Builder
{
return $query->when(Arr::get($params, 'name'), static function (Builder $query, $name) {
$query->where('name', 'like', '%' . $name . '%');
})->when(Arr::get($params, 'code'), static function (Builder $query, $code) {
$query->whereIn('code', Arr::wrap($code));
})->when(Arr::has($params, 'status'), static function (Builder $query) use ($params) {
$query->where('status', $params['status']);
})->when(Arr::get($params, 'created_at'), static function (Builder $query, $createdAt) {
$query->whereBetween('created_at', $createdAt);
});
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Common\Repository;
use App\Model\AdminUserLoginLog;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Builder;
final class AdminUserLoginLogRepository extends BaseRepository
{
/**
* @param AdminUserLoginLog $model
*/
public function __construct(protected readonly AdminUserLoginLog $model) {}
/**
* @param Builder $query
* @param array $params
* @return Builder
*/
public function handleSearch(Builder $query, array $params): Builder
{
return $query
->when(Arr::get($params, 'username'), static function (Builder $query, $username) {
$query->where('username', $username);
})
->when(Arr::get($params, 'ip'), static function (Builder $query, $ip) {
$query->where('ip', $ip);
})
->when(Arr::get($params, 'os'), static function (Builder $query, $os) {
$query->where('os', $os);
})
->when(Arr::get($params, 'browser'), static function (Builder $query, $browser) {
$query->where('browser', $browser);
})
->when(Arr::get($params, 'status'), static function (Builder $query, $status) {
$query->where('status', $status);
})
->when(Arr::get($params, 'message'), static function (Builder $query, $message) {
$query->where('message', $message);
})
->when(Arr::get($params, 'login_time'), static function (Builder $query, $login_time) {
$query->whereBetween('login_time', $login_time);
})
->when(Arr::get($params, 'remark'), static function (Builder $query, $remark) {
$query->where('remark', $remark);
});
}
}

View File

@@ -0,0 +1,18 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Common\Repository;
use App\Model\AdminUserOperationLog;
final class AdminUserOperationLogRepository extends BaseRepository
{
public function __construct(protected readonly AdminUserOperationLog $model) {}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Common\Repository;
use App\Model\AdminUser;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Builder;
/**
* Class AdminUserRepository
* @extends BaseRepository<AdminUser>
*/
final class AdminUserRepository extends BaseRepository
{
public function __construct(protected readonly AdminUser $model) {}
/**
* @param string $username
* @return AdminUser|null
*/
public function findByUserName(string $username): AdminUser|null
{
// @phpstan-ignore-next-line
return $this->model->newQuery()
->where('username', $username)
->first();
}
/**
* @param Builder $query
* @param array $params
* @return Builder
*/
public function handleSearch(Builder $query, array $params): Builder
{
return $query
->when(Arr::get($params, 'unique_username'), static function (Builder $query, $uniqueUsername) {
$query->where('username', $uniqueUsername);
})
->when(Arr::get($params, 'username'), static function (Builder $query, $username) {
$query->where('username', 'like', '%' . $username . '%');
})
->when(Arr::get($params, 'phone'), static function (Builder $query, $phone) {
$query->where('phone', $phone);
})
->when(Arr::get($params, 'email'), static function (Builder $query, $email) {
$query->where('email', $email);
})
->when(Arr::exists($params, 'status'), static function (Builder $query) use ($params) {
$query->where('status', Arr::get($params, 'status'));
})
->when(Arr::exists($params, 'user_type'), static function (Builder $query) use ($params) {
$query->where('user_type', Arr::get($params, 'user_type'));
})
->when(Arr::exists($params, 'nickname'), static function (Builder $query) use ($params) {
$query->where('nickname', 'like', '%' . Arr::get($params, 'nickname') . '%');
})
->when(Arr::exists($params, 'created_at'), static function (Builder $query) use ($params) {
$query->whereBetween('created_at', [
Arr::get($params, 'created_at')[0] . ' 00:00:00',
Arr::get($params, 'created_at')[1] . ' 23:59:59',
]);
})
->when(Arr::get($params, 'user_ids'), static function (Builder $query, $userIds) {
$query->whereIn('id', $userIds);
})
->when(Arr::get($params, 'role_id'), static function (Builder $query, $roleId) {
$query->whereHas('roles', static function (Builder $query) use ($roleId) {
$query->where('role_id', $roleId);
});
});
}
}

View File

@@ -1,9 +1,9 @@
<?php <?php
namespace App\Repository; namespace App\Common\Repository;
use App\Repository\Traits\BootTrait; use App\Common\Repository\Traits\BootTrait;
use App\Repository\Traits\RepositoryOrderByTrait; use App\Common\Repository\Traits\RepositoryOrderByTrait;
use Hyperf\Collection\Collection; use Hyperf\Collection\Collection;
use Hyperf\Contract\LengthAwarePaginatorInterface; use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\Database\Model\Builder; use Hyperf\Database\Model\Builder;
@@ -13,7 +13,7 @@ use Hyperf\Paginator\AbstractPaginator;
/** /**
* @template T of Model * @template T of Model
* @property T $model * @property Model $model
*/ */
abstract class BaseRepository abstract class BaseRepository
{ {
@@ -67,7 +67,7 @@ abstract class BaseRepository
} }
/** /**
* @return T * @return Model
*/ */
public function create(array $data): mixed public function create(array $data): mixed
{ {
@@ -81,7 +81,7 @@ abstract class BaseRepository
} }
/** /**
* @return null|T * @return null|Model
*/ */
public function saveById(mixed $id, array $data): mixed public function saveById(mixed $id, array $data): mixed
{ {
@@ -105,7 +105,7 @@ abstract class BaseRepository
} }
/** /**
* @return null|T * @return null|Model
*/ */
public function findById(mixed $id): mixed public function findById(mixed $id): mixed
{ {
@@ -118,7 +118,7 @@ abstract class BaseRepository
} }
/** /**
* @return null|T * @return null|Model
*/ */
public function findByFilter(array $params): mixed public function findByFilter(array $params): mixed
{ {
@@ -142,7 +142,7 @@ abstract class BaseRepository
} }
/** /**
* @return T * @return Model
*/ */
public function getModel(): Model public function getModel(): Model
{ {

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace App\Repository\Traits; namespace App\Common\Repository\Traits;
use function Hyperf\Support\class_basename; use function Hyperf\Support\class_basename;
use function Hyperf\Support\class_uses_recursive; use function Hyperf\Support\class_uses_recursive;

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace App\Repository\Traits; namespace App\Common\Repository\Traits;
use Hyperf\Database\Model\Builder; use Hyperf\Database\Model\Builder;

View File

@@ -1,11 +1,12 @@
<?php <?php
namespace App\Trait; namespace App\Common\Trait;
use App\Cache\Redis\Lua\RateLimit;
use App\Cache\Redis\RedisCache; use App\Cache\Redis\RedisCache;
use App\Cache\Redis\RedisKey; use App\Cache\Redis\RedisKey;
use App\Common\Repository\AdminUserRepository;
use App\Model\AdminUser; use App\Model\AdminUser;
use App\Repository\AdminUserRepository;
use Hyperf\Context\Context; use Hyperf\Context\Context;
use Hyperf\Database\Model\Model; use Hyperf\Database\Model\Model;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
@@ -25,6 +26,7 @@ trait AdminUserTrait
protected AdminUserRepository $adminUserRepository; protected AdminUserRepository $adminUserRepository;
/** /**
* 单例加缓存模型(仅仅用户信息) tips: 只可读取显示的数据(不影响大致问题),不可操作类敏感数据 比如 inc 账户余额 之类的 会导致脏读
* @param int $adminId * @param int $adminId
* @return AdminUser|Model|mixed|string|null * @return AdminUser|Model|mixed|string|null
*/ */

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace App\Trait; namespace App\Common\Trait;
use App\Constants\Common\ClientIpRequestConstant; use App\Constants\Common\ClientIpRequestConstant;
use App\Exception\ErrException; use App\Exception\ErrException;
@@ -15,7 +15,7 @@ trait ClientIpTrait
* @var RequestInterface * @var RequestInterface
*/ */
#[Inject] #[Inject]
protected readonly RequestInterface $request; protected RequestInterface $request;
/** /**
* @var string[] * @var string[]

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Common\Trait;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
trait ClientOsTrait
{
/**
* @var RequestInterface
*/
#[Inject]
protected RequestInterface $request;
/**
* @return string
*/
public function getClientOs(): string
{
$userAgent = $this->request->header('user-agent');
if (empty($userAgent)) return 'Unknown';
return match (true) {
preg_match('/win/i', $userAgent) => 'Windows',
preg_match('/mac/i', $userAgent) => 'MAC',
preg_match('/linux/i', $userAgent) => 'Linux',
preg_match('/unix/i', $userAgent) => 'Unix',
preg_match('/bsd/i', $userAgent) => 'BSD',
default => 'Other',
};
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Common\Trait;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
trait HttpMethodTrait
{
/**
* @var RequestInterface
*/
#[Inject]
protected readonly RequestInterface $request;
/**
* @return bool
*/
public function isCreate(): bool
{
return $this->request->isMethod('POST');
}
/**
* @return bool
*/
public function isUpdate(): bool
{
return $this->request->isMethod('PATCH') || $this->request->isMethod('PUT');
}
/**
* @return bool
*/
public function isDelete(): bool
{
return $this->request->isMethod('DELETE');
}
/**
* @return bool
*/
public function isSearch(): bool
{
return $this->request->isMethod('GET');
}
}

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace App\Trait; namespace App\Common\Trait;
trait ParserRouterTrait trait ParserRouterTrait
{ {

View File

@@ -25,4 +25,7 @@ class ResultCode extends AbstractConstants
#[Message("token错误")] #[Message("token错误")]
final public const int JWT_ERROR = 10002; final public const int JWT_ERROR = 10002;
#[Message("旧密码错误")]
final public const int OLD_PASSWORD_ERROR = 10003;
} }

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin;
use App\Annotation\Permission;
use App\Annotation\ResponseFormat;
use App\Controller\AbstractController;
use App\Middleware\Admin\AdminTokenMiddleware;
use App\Middleware\Admin\PermissionMiddleware;
use App\Request\Admin\AdminMenuRequest;
use App\Service\Admin\AdminUser\MenuService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Validation\Annotation\Scene;
#[Controller(prefix: "admin/menu")]
#[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
#[Middleware(middleware: PermissionMiddleware::class, priority: 99)]
class AdminMenuController extends AbstractController
{
/**
* @var MenuService
*/
#[Inject]
protected MenuService $service;
/**
* @return array
*/
#[RequestMapping(path: "list", methods: "GET")]
#[Permission(code: 'permission:menu:index')]
public function pageList(): array
{
return $this->service->handle();
}
/**
* @param AdminMenuRequest $request
* @return array
*/
#[RequestMapping(path: "", methods: "POST")]
#[Permission(code: 'permission:menu:create')]
#[Scene(scene: "create")]
public function createMenu(AdminMenuRequest $request): array
{
return $this->service->create();
}
/**
* @param int $id
* @param AdminMenuRequest $request
* @return array
*/
#[RequestMapping(path: "{id}", methods: "PUT")]
#[Permission(code: 'permission:menu:save')]
#[Scene(scene: "update")]
public function updateMenu(int $id, AdminMenuRequest $request): array
{
return $this->service->update($id);
}
/**
* @return array
*/
#[RequestMapping(path: "", methods: "DELETE")]
#[Permission(code: 'permission:menu:delete')]
public function deleteMenu(): array
{
return $this->service->delete();
}
}

View File

@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin;
use App\Annotation\Permission;
use App\Annotation\ResponseFormat;
use App\Controller\AbstractController;
use App\Middleware\Admin\AdminTokenMiddleware;
use App\Middleware\Admin\PermissionMiddleware;
use App\Request\Admin\AdminRoleRequest;
use App\Service\Admin\AdminUser\RoleService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Validation\Annotation\Scene;
#[Controller(prefix: "admin/role")]
#[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
#[Middleware(middleware: PermissionMiddleware::class, priority: 99)]
class AdminRoleController extends AbstractController
{
/**
* @var RoleService
*/
#[Inject]
protected RoleService $service;
/**
* @return array
*/
#[RequestMapping(path: "list", methods: "GET")]
#[Permission(code: 'permission:role:index')]
public function pageList(): array
{
return $this->service->handle();
}
/**
* @param AdminRoleRequest $request
* @return array
*/
#[RequestMapping(path: "", methods: "POST")]
#[Permission(code: 'permission:role:save')]
#[Scene(scene: "create")]
public function createRole(AdminRoleRequest $request): array
{
return $this->service->create();
}
/**
* @param int $id
* @param AdminRoleRequest $request
* @return array
*/
#[RequestMapping(path: "{id}", methods: "PUT")]
#[Permission(code: 'permission:role:update')]
#[Scene(scene: "create")]
public function updateRole(int $id, AdminRoleRequest $request): array
{
return $this->service->update($id);
}
/**
* @return array
*/
#[RequestMapping(path: "", methods: "DELETE")]
#[Permission(code: 'permission:role:delete')]
public function deleteRole(): array
{
return $this->service->delete();
}
/**
* @param int $id
* @return array
*/
#[RequestMapping(path: "{id}/permission", methods: "GET")]
#[Permission(code: 'permission:role:getMenu')]
public function getRolePermission(int $id): array
{
return $this->service->getRole($id);
}
/**
* @param int $id
* @param AdminRoleRequest $request
* @return array
*/
#[RequestMapping(path: "{id}/permission", methods: "PUT")]
#[Permission(code: 'permission:role:setMenu')]
#[Scene(scene: "batch_grant_permission")]
public function batchGrantPermissionByRole(int $id,AdminRoleRequest $request): array
{
return $this->service->setRole($id);
}
}

View File

@@ -6,20 +6,23 @@ namespace App\Controller\Admin;
use App\Annotation\Permission; use App\Annotation\Permission;
use App\Annotation\ResponseFormat; use App\Annotation\ResponseFormat;
use App\Controller\AbstractController;
use App\Middleware\Admin\AdminTokenMiddleware; use App\Middleware\Admin\AdminTokenMiddleware;
use App\Middleware\Admin\PermissionMiddleware; use App\Middleware\Admin\PermissionMiddleware;
use App\Request\Admin\AdminUserRequest;
use App\Service\Admin\AdminUser\UserService; use App\Service\Admin\AdminUser\UserService;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware; use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping; use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Validation\Annotation\Scene;
#[Controller(prefix: "admin/adminUser")] #[Controller(prefix: "admin/adminUser")]
#[ResponseFormat('admin')] #[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)] #[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
#[Middleware(middleware: PermissionMiddleware::class, priority: 99)] #[Middleware(middleware: PermissionMiddleware::class, priority: 99)]
class AdminUserController class AdminUserController extends AbstractController
{ {
/** /**
* @var UserService * @var UserService
@@ -56,11 +59,13 @@ class AdminUserController
} }
/** /**
* @param AdminUserRequest $request
* @return array * @return array
*/ */
#[RequestMapping(path: "", methods: "PUT")] #[RequestMapping(path: "", methods: "PUT")]
#[Permission(code: 'permission:user:update')] #[Permission(code: 'permission:user:update')]
public function updateInfo(): array #[Scene(scene: "update")]
public function updateInfo(AdminUserRequest $request): array
{ {
return $this->service->updateInfo(); return $this->service->updateInfo();
} }
@@ -76,11 +81,13 @@ class AdminUserController
} }
/** /**
* @param AdminUserRequest $request
* @return array * @return array
*/ */
#[RequestMapping(path: "", methods: "POST")] #[RequestMapping(path: "", methods: "POST")]
#[Permission(code: 'permission:user:save')] #[Permission(code: 'permission:user:save')]
public function createAdminUser(): array #[Scene(scene: "create")]
public function createAdminUser(AdminUserRequest $request): array
{ {
return $this->service->createUser(); return $this->service->createUser();
} }
@@ -97,7 +104,8 @@ class AdminUserController
#[RequestMapping(path: "{userId}", methods: "PUT")] #[RequestMapping(path: "{userId}", methods: "PUT")]
#[Permission(code: 'permission:user:update')] #[Permission(code: 'permission:user:update')]
public function saveInfo(int $userId): array #[Scene(scene: "update")]
public function saveInfo(int $userId,AdminUserRequest $request): array
{ {
return $this->service->saveUser($userId); return $this->service->saveUser($userId);
} }
@@ -115,11 +123,13 @@ class AdminUserController
/** /**
* @param int $userId * @param int $userId
* @param AdminUserRequest $request
* @return array * @return array
*/ */
#[RequestMapping(path: "{userId}/roles", methods: "PUT")] #[RequestMapping(path: "{userId}/roles", methods: "PUT")]
#[Permission(code: 'permission:user:setRole')] #[Permission(code: 'permission:user:setRole')]
public function batchGrantRolesForAdminUser(int $userId): array #[Scene(scene: "batch_grant_role")]
public function batchGrantRolesForAdminUser(int $userId,AdminUserRequest $request): array
{ {
return $this->service->batchGrantRoleForUser($userId); return $this->service->batchGrantRoleForUser($userId);
} }

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Log;
use App\Annotation\Permission;
use App\Annotation\ResponseFormat;
use App\Controller\AbstractController;
use App\Middleware\Admin\AdminTokenMiddleware;
use App\Middleware\Admin\PermissionMiddleware;
use App\Service\Admin\Log\AdminUserLoginLogService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
#[Controller(prefix: "admin/user-login-log")]
#[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
#[Middleware(middleware: PermissionMiddleware::class, priority: 99)]
class AdminUserLoginLogController extends AbstractController
{
/**
* @var AdminUserLoginLogService
*/
#[Inject]
protected AdminUserLoginLogService $service;
/**
* @return array
*/
#[RequestMapping(path: "list", methods: "GET")]
#[Permission(code: 'log:userLogin:list')]
public function pageList(): array
{
return $this->service->handle();
}
/**
* @return array
*/
#[RequestMapping(path: "", methods: "DELETE")]
#[Permission(code: 'log:userLogin:delete')]
public function delete(): array
{
return $this->service->deleteLog();
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Log;
use App\Annotation\Permission;
use App\Annotation\ResponseFormat;
use App\Controller\AbstractController;
use App\Middleware\Admin\AdminTokenMiddleware;
use App\Middleware\Admin\PermissionMiddleware;
use App\Service\Admin\Log\AdminUserOperationLogService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
#[Controller(prefix: "admin/user-operation-log")]
#[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
#[Middleware(middleware: PermissionMiddleware::class, priority: 99)]
class AdminUserOperationLogController extends AbstractController
{
/**
* @var AdminUserOperationLogService
*/
#[Inject]
protected AdminUserOperationLogService $service;
/**
* @return array
*/
#[RequestMapping(path: "list", methods: "GET")]
#[Permission(code: 'log:userOperation:list')]
public function pageList(): array
{
return $this->service->handle();
}
/**
* @return array
*/
#[RequestMapping(path: "", methods: "DELETE")]
#[Permission(code: 'log:userOperation:delete')]
public function delete(): array
{
return $this->service->deleteLog();
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin;
use App\Annotation\Permission;
use App\Annotation\ResponseFormat;
use App\Controller\AbstractController;
use App\Middleware\Admin\AdminTokenMiddleware;
use App\Request\Admin\PermissionRequest;
use App\Service\Admin\AdminUser\PermissionService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Validation\Annotation\Scene;
#[Controller(prefix: "admin/permission")]
#[ResponseFormat('admin')]
#[Middleware(middleware: AdminTokenMiddleware::class, priority: 100)]
class PermissionController extends AbstractController
{
/**
* @var PermissionService
*/
#[Inject]
protected PermissionService $service;
/**
* @return array
*/
#[RequestMapping(path: "menus", methods: "GET")]
public function menus(): array
{
return $this->service->handle();
}
/**
* @return array
*/
#[RequestMapping(path: "roles", methods: "GET")]
public function roles(): array
{
return $this->service->getRoleByAdminUser();
}
/**
* @param PermissionRequest $request
* @return array
*/
#[RequestMapping(path: "update", methods: "POST")]
#[Scene(scene: "update")]
public function update(PermissionRequest $request): array
{
return $this->service->update();
}
}

View File

@@ -2,9 +2,7 @@
namespace App\Lib\Jwt; namespace App\Lib\Jwt;
use App\Constants\ResultCode; use App\Common\Interface\JwtInterface;
use App\Exception\ErrException;
use App\Interface\JwtInterface;
use Carbon\Carbon; use Carbon\Carbon;
use Hyperf\Cache\CacheManager; use Hyperf\Cache\CacheManager;
use Hyperf\Cache\Driver\DriverInterface; use Hyperf\Cache\Driver\DriverInterface;
@@ -18,7 +16,6 @@ use Lcobucci\JWT\UnencryptedToken;
use Lcobucci\JWT\Validation\Constraint; use Lcobucci\JWT\Validation\Constraint;
use Lcobucci\JWT\Validation\Constraint\SignedWith; use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\Constraint\StrictValidAt; use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Psr\SimpleCache\InvalidArgumentException; use Psr\SimpleCache\InvalidArgumentException;
abstract class AbstractJwt implements JwtInterface abstract class AbstractJwt implements JwtInterface

View File

@@ -2,6 +2,6 @@
namespace App\Lib\Jwt; namespace App\Lib\Jwt;
use App\Interface\JwtInterface; use App\Common\Interface\JwtInterface;
final class Jwt extends AbstractJwt implements JwtInterface {} final class Jwt extends AbstractJwt implements JwtInterface {}

View File

@@ -2,7 +2,7 @@
namespace App\Lib\Jwt; namespace App\Lib\Jwt;
use App\Interface\JwtInterface; use App\Common\Interface\JwtInterface;
use Hyperf\Collection\Arr; use Hyperf\Collection\Arr;
use Hyperf\Contract\ConfigInterface; use Hyperf\Contract\ConfigInterface;
use function Hyperf\Support\make; use function Hyperf\Support\make;

View File

@@ -4,10 +4,11 @@ declare(strict_types=1);
namespace App\Middleware\Admin; namespace App\Middleware\Admin;
use App\Common\Interface\JwtInterface;
use App\Constants\ResultCode; use App\Constants\ResultCode;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Interface\JwtInterface;
use App\Middleware\Token\AbstractTokenMiddleware; use App\Middleware\Token\AbstractTokenMiddleware;
use Hyperf\Context\Context;
use Lcobucci\JWT\Token\RegisteredClaims; use Lcobucci\JWT\Token\RegisteredClaims;
use Lcobucci\JWT\UnencryptedToken; use Lcobucci\JWT\UnencryptedToken;
use function Hyperf\Support\env; use function Hyperf\Support\env;
@@ -29,4 +30,13 @@ final class AdminTokenMiddleware extends AbstractTokenMiddleware
if ($audience !== env('APP_NAME') .'_admin') throw new ErrException('token错误',ResultCode::JWT_ERROR); if ($audience !== env('APP_NAME') .'_admin') throw new ErrException('token错误',ResultCode::JWT_ERROR);
} }
/**
* @param UnencryptedToken $token
* @return void
*/
public function setContext(UnencryptedToken $token): void
{
Context::set('current_admin_id',(int)$token->claims()?->get(RegisteredClaims::ID) ?? 0);
}
} }

View File

@@ -5,21 +5,21 @@ declare(strict_types=1);
namespace App\Middleware\Admin; namespace App\Middleware\Admin;
use App\Annotation\Permission; use App\Annotation\Permission;
use App\Common\Trait\AdminUserTrait;
use App\Common\Trait\ParserRouterTrait;
use App\Constants\AdminCode; use App\Constants\AdminCode;
use App\Constants\Model\AdminUser\AdminUserStatusCode; use App\Constants\Model\AdminUser\AdminUserStatusCode;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Lib\Jwt\RequestScopedTokenTrait; use App\Lib\Jwt\RequestScopedTokenTrait;
use App\Model\AdminUser; use App\Model\AdminUser;
use App\Trait\AdminUserTrait;
use App\Trait\ParserRouterTrait;
use Hyperf\Collection\Arr; use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\AnnotationCollector; use Hyperf\Di\Annotation\AnnotationCollector;
use Hyperf\HttpServer\Router\Dispatched; use Hyperf\HttpServer\Router\Dispatched;
use Lcobucci\JWT\Token\RegisteredClaims; use Lcobucci\JWT\Token\RegisteredClaims;
use Psr\Container\ContainerInterface; use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface; use Psr\Http\Server\RequestHandlerInterface;
class PermissionMiddleware implements MiddlewareInterface class PermissionMiddleware implements MiddlewareInterface
@@ -45,7 +45,7 @@ class PermissionMiddleware implements MiddlewareInterface
*/ */
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{ {
$adminId = $this->getToken()?->claims()?->get(RegisteredClaims::ID) ?? 0; $adminId = (int) $this->getToken()?->claims()?->get(RegisteredClaims::ID) ?? 0;
if ($adminId <= 0) throw new ErrException('账户不存在'); if ($adminId <= 0) throw new ErrException('账户不存在');
$this->adminUserInfo = $this->getAdminUserInfo($adminId); $this->adminUserInfo = $this->getAdminUserInfo($adminId);
@@ -74,6 +74,7 @@ class PermissionMiddleware implements MiddlewareInterface
/** /**
* @var Permission[] $permissions * @var Permission[] $permissions
*/ */
$permissions = [];
$classAnnotation && $permissions[] = $classAnnotation; $classAnnotation && $permissions[] = $classAnnotation;
$methodPermission = Arr::get($annotations, Permission::class); $methodPermission = Arr::get($annotations, Permission::class);
$methodPermission && $permissions[] = $methodPermission; $methodPermission && $permissions[] = $methodPermission;

View File

@@ -4,9 +4,9 @@ declare(strict_types=1);
namespace App\Middleware\Admin; namespace App\Middleware\Admin;
use App\Common\Interface\JwtInterface;
use App\Constants\ResultCode; use App\Constants\ResultCode;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Interface\JwtInterface;
use App\Middleware\Token\AbstractTokenMiddleware; use App\Middleware\Token\AbstractTokenMiddleware;
use Lcobucci\JWT\Token\RegisteredClaims; use Lcobucci\JWT\Token\RegisteredClaims;
use Lcobucci\JWT\UnencryptedToken; use Lcobucci\JWT\UnencryptedToken;
@@ -68,4 +68,13 @@ class RefreshAdminTokenMiddleware extends AbstractTokenMiddleware
if ($audience !== env('APP_NAME') .'_admin') throw new ErrException('token错误',ResultCode::JWT_ERROR); if ($audience !== env('APP_NAME') .'_admin') throw new ErrException('token错误',ResultCode::JWT_ERROR);
} }
/**
* @param UnencryptedToken $token
* @return void
*/
public function setContext(UnencryptedToken $token): void
{
return;
}
} }

View File

@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace App\Middleware\Token; namespace App\Middleware\Token;
use App\Common\Interface\CheckTokenInterface;
use App\Common\Interface\JwtInterface;
use App\Constants\ResultCode; use App\Constants\ResultCode;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Interface\CheckTokenInterface;
use App\Interface\JwtInterface;
use App\Lib\Jwt\JwtFactory; use App\Lib\Jwt\JwtFactory;
use Hyperf\Collection\Arr; use Hyperf\Collection\Arr;
use Hyperf\Stringable\Str; use Hyperf\Stringable\Str;
@@ -35,6 +35,8 @@ abstract class AbstractTokenMiddleware
$this->checkToken->checkJwt($token); $this->checkToken->checkJwt($token);
$this->checkIssuer($token); $this->checkIssuer($token);
$this->setContext($token);
return $handler->handle( return $handler->handle(
value( value(
static function (ServerRequestPlusInterface $request, UnencryptedToken $token) { static function (ServerRequestPlusInterface $request, UnencryptedToken $token) {
@@ -54,6 +56,12 @@ abstract class AbstractTokenMiddleware
abstract public function getJwt(): JwtInterface; abstract public function getJwt(): JwtInterface;
/**
* @param UnencryptedToken $token
* @return void
*/
abstract public function setContext(UnencryptedToken $token): void;
/** /**
* @param ServerRequestInterface $request * @param ServerRequestInterface $request
* @return Token * @return Token

View File

@@ -85,8 +85,8 @@ class AdminMenu extends Model
return $this->belongsToMany( return $this->belongsToMany(
AdminRole::class, AdminRole::class,
'admin_role_belongs_menu', 'admin_role_belongs_menu',
'menu_id', 'admin_menu_id',
'role_id' 'admin_role_id'
); );
} }

View File

@@ -65,9 +65,9 @@ class AdminRole extends Model
{ {
return $this->belongsToMany( return $this->belongsToMany(
AdminMenu::class, AdminMenu::class,
'role_belongs_menu', 'admin_role_belongs_menu',
'role_id', 'admin_role_id',
'menu_id' 'admin_menu_id'
); );
} }
@@ -79,8 +79,8 @@ class AdminRole extends Model
return $this->belongsToMany( return $this->belongsToMany(
AdminUser::class, AdminUser::class,
'admin_user_belongs_role', 'admin_user_belongs_role',
'role_id', 'admin_role_id',
'user_id' 'admin_user_id'
); );
} }

View File

@@ -6,6 +6,9 @@ namespace App\Model;
use Carbon\Carbon;
use Hyperf\Database\Model\Events\Creating;
/** /**
* @property int $id * @property int $id
* @property int $admin_user_id * @property int $admin_user_id
@@ -20,6 +23,9 @@ namespace App\Model;
*/ */
class AdminUserLoginLog extends Model class AdminUserLoginLog extends Model
{ {
public bool $timestamps = false;
/** /**
* The table associated with the model. * The table associated with the model.
*/ */
@@ -28,10 +34,21 @@ class AdminUserLoginLog extends Model
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
*/ */
protected array $fillable = []; protected array $fillable = ['id','admin_user_id', 'username', 'ip', 'os', 'browser', 'status', 'message', 'login_time', 'remark'];
/** /**
* The attributes that should be cast to native types. * The attributes that should be cast to native types.
*/ */
protected array $casts = ['id' => 'integer', 'admin_user_id' => 'integer', 'status' => 'integer']; protected array $casts = ['id' => 'integer', 'admin_user_id' => 'integer', 'status' => 'integer'];
/**
* @param Creating $event
* @return void
*/
public function creating(Creating $event): void
{
if ($event->getModel()->login_time === null) {
$event->getModel()->login_time = Carbon::now();
}
}
} }

View File

@@ -28,7 +28,7 @@ class AdminUserOperationLog extends Model
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
*/ */
protected array $fillable = []; protected array $fillable = ['id', 'admin_user_id','username', 'method', 'router', 'service_name', 'ip', 'ip_location', 'created_at', 'updated_at', 'remark'];
/** /**
* The attributes that should be cast to native types. * The attributes that should be cast to native types.

View File

@@ -1,18 +0,0 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Repository;
use App\Model\AdminRole;
final class AdminRoleRepository extends BaseRepository
{
public function __construct(protected readonly AdminRole $model) {}
}

View File

@@ -1,37 +0,0 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Repository;
use App\Model\AdminUser;
use Hyperf\Database\Concerns\BuildsQueries;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
/**
* Class AdminUserRepository
* @extends BaseRepository<AdminUser>
*/
final class AdminUserRepository extends BaseRepository
{
public function __construct(protected readonly AdminUser $model) {}
/**
* @param string $username
* @return AdminUser|null
*/
public function findByUserName(string $username): AdminUser|null
{
// @phpstan-ignore-next-line
return $this->model->newQuery()
->where('username', $username)
->first();
}
}

View File

@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace App\Request\Admin;
use Hyperf\Validation\Request\FormRequest;
class AdminMenuRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'parent_id' => 'sometimes|integer',
'name' => 'required|string|max:255',
'path' => 'sometimes|string|max:255',
'component' => 'sometimes|string|max:255',
'redirect' => 'sometimes|string|max:255',
'status' => 'sometimes|integer',
'sort' => 'sometimes|integer',
'remark' => 'sometimes|string|max:255',
'meta.title' => 'required|string|max:255',
'meta.i18n' => 'sometimes|string|max:255',
'meta.badge' => 'sometimes|string|max:255',
'meta.link' => 'sometimes|string|max:255',
'meta.icon' => 'sometimes|string|max:255',
'meta.affix' => 'sometimes|boolean',
'meta.hidden' => 'sometimes|boolean',
'meta.type' => 'sometimes|string|max:255',
'meta.cache' => 'sometimes|boolean',
'meta.breadcrumbEnable' => 'sometimes|boolean',
'meta.copyright' => 'sometimes|boolean',
'meta.componentPath' => 'sometimes|string|max:64',
'meta.componentSuffix' => 'sometimes|string|max:4',
'meta.activeName' => 'sometimes|string|max:255',
'btnPermission' => 'sometimes|array',
];
}
/**
* @return array
*/
public function messages(): array
{
return parent::messages();
}
/**
* @var array|array[]
*/
protected array $scenes = [
'update' => [
'parent_id',
'name',
'path',
'component',
'redirect',
'status',
'sort',
'remark',
'meta.title',
'meta.i18n',
'meta.badge',
'meta.link',
'meta.icon',
'meta.affix',
'meta.hidden',
'meta.type',
'meta.cache',
'meta.breadcrumbEnable',
'meta.copyright',
'meta.componentPath',
'meta.componentSuffix',
'meta.activeName',
'btnPermission',
],
'create' => [
'parent_id',
'name',
'path',
'component',
'redirect',
'status',
'sort',
'remark',
'meta.title',
'meta.i18n',
'meta.badge',
'meta.link',
'meta.icon',
'meta.affix',
'meta.hidden',
'meta.type',
'meta.cache',
'meta.breadcrumbEnable',
'meta.copyright',
'meta.componentPath',
'meta.componentSuffix',
'meta.activeName',
'btnPermission',
],
];
}

View File

@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace App\Request\Admin;
use App\Common\Trait\HttpMethodTrait;
use Hyperf\Validation\Request\FormRequest;
class AdminRoleRequest extends FormRequest
{
use HttpMethodTrait;
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
$rules = [
'name' => 'required|string|max:60',
'code' => [
'required',
'string',
'max:60',
'regex:/^[a-zA-Z0-9_]+$/',
],
'status' => 'sometimes|integer|in:1,2',
'sort' => 'required|integer',
'remark' => 'nullable|string|max:255',
'permissions' => 'sometimes|array',
'permissions.*' => 'string|exists:admin_menu,name',
];
if ($this->isCreate()) {
$rules['code'][] = 'unique:admin_role,code';
}
if ($this->isUpdate()) {
$rules['code'][] = 'unique:admin_role,code,' . $this->route('id');
}
return $rules;
}
/**
* @return array
*/
public function messages(): array
{
return parent::messages();
}
protected array $scenes = [
'update' => [
'code',
'name',
'status',
'sort',
'remark',
],
'create' => [
'code',
'name',
'status',
'sort',
'remark',
],
'batch_grant_permission' => [
'permissions',
'permissions.*',
]
];
}

View File

@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Request\Admin;
use Hyperf\Validation\Request\FormRequest;
class AdminUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'username' => 'required|string|max:20',
'user_type' => 'required|integer',
'nickname' => ['required', 'string', 'max:60', 'regex:/^[^\s]+$/'],
'phone' => 'sometimes|string|max:12',
'email' => 'sometimes|string|max:60|email:rfc,dns',
'avatar' => 'sometimes|string|max:255|url',
'signed' => 'sometimes|string|max:255',
'status' => 'sometimes|integer',
'backend_setting' => 'sometimes|array|max:255',
'remark' => 'sometimes|string|max:255',
'password' => 'sometimes|string|min:6|max:20',
'role_codes' => 'required|array',
'role_codes.*' => 'string|exists:admin_role,code',
];
}
/**
* @return array
*/
public function messages(): array
{
return parent::messages();
}
protected array $scenes = [
'update' => [
'username',
'user_type',
'nickname',
'phone',
'email',
'avatar',
'signed',
'status',
'backend_setting',
'remark',
'password',
],
'create' => [
'username',
'user_type',
'nickname',
'phone',
'email',
'avatar',
'signed',
'status',
'backend_setting',
'remark',
'password',
],
'batch_grant_role' => [
'role_codes',
'role_codes.*',
]
];
}

View File

@@ -22,7 +22,20 @@ class LoginRequest extends FormRequest
public function rules(): array public function rules(): array
{ {
return [ return [
'username' => 'required|string|exists:admin_user,username',
'password' => 'required|string'
]; ];
} }
/**
* @return array
*/
public function messages(): array
{
return parent::messages();
}
protected array $scenes = [
'login' => ['username', 'password'],
];
} }

View File

@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Request\Admin;
use Hyperf\Validation\Request\FormRequest;
class PermissionRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'nickname' => 'sometimes|string|max:255',
'new_password' => 'sometimes|confirmed|string|min:8',
'new_password_confirmation' => 'sometimes|string|min:8',
'old_password' => ['sometimes', 'string'],
'avatar' => 'sometimes|string|max:255',
'signed' => 'sometimes|string|max:255',
'backend_setting' => 'sometimes|array',
];
}
/**
* @return array
*/
public function messages(): array
{
return parent::messages();
}
/**
* @var array|array[]
*/
protected array $scenes = [
'update' => [
'nickname',
'new_password',
'new_password_confirmation',
'old_password',
'avatar',
'signed',
'backend_setting',
],
];
}

View File

@@ -0,0 +1,137 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Admin\AdminUser;
use App\Common\Repository\AdminMenuRepository;
use App\Exception\ErrException;
use App\Model\AdminMenu;
use App\Service\Admin\BaseAdminService;
use Hyperf\Di\Annotation\Inject;
class MenuService extends BaseAdminService
{
/**
* @var AdminMenuRepository
*/
#[Inject]
protected AdminMenuRepository $adminMenuRepository;
/**
* @return array
*/
public function handle(): array
{
return $this->adminReturn->success('success',$this->adminMenuRepository->list([
'children' => true,
'parent_id' => 0
])?->toArray() ?? []);
}
/**
* @return array
*/
public function create(): array
{
$data = array_merge($this->getRequestData(),[
'created_by' => $this->adminId
]);
if (empty($data['parent_id'])) $data['parent_id'] = 0;
/**
* @var AdminMenu $model
*/
$model = $this->adminMenuRepository->create($data);
if (!$model) throw new ErrException('添加失败');
if ($data['meta']['type'] !== 'M' || empty($data['btnPermission'])) return $this->adminReturn->success('success',$model->toArray());
foreach ($data['btnPermission'] as $item) {
$this->adminMenuRepository->create([
'parent_id' => $model->id,
'name' => $item['code'],
'sort' => 0,
'status' => 1,
'meta' => [
'title' => $item['title'],
'i18n' => $item['i18n'],
'type' => 'B'
],
]);
}
return $this->adminReturn->success('success',$model->toArray());
}
/**
* @param int $id
* @return array
*/
public function update(int $id): array
{
$data = array_merge($this->getRequestData(),[
'updated_by' => $this->adminId
]);
$model = $this->adminMenuRepository->updateById($id, $data);
if (!$model) throw new ErrException('修改失败');
if ($data['meta']['type'] !== 'M' || !isset($data['btnPermission'])) return $this->adminReturn->success();
$existsBtnPermissions = array_flip(
$this->adminMenuRepository
->getQuery()
->where('parent_id', $id)
->whereJsonContains('meta->type', 'B')
->pluck('id')
->toArray()
);
if (!empty($data['btnPermission'])) {
foreach ($data['btnPermission'] as $item) {
if (empty($item['type']) || $item['type'] !== 'B') continue;
$data = [
'name' => $item['code'],
'meta' => [
'title' => $item['title'],
'i18n' => $item['i18n'],
'type' => 'B'
],
];
if (!empty($item['id'])) {
$this->adminMenuRepository->updateById($item['id'], $data);
unset($existsBtnPermissions[$item['id']]);
} else {
$data['parent_id'] = $id;
$this->adminMenuRepository->create($data);
}
}
}
if (!empty($existsBtnPermissions)) $this->adminMenuRepository->deleteById(array_keys($existsBtnPermissions));
return $this->adminReturn->success();
}
/**
* @return array
*/
public function delete(): array
{
$res = $this->adminMenuRepository->deleteById($this->getRequestData());
if (!$res) throw new ErrException('删除失败');
return $this->adminReturn->success();
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Admin\AdminUser;
use App\Common\Repository\AdminMenuRepository;
use App\Common\Repository\AdminRoleRepository;
use App\Common\Trait\AdminUserTrait;
use App\Constants\Model\AdminUser\AdminMenuStatusCode;
use App\Constants\Model\AdminUser\AdminRoleStatusCode;
use App\Constants\ResultCode;
use App\Exception\ErrException;
use App\Service\Admin\BaseAdminService;
use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\Inject;
class PermissionService extends BaseAdminService
{
use AdminUserTrait;
/**
* @var AdminRoleRepository
*/
#[Inject]
protected AdminRoleRepository $adminRoleRepository;
/**
* @var AdminMenuRepository
*/
#[Inject]
protected AdminMenuRepository $adminMenuRepository;
/**
* @return array
*/
public function handle(): array
{
return $this->adminReturn->success(
'success',
$this->getAdminUserInfo($this->adminId)->isSuperAdmin() ?
$this->getAdminMenuBySuperAdmin() :
$this->getAdminMenuByAdminId()
);
}
/**
* @return array
*/
private function getAdminMenuByAdminId(): array
{
$permissions = $this->getAdminUserInfo($this->adminId)->getPermissions()->pluck('name')->unique();
$menuList = $permissions->isEmpty() ?
[] :
$this->adminMenuRepository->list([
'status' => AdminMenuStatusCode::Normal,
'name' => $permissions->toArray()
])->toArray();
$tree = [];
$map = [];
foreach ($menuList as &$menu) {
$menu['children'] = [];
$map[$menu['id']] = &$menu;
}
unset($menu);
foreach ($menuList as &$menu) {
$pid = $menu['parent_id'];
if ($pid === 0 || !isset($map[$pid])) {
$tree[] = &$menu;
} else {
$map[$pid]['children'][] = &$menu;
}
}
unset($menu);
return $tree;
}
/**
* @return array
*/
private function getAdminMenuBySuperAdmin(): array
{
return $this->adminMenuRepository->list([
'status' => AdminMenuStatusCode::Normal,
'children' => true,
'parent_id' => 0,
])?->toArray() ?? [];
}
/**
* @return array
*/
public function getRoleByAdminUser(): array
{
return $this->adminReturn->success(
'success',
$this->getAdminUserInfo($this->adminId)->isSuperAdmin() ?
$this->adminRoleRepository->list(['status' => AdminRoleStatusCode::Normal])->toArray() :
$this->getAdminUserInfo($this->adminId)->getRoles(['name', 'code', 'remark'])->toArray()
);
}
/**
* @return array
*/
public function update(): array
{
$userInfo = $this->getAdminUserInfo($this->adminId);
if (!$userInfo) throw new ErrException('用户不存在');
$data = $this->getRequestData();
if (Arr::exists($data, 'new_password')) {
if (!$userInfo->verifyPassword(Arr::get($data,'old_password')))
throw new ErrException('旧密码错误',ResultCode::OLD_PASSWORD_ERROR);
$data['password'] = $data['new_password'];
}
if (!$this->adminUserRepository->updateById($userInfo->id, $data)) throw new ErrException('更新失败');
return $this->adminReturn->success();
}
}

View File

@@ -0,0 +1,139 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Admin\AdminUser;
use App\Common\Repository\AdminMenuRepository;
use App\Common\Repository\AdminRoleRepository;
use App\Exception\ErrException;
use App\Model\AdminMenu;
use App\Service\Admin\BaseAdminService;
use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\Inject;
class RoleService extends BaseAdminService
{
/**
* @var AdminRoleRepository
*/
#[Inject]
protected AdminRoleRepository $adminRoleRepository;
/**
* @var AdminMenuRepository
*/
#[Inject]
protected AdminMenuRepository $adminMenuRepository;
/**
* @return array
*/
public function handle(): array
{
return $this->adminReturn->success(
'success',
$this->adminRoleRepository->page(
$this->getRequestData(),
$this->getCurrentPage(),
$this->getPageSize()
)
);
}
/**
* @return array
*/
public function create(): array
{
if (!$this->adminRoleRepository->create(
array_merge(
$this->getRequestData(),
['created_by' => $this->adminId]
)
)) throw new ErrException('添加失败');
return $this->adminReturn->success();
}
/**
* @param int $id
* @return array
*/
public function update(int $id): array
{
if (!$this->adminRoleRepository->updateById(
$id,
array_merge(
$this->getRequestData(),
['updated_by' => $this->adminId]
)
)) throw new ErrException('更新失败');
return $this->adminReturn->success();
}
/**
* @return array
*/
public function delete(): array
{
if (!$this->adminRoleRepository->deleteById($this->getRequestData())) throw new ErrException('删除失败');
return $this->adminReturn->success();
}
/**
* @param int $id
* @return array
*/
public function getRole(int $id): array
{
return $this->adminReturn->success(
'success',
$this->adminRoleRepository
->findById($id)
->adminMenus()
->get()
->map(static fn (AdminMenu $adminMenu) => $adminMenu->only([
'id' , 'name'
]))->toArray()
);
}
/**
* @param int $id
* @return array
*/
public function setRole(int $id): array
{
if (!$this->adminRoleRepository->existsById($id)) throw new ErrException('角色不存在');
$permissionsCode = Arr::get($this->getRequestData(), 'permissions', []);
if (count($permissionsCode) === 0) {
$this->adminRoleRepository->findById($id)->adminMenus()->detach();
return $this->adminReturn->success();
}
if (!$this->adminRoleRepository
->findById($id)
->adminMenus()
->sync(
$this->adminMenuRepository
->list([
'code' => $permissionsCode
])
->map(static fn ($item) => $item->id)
->toArray()
)) throw new ErrException('更新失败');
return $this->adminReturn->success();
}
}

View File

@@ -12,17 +12,15 @@ namespace App\Service\Admin\AdminUser;
use App\Cache\Redis\Lua\RateLimit; use App\Cache\Redis\Lua\RateLimit;
use App\Cache\Redis\RedisCache; use App\Cache\Redis\RedisCache;
use App\Common\Repository\AdminRoleRepository;
use App\Common\Repository\AdminUserRepository;
use App\Common\Trait\AdminUserTrait;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Lib\Jwt\RequestScopedTokenTrait;
use App\Model\AdminRole; use App\Model\AdminRole;
use App\Repository\AdminRoleRepository;
use App\Repository\AdminUserRepository;
use App\Service\Admin\BaseAdminService; use App\Service\Admin\BaseAdminService;
use App\Service\BaseTokenService; use App\Service\BaseTokenService;
use App\Trait\AdminUserTrait;
use Hyperf\Collection\Arr; use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
use Lcobucci\JWT\Token\RegisteredClaims;
class UserService extends BaseAdminService class UserService extends BaseAdminService
{ {
@@ -46,21 +44,15 @@ class UserService extends BaseAdminService
#[Inject] #[Inject]
protected AdminRoleRepository $adminRoleRepository; protected AdminRoleRepository $adminRoleRepository;
#[Inject]
protected RedisCache $redisCache;
/** /**
* @return array * @return array
*/ */
public function handle(): array public function handle(): array
{ {
$this->redisCache->with()->set('123',1);
$this->redisCache->with()->lua(RateLimit::class)->check('user:123', 10, 60);
return $this->adminReturn->success( return $this->adminReturn->success(
'success', 'success',
Arr::only( Arr::only(
$this->getAdminUserInfo($this->adminId) ?: [], $this->getAdminUserInfo($this->adminId)?->toArray() ?: [],
['username', 'nickname', 'avatar', 'signed', 'backend_setting', 'phone', 'email'] ['username', 'nickname', 'avatar', 'signed', 'backend_setting', 'phone', 'email']
) )
); );
@@ -190,7 +182,7 @@ class UserService extends BaseAdminService
'code' => $this->request->input('role_codes') 'code' => $this->request->input('role_codes')
])->map(static function(AdminRole $adminRole) { ])->map(static function(AdminRole $adminRole) {
return $adminRole->id; return $adminRole->id;
})->all() })
); );
return $this->adminReturn->success(); return $this->adminReturn->success();

View File

@@ -10,12 +10,12 @@ declare(strict_types=1);
namespace App\Service\Admin; namespace App\Service\Admin;
use App\Exception\ErrException;
use App\Lib\Jwt\RequestScopedTokenTrait; use App\Lib\Jwt\RequestScopedTokenTrait;
use App\Lib\Return\AdminReturn; use App\Lib\Return\AdminReturn;
use Hyperf\Context\Context; use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\RequestInterface;
use Lcobucci\JWT\Token\RegisteredClaims;
abstract class BaseAdminService abstract class BaseAdminService
{ {
@@ -36,20 +36,27 @@ abstract class BaseAdminService
protected AdminReturn $adminReturn; protected AdminReturn $adminReturn;
/** /**
* 管理员 id * @param string $name
* @var int * @return \current_admin_id|mixed
*/ */
protected int $adminId = 0; public function __get(string $name)
/**
* 主构造函数
*/
public function __construct()
{ {
$this->adminId = (int) $this->getToken()?->claims()?->get(RegisteredClaims::ID) ?? 0; if ($name === 'adminId') return Context::get('current_admin_id',0);
if ($this->adminId > 0) Context::set('current_admin_id', $this->adminId);
if (!property_exists($this, $name)) throw new ErrException('属性未定义');
return $this->$name;
} }
// /**
// * 主构造函数
// */
// public function __construct()
// {
// $this->adminId = Context::get('current_admin_id',0);
// var_dump('BaseAdminService获取到的'.$this->adminId);
// }
/** /**
* 主函数抽象类 * 主函数抽象类
*/ */

View File

@@ -0,0 +1,51 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Admin\Log;
use App\Common\Repository\AdminUserLoginLogRepository;
use App\Exception\ErrException;
use App\Service\Admin\BaseAdminService;
use Hyperf\Di\Annotation\Inject;
class AdminUserLoginLogService extends BaseAdminService
{
/**
* @var AdminUserLoginLogRepository
*/
#[Inject]
protected AdminUserLoginLogRepository $adminUserLoginLogRepository;
/**
* @return array
*/
public function handle(): array
{
return $this->adminReturn->success(
'success',
$this->adminUserLoginLogRepository->page(
$this->getRequestData(),
$this->getCurrentPage(),
$this->getPageSize()
)
);
}
/**
* @return array
*/
public function deleteLog(): array
{
if (!$this->adminUserLoginLogRepository->deleteById($this->request->input('ids')))
throw new ErrException('删除失败');
return $this->adminReturn->success();
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Admin\Log;
use App\Common\Repository\AdminUserOperationLogRepository;
use App\Exception\ErrException;
use App\Service\Admin\BaseAdminService;
use Hyperf\Di\Annotation\Inject;
class AdminUserOperationLogService extends BaseAdminService
{
/**
* @var AdminUserOperationLogRepository
*/
#[Inject]
protected AdminUserOperationLogRepository $adminUserOperationLogRepository;
/**
* @return array
*/
public function handle(): array
{
return $this->adminReturn->success(
'success',
$this->adminUserOperationLogRepository->page(
$this->getRequestData(),
$this->getCurrentPage(),
$this->getPageSize()
)
);
}
/**
* @return array
*/
public function deleteLog(): array
{
if (!$this->adminUserOperationLogRepository->deleteById($this->request->input('ids')))
throw new ErrException('删除失败');
return $this->adminReturn->success();
}
}

View File

@@ -10,11 +10,9 @@ declare(strict_types=1);
namespace App\Service\Admin\Login; namespace App\Service\Admin\Login;
use App\Common\Repository\AdminUserRepository;
use App\Constants\Model\AdminUser\AdminUserStatusCode; use App\Constants\Model\AdminUser\AdminUserStatusCode;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Interface\JwtInterface;
use App\Lib\Jwt\JwtFactory;
use App\Repository\AdminUserRepository;
use App\Service\Admin\BaseAdminService; use App\Service\Admin\BaseAdminService;
use App\Service\BaseTokenService; use App\Service\BaseTokenService;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
@@ -48,7 +46,6 @@ class LoginService extends BaseAdminService
} }
if ($adminInfo->status == AdminUserStatusCode::DISABLE) throw new ErrException('用户已禁用'); if ($adminInfo->status == AdminUserStatusCode::DISABLE) throw new ErrException('用户已禁用');
$jwtHandle = $this->tokenService->setJwt('admin')->getJwt(); $jwtHandle = $this->tokenService->setJwt('admin')->getJwt();
return $this->adminReturn->success('success',[ return $this->adminReturn->success('success',[

View File

@@ -10,13 +10,13 @@ declare(strict_types=1);
namespace App\Service; namespace App\Service;
use App\Common\Interface\CheckTokenInterface;
use App\Common\Interface\JwtInterface;
use App\Exception\ErrException; use App\Exception\ErrException;
use App\Interface\CheckTokenInterface;
use App\Lib\Jwt\JwtFactory; use App\Lib\Jwt\JwtFactory;
use Hyperf\Di\Annotation\Inject; use Hyperf\Di\Annotation\Inject;
use Lcobucci\JWT\Token\RegisteredClaims; use Lcobucci\JWT\Token\RegisteredClaims;
use Lcobucci\JWT\UnencryptedToken; use Lcobucci\JWT\UnencryptedToken;
use App\Interface\JwtInterface;
use function Hyperf\Support\value; use function Hyperf\Support\value;
final class BaseTokenService implements CheckTokenInterface final class BaseTokenService implements CheckTokenInterface
@@ -55,20 +55,4 @@ final class BaseTokenService implements CheckTokenInterface
$this->jwt = $jwt; $this->jwt = $jwt;
return $this; return $this;
} }
/**
* @param UnencryptedToken $token
* @return \Closure
*/
public function refreshToken(UnencryptedToken $token): \Closure
{
return value(static function (JwtInterface $jwt) use ($token) {
$jwt->addBlackList($token);
return [
'access_token' => $jwt->builderAccessToken($token->claims()->get(RegisteredClaims::ID))->toString(),
'refresh_token' => $jwt->builderRefreshToken($token->claims()->get(RegisteredClaims::ID))->toString(),
'expire_at' => (int) $jwt->getConfig('ttl', 0),
];
}, $this->getJwt());
}
} }

View File

@@ -11,5 +11,5 @@ declare(strict_types=1);
*/ */
return [ return [
Hyperf\Database\Schema\Blueprint::class => App\Common\Macros\BlueprintMacros::class, Hyperf\Database\Schema\Blueprint::class => App\Common\Macros\BlueprintMacros::class,
App\Interface\CheckTokenInterface::class => App\Service\BaseTokenService::class, App\Common\Interface\CheckTokenInterface::class => App\Service\BaseTokenService::class,
]; ];