登录验证
This commit is contained in:
@@ -0,0 +1,94 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace app\console\controller;
|
||||||
|
|
||||||
|
use support\Request;
|
||||||
|
use support\Response;
|
||||||
|
use app\console\model\AdminsModel;
|
||||||
|
use app\console\service\AdminsService;
|
||||||
|
use app\console\validate\AdminsValidator;
|
||||||
|
use app\mzl\common\controller\BaseController;
|
||||||
|
|
||||||
|
class AdminsController extends BaseController
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 不需要验证token的接口
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $noNeedJwt = ['login'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证器
|
||||||
|
*/
|
||||||
|
protected mixed $validator = AdminsValidator::class;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回业务 Service 实例
|
||||||
|
*/
|
||||||
|
protected function getService()
|
||||||
|
{
|
||||||
|
return new AdminsService(new AdminsModel());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 额外字段处理 (根据场景处理)
|
||||||
|
* @param array $item
|
||||||
|
* @param string $scene
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function postProcessItem(array $item, string $scene): array
|
||||||
|
{
|
||||||
|
|
||||||
|
if ($scene === 'default') {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return $item;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 参数预处理 (根据场景处理)
|
||||||
|
* @param Request $request
|
||||||
|
* @param string $scene
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function prepareParams(Request $request, string $scene): array
|
||||||
|
{
|
||||||
|
$params = parent::prepareParams($request, $scene);
|
||||||
|
|
||||||
|
if ($scene === 'default') {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return $params;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页
|
||||||
|
*
|
||||||
|
* @param Request $request 请求对象
|
||||||
|
* @return Response 响应对象
|
||||||
|
*/
|
||||||
|
public function index(Request $request, string $scene = 'default'): Response
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return parent::index($request, $scene);
|
||||||
|
} catch (\Throwable $th) {
|
||||||
|
return $this->errorResponse($th->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录
|
||||||
|
*/
|
||||||
|
public function login(Request $request, string $scene = 'default'): Response
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$user =$this->getService()->login($request->all());
|
||||||
|
return $this->successResponse($user);
|
||||||
|
} catch (\Throwable $th) {
|
||||||
|
return $this->errorResponse($th->getMessage().$th->getFile().$th->getLine());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace app\console\model;
|
||||||
|
|
||||||
|
use support\Model;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AdminsModel
|
||||||
|
*/
|
||||||
|
class AdminsModel extends Model
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The connection name for the model.
|
||||||
|
*
|
||||||
|
* @var string|null
|
||||||
|
*/
|
||||||
|
protected $connection = 'mysql';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The table associated with the model.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $table = 'hs_admins';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The primary key associated with the table.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $primaryKey = 'id';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if the model should be timestamped.
|
||||||
|
*
|
||||||
|
* @var bool
|
||||||
|
*/
|
||||||
|
public $timestamps = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模型的数据字段的保存格式。
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $dateFormat = 'U';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 允许自动填充模型字段
|
||||||
|
*/
|
||||||
|
protected $fillable = ['id', 'username', 'nickname', 'password', 'avatar', 'email', 'mobile', 'created_at', 'updated_at', 'login_at', 'status'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 不允许自动填充模型字段
|
||||||
|
*/
|
||||||
|
protected $guarded = [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace app\console\service;
|
||||||
|
|
||||||
|
use app\console\model\AdminsModel;
|
||||||
|
use app\mzl\common\services\BaseService;
|
||||||
|
use app\mzl\common\utils\JwtUtil;
|
||||||
|
use app\mzl\modules\translation\service\TranslationService;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use support\exception\BusinessException;
|
||||||
|
|
||||||
|
class AdminsService extends BaseService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 定义模型
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getModel(): string
|
||||||
|
{
|
||||||
|
return AdminsModel::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多场景配置
|
||||||
|
*/
|
||||||
|
public function queryScenes(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
// 'default' => function ($params) {
|
||||||
|
// $keyword = $params['keyword'] ?? '';
|
||||||
|
// return [
|
||||||
|
// 'filters' => [
|
||||||
|
// ['field' => '***', 'operator' => '=', 'value' => '***']
|
||||||
|
// ],
|
||||||
|
// 'fields' => ['id'],
|
||||||
|
// 'relations' => [],
|
||||||
|
// 'custom' => function(Builder $q) use ($keyword) {
|
||||||
|
// // 示例
|
||||||
|
// if ($keyword) {
|
||||||
|
// $q->where(function($q2) use($keyword) {
|
||||||
|
// $q2->whereHas('***', function($q3) use($keyword) {
|
||||||
|
// $q3->where('***', 'like', "%{$keyword}%");
|
||||||
|
// })->orWhereHas('***', function($q4) use($keyword) {
|
||||||
|
// $q4->where('***', 'like', "%{$keyword}%");
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
// 'sorts' => [
|
||||||
|
// ['field' => 'created_at', 'direction' => 'desc']
|
||||||
|
// ],
|
||||||
|
// 'pagination' => [
|
||||||
|
// 'page' => $params['page'] ?? 1,
|
||||||
|
// 'per_page' => $params['per_page'] ?? 10,
|
||||||
|
// ]
|
||||||
|
// ];
|
||||||
|
// }
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function login(array $params)
|
||||||
|
{
|
||||||
|
$sourceLocale = locale();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (empty($params['username'])) {
|
||||||
|
throw new BusinessException('用户名不能为空');
|
||||||
|
}
|
||||||
|
if (empty($params['password'])) {
|
||||||
|
throw new BusinessException('密码不能为空');
|
||||||
|
}
|
||||||
|
$admin = AdminsModel::where(['username'=>$params['username']])->first();
|
||||||
|
if (!$admin) {
|
||||||
|
throw new BusinessException('用户不存在');
|
||||||
|
}
|
||||||
|
$userId = $admin['id'];
|
||||||
|
|
||||||
|
$adminPassword = $admin['password'];
|
||||||
|
|
||||||
|
// $hashedPassword = password_hash($params['password'], PASSWORD_DEFAULT); //注册时的加密方法
|
||||||
|
if (!password_verify($params['password'], $adminPassword)) {
|
||||||
|
throw new BusinessException('密码错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
//密码验证成功后加密生成 Token
|
||||||
|
$token = JwtUtil::generateToken($userId);
|
||||||
|
$result = $admin;
|
||||||
|
unset($result['password']);
|
||||||
|
$result['token'] = $token;
|
||||||
|
|
||||||
|
return $admin;
|
||||||
|
} catch (\Throwable $th) {
|
||||||
|
throw $th;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace app\console\validate;
|
||||||
|
|
||||||
|
use think\Validate;
|
||||||
|
|
||||||
|
class AdminsValidator extends Validate
|
||||||
|
{
|
||||||
|
// 规则
|
||||||
|
protected $rule = [
|
||||||
|
|
||||||
|
];
|
||||||
|
|
||||||
|
// 提示
|
||||||
|
protected $message = [
|
||||||
|
|
||||||
|
];
|
||||||
|
|
||||||
|
// 场景
|
||||||
|
protected $scene = [
|
||||||
|
'store' => [
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
'update' => [
|
||||||
|
|
||||||
|
]
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<?php
|
||||||
|
namespace app\middleware;
|
||||||
|
|
||||||
|
|
||||||
|
use app\admin\model\Admin;
|
||||||
|
use app\console\model\AdminsModel;
|
||||||
|
use app\model\User;
|
||||||
|
use app\mzl\common\utils\JwtUtil;
|
||||||
|
use app\util\Util;
|
||||||
|
use ReflectionClass;
|
||||||
|
use support\Redis;
|
||||||
|
use Webman\Http\Request;
|
||||||
|
use Webman\Http\Response;
|
||||||
|
use Webman\MiddlewareInterface;
|
||||||
|
use support\exception\BusinessException;
|
||||||
|
|
||||||
|
class ConsoleAuthMiddleware implements MiddlewareInterface
|
||||||
|
{
|
||||||
|
public function process(Request $request, callable $handler): Response
|
||||||
|
{
|
||||||
|
if (strpos($request->path(), '/console/') !== 0) {
|
||||||
|
return $handler($request);
|
||||||
|
}
|
||||||
|
// 通过反射获取控制器哪些方法不需要登录
|
||||||
|
$controller = new ReflectionClass($request->controller);
|
||||||
|
$noNeedLogin = $controller->getDefaultProperties()['noNeedJwt'] ?? [];
|
||||||
|
|
||||||
|
$isLogin = !in_array($request->action, $noNeedLogin);
|
||||||
|
|
||||||
|
// 从 Header 获取 Token
|
||||||
|
$token = $request->header('Authorization');
|
||||||
|
|
||||||
|
//需要登录并且未提供token
|
||||||
|
$body = [
|
||||||
|
'status' => 'error',
|
||||||
|
'code' => 401,
|
||||||
|
'message' => 'Please log in.',
|
||||||
|
'data' => [],
|
||||||
|
];
|
||||||
|
if ($isLogin && (!$token || !str_starts_with($token, 'Bearer '))) {
|
||||||
|
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||||
|
}elseif(!$isLogin){
|
||||||
|
return $handler($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
$token = substr($token, 7);
|
||||||
|
try {
|
||||||
|
// 验证 Token 并获取用户ID
|
||||||
|
$decoded = JwtUtil::verifyToken($token);
|
||||||
|
|
||||||
|
if (!isset($decoded->sub)) {
|
||||||
|
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$userId = $decoded->sub;
|
||||||
|
$user = AdminsModel::find($userId);
|
||||||
|
if(!$user){
|
||||||
|
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将用户ID存入请求对象,供后续使用
|
||||||
|
$request->user = $user;
|
||||||
|
return $handler($request);
|
||||||
|
} catch (BusinessException $e) {
|
||||||
|
return json(['code' => 401, 'msg' => $e->getMessage()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace app\mzl\common\utils;
|
||||||
|
|
||||||
|
use Firebase\JWT\JWT;
|
||||||
|
use Firebase\JWT\Key;
|
||||||
|
use Firebase\JWT\ExpiredException;
|
||||||
|
use Firebase\JWT\SignatureInvalidException;
|
||||||
|
use support\exception\BusinessException;
|
||||||
|
|
||||||
|
class JwtUtil
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 生成 JWT Token
|
||||||
|
* @param int|string $userId
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function generateToken($userId): string
|
||||||
|
{
|
||||||
|
$config = config('jwt');
|
||||||
|
$payload = [
|
||||||
|
'iss' => 'webman', // 签发者
|
||||||
|
'aud' => 'client', // 接收方
|
||||||
|
'iat' => time(), // 签发时间
|
||||||
|
'exp' => time() + $config['expire'], // 过期时间
|
||||||
|
'sub' => $userId // 用户标识
|
||||||
|
];
|
||||||
|
return JWT::encode($payload, $config['secret'], $config['algorithm']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证并解析 Token
|
||||||
|
* @param string $token
|
||||||
|
* @return object
|
||||||
|
* @throws BusinessException
|
||||||
|
*/
|
||||||
|
public static function verifyToken(string $token)
|
||||||
|
{
|
||||||
|
$config = config('jwt');
|
||||||
|
$body = [
|
||||||
|
'status' => 'error',
|
||||||
|
'code' => 403,
|
||||||
|
'message' => 'Please log in.',
|
||||||
|
'data' => [],
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
return JWT::decode($token, new Key($config['secret'], $config['algorithm']));
|
||||||
|
} catch (ExpiredException $e) {
|
||||||
|
$body['message'] = 'Token Expired';
|
||||||
|
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||||
|
} catch (SignatureInvalidException $e) {
|
||||||
|
$body['message'] = 'Signature Invalid';
|
||||||
|
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
$body['message'] = 'Invalid Token';
|
||||||
|
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?php
|
||||||
|
return [
|
||||||
|
'secret' => getenv('JWT_SECRET_KEY'), // 替换为高强度的密钥
|
||||||
|
'algorithm' => getenv('JWT_ALGORITHM'), // 加密算法
|
||||||
|
'expire' => getenv('JWT_EXPIRATION'), // 过期时间
|
||||||
|
];
|
||||||
@@ -23,6 +23,7 @@ return [
|
|||||||
app\middleware\Lang::class
|
app\middleware\Lang::class
|
||||||
],
|
],
|
||||||
'console' => [
|
'console' => [
|
||||||
app\middleware\Lang::class
|
app\middleware\Lang::class,
|
||||||
|
app\middleware\ConsoleAuthMiddleware::class,
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
@@ -120,6 +120,8 @@ Route::group('/applet', function() {
|
|||||||
|
|
||||||
// ====== ====== ====== 后台管理 ====== ====== ======
|
// ====== ====== ====== 后台管理 ====== ====== ======
|
||||||
Route::group('/console', function() {
|
Route::group('/console', function() {
|
||||||
|
// 协议管理
|
||||||
|
Route::any('/user/login', [\app\console\controller\AdminsController::class, 'login']);
|
||||||
// 协议管理
|
// 协议管理
|
||||||
Route::any('/agt/list', [\app\console\controller\AgreementController::class, 'index']);
|
Route::any('/agt/list', [\app\console\controller\AgreementController::class, 'index']);
|
||||||
Route::any('/agt/add', [\app\console\controller\AgreementController::class, 'add']);
|
Route::any('/agt/add', [\app\console\controller\AgreementController::class, 'add']);
|
||||||
|
|||||||
Reference in New Issue
Block a user