fix:优化auth权限,登录逻辑获取信息

This commit is contained in:
Ying
2022-12-02 11:16:57 +08:00
parent 66c75fb6b4
commit 1cba17c91c
31 changed files with 668 additions and 811 deletions

View File

@@ -11,54 +11,26 @@
namespace app;
use app\admin\library\Auth;
use support\Log;
use support\Response;
use think\helper\Str;
define('AdminSession', 'AdminLogin');
class AdminController extends BaseController
{
/**
* 数据库实例
* @var object
*/
public object $model;
/**
* 是否验证
* @var bool
*/
public bool $isValidate = true;
/**
* 验证场景
* @var string
*/
public string $scene = '';
/**
* 数据表名称
* @var string
*/
public string $tableName;
/**
* 控制器/类名
* @var string
*/
public string $controller;
/**
* 控制器方法
* @var string
*/
public string $action;
/**
* 控制器/方法名
* @var string
*/
public string $method;
/**
* 操作状态
* @var mixed
@@ -67,7 +39,6 @@ class AdminController extends BaseController
/**
* 获取模板
* @access protected
* @var string
*/
public string $template = '';
@@ -80,49 +51,42 @@ class AdminController extends BaseController
/**
* 当前表字段
*
* @var array
*/
protected array $tableFields = [];
/**
* 默认开关
*
* @var string
*/
protected string $keepField = 'status';
/**
* 开启数据限制
* 默认关闭
* @var boolean
*/
protected bool $dataLimit = false;
/**
* 数据限制字段
*
* @var string
*/
protected string $dataLimitField = 'admin_id';
/**
* 需要排除的字段
*
* @var mixed
*/
protected mixed $ruleOutFields = '';
/**
* 查询过滤字段
*
* @var array
*/
protected array $filterWhere = ['page', 'limit'];
/**
* 查询转换字段
*
* @var array
*/
protected array $converTime = ['create_time', 'update_time', 'delete_time'];
@@ -143,14 +107,14 @@ class AdminController extends BaseController
}
/**
* 获取资源
* 获取资源列表
* @return Response|void
*/
public function index()
{
if (request()->isAjax()) {
$page = (int)input('page', 1);
$limit = (int)input('limit',18);
$limit = (int)input('limit', 18);
$where = $this->buildSelectParams();
$count = $this->model->where($where)->count();
$limit = is_empty($limit) ? 10 : $limit;
@@ -168,11 +132,13 @@ class AdminController extends BaseController
if (!empty($localKey) && !empty($bind)) {
$relation[] = $method->getName();
$expBind = explode(',', $bind[1]);
$relListKey[] = ['key'=>$localKey[1], 'value'=>$expBind[0]];
$relListKey[] = ['key' => $localKey[1], 'value' => $expBind[0]];
}
}
} catch (\ReflectionException $e) {}
$subQuery = $this->model->field('id')->where($where)->order($order, 'desc')->limit((int)$limit)->page((int)$page)->buildSql();
} catch (\Throwable $th) {
Log::info($th->getMessage());
}
$subQuery = $this->model->field('id')->where($where)->order($order, 'desc')->limit($limit)->page($page)->buildSql();
$subQuery = '( SELECT object.id FROM ' . $subQuery . ' AS object )';
$list = $this->model->with($relation)->where('id in' . $subQuery)->order($order, 'desc')->select()->toArray();
foreach ($list as $key => $value) {
@@ -198,7 +164,7 @@ class AdminController extends BaseController
$post = $this->preRuleOutFields(\request()->post());
if ($this->dataLimit) {
$post[$this->dataLimitField] = request()->adminData['id'];
$post[$this->dataLimitField] = get_admin_id();
}
$validate = $this->isValidate ? get_class($this->model) : $this->isValidate;
@@ -226,7 +192,7 @@ class AdminController extends BaseController
// 限制数据调用
if (!$this->auth->SuperAdmin() && $this->dataLimit
&& in_array($this->dataLimitField, $this->model->getFields())) {
if ($data[$this->dataLimitField] != request()->adminData['id']) {
if ($data[$this->dataLimitField] != get_admin_id()) {
return $this->error('没有权限');
}
}
@@ -266,7 +232,7 @@ class AdminController extends BaseController
foreach ($list as $item) {
if (!$this->auth->SuperAdmin() && $this->dataLimit
&& in_array($this->dataLimitField, $this->model->getFields())) {
if ($item[$this->dataLimitField] != request()->adminData['id']) {
if ($item[$this->dataLimitField] != get_admin_id()) {
continue;
}
}
@@ -296,7 +262,7 @@ class AdminController extends BaseController
$where[] = ['id', '=', input('id')];
if (!$this->auth->SuperAdmin() && $this->dataLimit
&& in_array($this->dataLimitField, $this->model->getFields())) {
$where[] = [$this->dataLimitField, '=',request()->adminData['id']];
$where[] = [$this->dataLimitField, '=', get_admin_id()];
}
try {
@@ -315,7 +281,7 @@ class AdminController extends BaseController
/**
* 数据表排序
* @return Response|void
* @return Response
*/
public function sort()
{
@@ -396,7 +362,6 @@ class AdminController extends BaseController
/**
* 获取查询参数
* @return mixed|void
*/
protected function buildSelectParams()
{
@@ -522,7 +487,7 @@ class AdminController extends BaseController
// 限制数据字段
if (!$this->auth->SuperAdmin() && $this->dataLimit) {
if (in_array($this->dataLimitField, $this->tableFields)) {
$where[] = [$this->dataLimitField, '=', request()->adminData['id']];
$where[] = [$this->dataLimitField, '=', get_admin_id()];
}
}

View File

@@ -1,5 +1,5 @@
<?php
declare (strict_types = 1);
declare (strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于WebMan开发]
// +----------------------------------------------------------------------
@@ -19,13 +19,6 @@ use Gregwar\Captcha\CaptchaBuilder;
class BaseController
{
/**
* 应用实例
* @var mixed $app
*/
protected mixed $app;
/**
* 数据库实例
* @var object
@@ -33,11 +26,10 @@ class BaseController
public object $model;
/**
* 是否批量验证
* 是否验证
* @var bool
*/
protected bool $batchValidate = false;
public bool $isValidate = true;
/**
* 验证场景
@@ -46,40 +38,10 @@ class BaseController
public string $scene = '';
/**
* 操作状态
* @var mixed
*/
public mixed $status;
/**
* 接口权限
* @var object
*/
public object $auth;
/**
* 控制器登录鉴权
* 是否批量验证
* @var bool
*/
public bool $needLogin = false;
/**
* 禁止登录重复
* @var array
*/
public array $repeatLogin = [];
/**
* 非鉴权方法
* @var array
*/
public array $noNeedAuth = ['index', 'login', 'logout'];
/**
* 验证错误消息
* @var string
*/
protected string $errorText;
protected bool $batchValidate = false;
/**
* 获取访问来源
@@ -96,10 +58,10 @@ class BaseController
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param $validate
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @return bool|true
* @return bool
*/
protected function validate(array $data, $validate, array $message = [], bool $batch = false): bool
{
@@ -111,8 +73,8 @@ class BaseController
// 支持场景
[$validate, $scene] = explode('.', $validate);
}
$class = false !== strpos($validate, '\\') ? $validate : $this->parseClass('validate', $validate);
$v = new $class();
$class = str_contains($validate, '\\') ? $validate : $this->parseClass('validate', $validate);
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
}
@@ -132,23 +94,23 @@ class BaseController
* 解析应用类的类名
* @access public
* @param string $layer 层名 controller model ...
* @param string $name 类名
* @param string $name 类名
* @return string
*/
protected function parseClass(string $layer, string $name): string
{
$name = str_replace(['/', '.'], '\\', $name);
$name = str_replace(['/', '.'], '\\', $name);
$array = explode('\\', $name);
$class = Str::studly(array_pop($array));
$path = $array ? implode('\\', $array) . '\\' : '';
return 'app'. '\\' . $layer . '\\' . $path . $class;
$path = $array ? implode('\\', $array) . '\\' : '';
return 'app' . '\\' . $layer . '\\' . $path . $class;
}
/**
* 操作成功跳转的快捷方法
* @access protected
* @param mixed $msg 提示信息
* @param string|null $url 跳转的URL地址
* @param null $url 跳转的URL地址
* @param mixed $data 返回的数据
* @param int $count
* @param int $code
@@ -156,7 +118,7 @@ class BaseController
* @param array $header 发送的Header信息
* @return Response
*/
protected function success($msg = '', string $url = null, $data = '', int $count = 0, int $code = 200, int $wait = 3, array $header = []): Response
protected function success(mixed $msg = '', $url = null, mixed $data = '', int $count = 0, int $code = 200, int $wait = 3, array $header = []): Response
{
if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
$url = $_SERVER["HTTP_REFERER"];
@@ -191,7 +153,7 @@ class BaseController
* @param array $header 发送的Header信息
* @return Response
*/
protected function error($msg = '', $url = null, $data = '', int $code = 101, int $wait = 3, array $header = []): Response
protected function error(mixed $msg = '', $url = null, mixed $data = '', int $code = 101, int $wait = 3, array $header = []): Response
{
if (is_null($url)) {
$url = request()->isAjax() ? '' : 'javascript:history.back(-1);';
@@ -254,9 +216,7 @@ class BaseController
/**
* 获取模型字段集
* @access protected
* @param $model
* @return mixed
* @param null $model
*/
protected function getTableFields($model = null)
{
@@ -301,6 +261,7 @@ class BaseController
if (strtolower($captcha) !== \request()->session()->get('captcha')) {
return false;
}
return true;
}
}

View File

@@ -33,30 +33,6 @@ class HomeController extends BaseController
*/
public object $model;
/**
* 是否验证
* @var bool
*/
public bool $isValidate = true;
/**
* 验证场景
* @var string
*/
public string $scene = '';
/**
* 控制器/类名
* @var string
*/
public string $controller;
/**
* 控制器方法
* @var string
*/
public string $action;
/**
* 操作状态
* @var mixed
@@ -98,6 +74,7 @@ class HomeController extends BaseController
* @var string
*/
public string $JumpUrl = '/user/index';
/**
* 初始化函数
*/

View File

@@ -37,57 +37,45 @@ class Login extends AdminController
public function index(): \support\Response
{
// 禁止重复访问
if (isset(request()->adminData['id'])) {
$session = get_admin_info();
if (isset($session['id'])) {
return $this->redirect('/admin/index');
}
if (request()->isPost()) {
$user = request()->post('name');
$pwd = request()->post('pwd');
$captcha = request()->post('captcha');
if ((isset(request()->adminData['count'])
&& request()->adminData['count'] >= 5)
&& (isset(request()->adminData['time'])
&& request()->adminData['time'] >= strtotime('- 5 minutes'))
) {
$error = '错误次数过多,请稍后再试!';
$this->writeLoginLogs($error);
return $this->error($error);
if ((isset($session['count']) && $session['count'] >= 5)
&& (isset($session['time']) && $session['time'] >= strtotime('- 5 minutes'))) {
return $this->displayResponse('错误次数过多,请稍后再试!');
}
// 验证码
if (isset(request()->adminData['isCaptcha'])) {
if (isset($session['isCaptcha'])) {
if (!$captcha || !$this->captchaCheck($captcha)) {
$error = '验证码错误!';
$this->writeLoginLogs($error);
return $this->error($error);
return $this->displayResponse('验证码错误!');
}
}
// 验证表单令牌
if (!request()->checkToken('__token__', \request()->all())) {
$error = '表单令牌错误!';
$this->writeLoginLogs($error);
return $this->error($error, '', ['token' => token()]);
if (!request()->checkToken('__token__', request()->all())) {
return $this->displayResponse('表单令牌错误!', ['token' => token()]);
} else {
$result = Admin::checkLogin($user, $pwd);
if (empty($result)) {
request()->adminData['time'] = time();
request()->adminData['isCaptcha'] = true;
request()->adminData['count'] = isset(request()->adminData['count']) ? request()->adminData['count'] + 1 : 1;
request()->session()->set(AdminSession, request()->adminData);
$error = '用户名或密码错误!';
$this->writeLoginLogs($error);
Event::emit('adminLoginError', \request()->all());
return $this->error($error, '', ['token' => token()]);
$session['time'] = time();
$session['isCaptcha'] = true;
$session['count'] = isset($session['count']) ? $session['count'] + 1 : 1;
request()->session()->set(AdminSession, $session);
// 执行登录失败事件
Event::emit('adminLoginError', request()->all());
return $this->displayResponse('用户名或密码错误!', ['token' => token()]);
}
if ($result['status'] !== 1) {
$error = '账号已被禁用!';
$this->writeLoginLogs($error);
return $this->error($error);
return $this->displayResponse('账号已被禁用!');
}
$result->login_ip = request()->getRealIp();
@@ -97,30 +85,41 @@ class Login extends AdminController
try {
$result->save();
$session = array_merge(request()->adminData, $result->toArray());
$session = array_merge($session, $result->toArray());
request()->session()->set(AdminSession, $session);
} catch (\Throwable $th) {
return $this->error($th->getMessage());
}
$success = '登录成功!';
$this->writeLoginLogs($success, true);
Event::emit('adminLoginSuccess', $result->toArray());
return $this->success($success, $this->JumpUrl);
return $this->displayResponse('登录成功!', [] , $this->JumpUrl);
}
}
return view('login/index', [
'captcha' => request()->adminData['isCaptcha'] ?? false,
'captcha' => $session['isCaptcha'] ?? false,
]);
}
/**
* 退出登录
* @param string $msg
* @param array $data
* @param string $url
* @return Response
*/
private function displayResponse(string $msg = 'error', array $data = [], string $url = ''): Response
{
$this->adminLoginLog($msg, $url ? 1 : 0);
return empty($url) ? $this->error($msg, $url, $data) : $this->success($msg, $url);
}
/**
* 写入登录日志
* @param string $error
* @param int $status
*/
private function writeLoginLogs(string $error, int $status = 0)
private function adminLoginLog(string $error, int $status = 0)
{
$name = \request()->input('name');
$userAgent = \request()->header('user-agent');
@@ -131,7 +130,7 @@ class Login extends AdminController
$user_os = '未知';
}
$user_browser = preg_replace('/[^(]+\((.*?)[^)]+\) .*?/','$1',$userAgent);
$user_browser = preg_replace('/[^(]+\((.*?)[^)]+\) .*?/', '$1', $userAgent);
$data = [
'user_ip' => request()->getRealIp(),

View File

@@ -325,7 +325,7 @@ class Admin extends AdminController
$page = input('page', 1);
$limit = input('limit', 3);
// 计算最大页码
$data = AdminNotice::with(['admin'])->where(['type' => $type, 'admin_id' => \request()->admin_id])
$data = AdminNotice::with(['admin'])->where(['type' => $type, 'admin_id' => get_admin_id()])
->order('id', 'desc')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
return $this->success('获取成功', '', $data);
}
@@ -333,7 +333,7 @@ class Admin extends AdminController
foreach ($array as $item) {
$where = [
['type', '=', $item],
['admin_id', '=', request()->admin_id]
['admin_id', '=', get_admin_id()]
];
$count[$item] = AdminNotice::where($where)->where('status', 0)->count();
$list[$item] = AdminNotice::with(['admin'])->withoutField('content')->where($where)->limit(3)->order('id desc')->select()->toArray();
@@ -358,7 +358,7 @@ class Admin extends AdminController
$type = input('type', 'notice');
if (!empty($id)) {
$detail = AdminNotice::with(['admin'])->where(['id' => $id, 'admin_id' => \request()->admin_id])->find();
$detail = AdminNotice::with(['admin'])->where(['id' => $id, 'admin_id' => get_admin_id()])->find();
if (empty($detail)) {
return $this->error('404 Not Found');
}
@@ -383,7 +383,7 @@ class Admin extends AdminController
{
if (\request()->post()) {
$post = request()->post();
$post['send_id'] = request()->admin_id;
$post['send_id'] = get_admin_id();
$post['type'] = 'message';
$post['send_ip'] = request()->getRealIp();
$post['create_time'] = time();
@@ -404,7 +404,7 @@ class Admin extends AdminController
if (empty($id)) {
throw new Exception('参数错误');
}
AdminNotice::where(['id' => $id, 'admin_id' => request()->admin_id])->update(['status' => $status]);
AdminNotice::where(['id' => $id, 'admin_id' => get_admin_id()])->update(['status' => $status]);
} catch (Exception $e) {
return $this->error('更新失败');
}
@@ -424,7 +424,7 @@ class Admin extends AdminController
$where = [
['type', '=', $type],
['status', '=', 1],
['admin_id', '=', request()->admin_id]
['admin_id', '=', get_admin_id()]
];
try {
AdminNotice::where($where)->delete();
@@ -446,7 +446,7 @@ class Admin extends AdminController
$type = input('type', 'notice');
$where = [
['type', '=', $type],
['admin_id', '=', request()->admin_id]
['admin_id', '=', get_admin_id()]
];
try {
AdminNotice::where($where)->update(['status' => 1]);
@@ -468,10 +468,9 @@ class Admin extends AdminController
*/
public function center(Request $request): \support\Response
{
if (request()->isPost()) {
$post = request()->post();
$post['id'] = $request->admin_id;
$post['id'] = get_admin_id();
if ($this->model->update($post)) {
return $this->success();
}
@@ -480,7 +479,7 @@ class Admin extends AdminController
}
$title = [];
$data = $this->model->find($request->admin_id);
$data = $this->model->find(get_admin_id());
if (!empty($data['group_id'])) {
$group = AdminGroupModel::field('title')
->whereIn('id', $data['group_id'])
@@ -505,7 +504,7 @@ class Admin extends AdminController
{
if (request()->isAjax()) {
$post = request()->post();
$id = $request->admin_id;
$id = get_admin_id();
try {
//code...
switch ($post['field']) {
@@ -571,7 +570,7 @@ class Admin extends AdminController
}
// 查找数据
$where[] = ['id', '=', request()->admin_id];
$where[] = ['id', '=', get_admin_id()];
$where[] = ['pwd', '=', encryptPwd($pwd)];
$result = $this->model->where($where)->find();

View File

@@ -1,5 +1,6 @@
<?php
declare (strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于WebMan开发]
// +----------------------------------------------------------------------
@@ -11,8 +12,7 @@ declare (strict_types=1);
// +----------------------------------------------------------------------
namespace app\admin\controller\system;
set_time_limit(600);
use GuzzleHttp\Exception\TransferException;
use support\Response;
use system\File;
@@ -276,6 +276,9 @@ class Plugin extends AdminController
public function config(): Response
{
$name = input('name');
if (!empty($name)) {
$name = strtolower(trim($name));
}
if (preg_replace('/[^a-zA-Z0-9]/i', '', $name) !== $name) {
return $this->error('插件名称只能是字母和数字');
}

View File

@@ -103,9 +103,9 @@ class Auth
* @param string $mode 执行check的模式
* @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
* @return bool 通过验证返回true;失败返回false
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function check($name, int $admin_id = 0, int $type = 1, string $mode = 'url', string $relation = 'or'): bool
{
@@ -203,9 +203,9 @@ class Auth
* 获取权限菜单
* @access public
* @return mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function getRulesMenu()
{
@@ -231,9 +231,9 @@ class Auth
* @param $admin_id
* @param array $nodes
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function getAuthList($admin_id, array $nodes = []): array
{
@@ -342,11 +342,11 @@ class Auth
/**
* 超级管理员
* @access public
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @access public
* @return bool
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function superAdmin(): bool
{
@@ -363,9 +363,9 @@ class Auth
* 管理组分级鉴权
* @param array $groupIDs
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function checkRulesForGroup(array $groupIDs = []): bool
{
@@ -395,23 +395,22 @@ class Auth
* 获取用户信息
* @param $admin_id
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function getAdminData($admin_id): array
public function getAdminInfo($admin_id): array
{
$admin_id = $admin_id ?? session('AdminLogin.id');
static $AdminData = [];
$admin_id = $admin_id ?? get_admin_id();
static $AdminArray = [];
$user = Db::name('admin');
// 获取用户表主键
$_pk = is_string($user->getPk()) ? $user->getPk() : 'id';
if (!isset($AdminData[$admin_id])) {
$AdminData[$admin_id] = $user->where($_pk, $admin_id)->find();
if (!isset($AdminArray[$admin_id])) {
$AdminArray[$admin_id] = $user->where($_pk, $admin_id)->find();
}
return $AdminData[$admin_id];
return $AdminArray[$admin_id];
}
/**

View File

@@ -41,24 +41,28 @@ class AdminPermissions implements MiddlewareInterface
* @throws DataNotFoundException
* @throws DbException
* @throws InvalidArgumentException
* @throws ModelNotFoundException
* @throws ModelNotFoundException|\ReflectionException
*/
public function process(Request $request, callable $handler): Response
{
$app = request()->getApp();
$app = request()->getApp();
$controller = request()->getController();
$action = request()->getAction();
$action = request()->getAction();
$AdminLogin = request()->session()->get(AdminSession);
if (!isset($AdminLogin['id']) && strtolower($controller) !== 'login') {
return redirect(url('/login/index'));
}
// 判断是否需要鉴权
$request->admin_id = $AdminLogin['id'] ?? 0;
$request->adminData = $AdminLogin ?? [];
$method = '/' . $controller. '/' .$action;
if (!in_array($method, $this->noNeedAuth) && !in_array('*', $this->noNeedAuth)) {
if (!Auth::instance()->SuperAdmin() && !Auth::instance()->check($method, $request->admin_id)) {
// 获取权限列表
$class = new \ReflectionClass($request->controller);
$properties = $class->getDefaultProperties();
$this->noNeedAuth = $properties['noNeedAuth'] ?? $this->noNeedAuth;
// 控制器鉴权
$method = '/' . $controller . '/' . $action;
if (!in_array('*', $this->noNeedAuth)
&& !in_array(strtolower($method), array_map('strtolower', $this->noNeedAuth))) {
if (!Auth::instance()->SuperAdmin() && !Auth::instance()->check($method, get_admin_id())) {
if (request()->isAjax()) {
return json(['code' => 101, 'msg' => '没有权限']);
} else {
@@ -67,9 +71,14 @@ class AdminPermissions implements MiddlewareInterface
}
}
// 控制器中间件分发
$id = input('id');
/**
* Admin应用
* 控制器权限分发
*/
if (\request()->isPost()) {
$id = input('id');
if ($controller == 'system/Admin') {
if ($data = AdminModel::getById($id)) {
$group_id = input('group_id');
@@ -79,7 +88,9 @@ class AdminPermissions implements MiddlewareInterface
return json(ResultCode::AUTH_ERROR);
}
}
} else if ($controller == 'system/AdminGroup') {
}
if ($controller == 'system/AdminGroup') {
if (!empty($id) && $id >= 1) {
if (!Auth::instance()->checkRulesForGroup((array)$id)) {
return json(ResultCode::AUTH_ERROR);
@@ -88,11 +99,12 @@ class AdminPermissions implements MiddlewareInterface
}
}
// 分配当前管理员信息
View::assign('app', $app);
View::assign('controller', $controller);
View::assign('action', $action);
View::assign('AdminLogin', $AdminLogin);
$this->writeAdminRequestLogs();
self::writeAdminRequestLogs();
return $handler($request);
}
@@ -103,7 +115,7 @@ class AdminPermissions implements MiddlewareInterface
* @throws DbException
* @throws ModelNotFoundException
*/
public function writeAdminRequestLogs()
public static function writeAdminRequestLogs()
{
if (saenv('system_logs')) {

View File

@@ -160,7 +160,7 @@
</div>
<div class="dash"></div>
<h3>{:__('标签')} <i class="layui-inputags layui-icon layui-icon-add-1" style="color: #666"></i> </h3>
<div class="layui-badge-list" style="padding-top: 6px;"> <volist name="$data.tags" id="vo">
<div class="layui-badge-list" style="padding-top: 6px;"> <volist name="$data['tags']" id="vo">
<span class="layui-badge layui-bg-gray"><i class="layui-icon layui-icon-close"></i>{$vo}</span>
</volist>
</div>

View File

@@ -27,7 +27,6 @@ class Ajax extends ApiController
* @return Response|void
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function smsSend()
{
@@ -46,10 +45,10 @@ class Ajax extends ApiController
return $this->error(__('发送频繁'));
}
$userData = User::getByMobile($mobile);
if (in_array($event, ['register', 'changer']) && $userData) {
$user = User::getByMobile($mobile);
if (in_array($event, ['register', 'changer']) && $user) {
return $this->error('当前手机号已被占用');
} else if ($event == 'forgot' && !$userData) {
} else if ($event == 'forgot' && !$user) {
return $this->error('当前手机号未注册');
}
@@ -89,10 +88,10 @@ class Ajax extends ApiController
return $this->error(__('发送频繁'));
}
$userData = User::getByEmail($email);
if (in_array($event, ['register', 'changer']) && $userData) {
$user = User::getByEmail($email);
if (in_array($event, ['register', 'changer']) && $user) {
return $this->error('当前邮箱已被注册');
} else if ($event == 'forgot' && !$userData) {
} else if ($event == 'forgot' && !$user) {
return $this->error('当前邮箱不存在');
}

View File

@@ -1,4 +1,4 @@
<?php /** @noinspection ALL */
<?php
namespace app\api\middleware\system;
@@ -39,28 +39,25 @@ class ApiPermissions implements MiddlewareInterface
* @param Request $request
* @param callable $handler
* @return Response
* @throws \ReflectionException
*/
public function process(Request $request, callable $handler): Response
{
$app = request()->getApp();
$app = request()->getApp();
$controller = request()->getController();
$action = request()->getAction();
$method = $controller . '/' . $action;
$className = '\app' . $app . '\\controller\\' . $controller;
$className = str_replace('/', '\\', $className);
if (class_exists($className)) {
$refClass = new \ReflectionClass($className);
$property = $refClass->getDefaultProperties();
$this->needLogin = $property['needLogin'] ?? false;
$this->noNeedAuth = $property['noNeedAuth'] ?? [];
}
$action = request()->getAction();
$method = $controller . '/' . $action;
$refClass = new \ReflectionClass($request->controller);
$property = $refClass->getDefaultProperties();
$this->needLogin = $property['needLogin'] ?? $this->needLogin;
$this->noNeedAuth = $property['noNeedAuth'] ?? $this->noNeedAuth;
$auth = Auth::instance();
if ($auth->isLogin()) {
$request->user_id = $auth->userData['id'];
$request->userData = $auth->userData;
// 验证权限
if ($this->authWorkflow && Event::hasListener('apiAuth')) {
$result = Event::emit('apiAuth', ['method' => $method, 'user_id' => $request->user_id], true);
$result = Event::emit('apiAuth', ['method' => $method, 'user_id' => $auth->user_id], true);
if (isset($result['code']) && $result['code'] != 200) {
return json($result);
}

View File

@@ -13,8 +13,12 @@ declare(strict_types=1);
namespace app\common\library;
use app\common\model\system\UserLog;
use Psr\SimpleCache\InvalidArgumentException;
use system\Random;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use app\common\model\system\User as UserModel;
use Webman\Event\Event;
@@ -28,11 +32,16 @@ class Auth
*/
public string $token;
/**
* 用户ID
*/
public int $user_id = 0;
/**
* 用户数据
* @var object|array
*/
public mixed $userData;
public mixed $userInfo;
/**
* 保活时间
@@ -79,9 +88,11 @@ class Auth
/**
* 用户注册
* @param array $post
* @return bool
* @throws \Psr\SimpleCache\InvalidArgumentException
* @throws \think\db\exception\DbException
* @return false|Response
* @throws DataNotFoundException
* @throws DbException
* @throws InvalidArgumentException
* @throws ModelNotFoundException
*/
public function register(array $post)
{
@@ -90,10 +101,8 @@ class Auth
return false;
}
/**
* 禁止批量注册
*/
$where[] = ['create_ip', '=', ip2long(request()->getRealIp())];
// 禁止批量注册
$where[] = ['create_ip', '=', request()->getRealIp()];
$where[] = ['create_time', '>', linux_extime(1)];
$totalMax = UserModel::where($where)->count();
@@ -128,24 +137,24 @@ class Auth
$post['pwd'] = encryptPwd($post['pwd'], $post['salt']);
}
$this->userData = UserModel::create($post);
return $this->responseToken($this->userData);
$user = UserModel::create($post);
} catch (\Throwable $th) {
$this->setError($th->getMessage());
return false;
}
return $this->responseToken($user);
}
/**
* 用户检测登录
* @param string $nickname
* @param string $pwd
* @return mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return false|Response
* @throws DataNotFoundException
* @throws DbException
* @throws InvalidArgumentException
* @throws ModelNotFoundException
*/
public function login(string $nickname = '', string $pwd = '')
{
@@ -155,36 +164,37 @@ class Auth
} else {
$where[] = ['mobile', '=', htmlspecialchars(trim($nickname))];
}
$this->userData = UserModel::where($where)->find();
if (!empty($this->userData)) {
$user = UserModel::where($where)->find();
$uPwd = encryptPwd($pwd, $this->userData['salt']);
if ($this->userData['pwd'] !== $uPwd) {
if (!empty($user)) {
$uPwd = encryptPwd($pwd, $user['salt']);
if ($user['pwd'] !== $uPwd) {
$this->setError('用户名或密码错误');
UserLog::write($this->getError(), $this->userData->nickname, $this->userData->id);
UserLog::write($this->getError(), $user['nickname'], $user['id']);
return false;
}
if (!$this->userData['status']) {
if (!$user['status']) {
$this->setError('用户异常或未审核,请联系管理员');
UserLog::write($this->getError(), $this->userData->nickname, $this->userData->id);
UserLog::write($this->getError(), $user['nickname'], $user['id']);
return false;
}
// 更新登录数据
$userUpdate = [
'id' => $this->userData['id'],
$update = [
'id' => $user['id'],
'login_time' => time(),
'login_ip' => request()->getRealIp(),
'login_count' => $this->userData['login_count'] + 1,
'login_count' => $user['login_count'] + 1,
];
if (UserModel::update($userUpdate)) {
Event::emit('userLoginSuccess', $this->userData);
UserLog::write('登录成功', $this->userData->nickname, $this->userData->id, 1);
return $this->responseToken($this->userData);
if (UserModel::update($update)) {
Event::emit('userLoginSuccess', $user);
UserLog::write('登录成功', $user['nickname'], $user['id'], 1);
return $this->responseToken($user);
}
}
@@ -195,9 +205,9 @@ class Auth
/**
* 验证是否登录
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException|InvalidArgumentException
*/
public function isLogin(): bool
{
@@ -205,46 +215,67 @@ class Auth
if (!$token) {
return false;
}
$uid = $this->checkToken($token);
if (!empty($uid)) {
$this->token = $token;
$this->userData = UserModel::with('group')->find($uid);
return true;
// 验证token
$user = $this->checkToken($token);
if (isset($user['id'])) {
$this->userInfo = UserModel::with('group')->find($user['id']);
if (!empty($this->userInfo)) {
$this->token = $token;
$this->user_id = $user['id'];
$this->refreshUserInfo($token, $this->userInfo);
return true;
}
}
return false;
}
/**
* 退出登录
* @return void
* @throws \Psr\SimpleCache\InvalidArgumentException
* 获取用户信息
*/
public function logout()
public function getUserInfo()
{
Cache::delete($this->token);
$token = $this->getToken();
if (!$token) {
return false;
}
// 获取用户信息
return $this->checkToken($token);
}
/**
*
* 返回前端令牌
* @param mixed $userData
* @param $user
* @param bool $token
* @return mixed
* @throws \Psr\SimpleCache\InvalidArgumentException
* @return Response
* @throws InvalidArgumentException
*/
public function responseToken($userData, bool $token = false)
public function responseToken($user, bool $token = false): Response
{
$this->token = $token ? $this->getToken() : $this->buildToken($userData['id']);
$this->token = $token ? $this->getToken() : $this->buildToken($user['id']);
$response = response();
$response->cookie('uid', $userData['id'],$this->keepTime, '/');
$response->cookie('token', $this->token,$this->keepTime, '/');
$response->cookie('nickname', $userData['nickname'],$this->keepTime, '/');
Cache::set($this->token, $userData['id'], $this->keepTime);
Event::emit("userLoginSuccess", $userData);
$response->cookie('uid', $user['id'], $this->keepTime, '/');
$response->cookie('token', $this->token, $this->keepTime, '/');
$response->cookie('nickname', $user['nickname'], $this->keepTime, '/');
$this->refreshUserInfo($this->token, $user);
// 执行登录成功事件
Event::emit("userLoginSuccess", $user);
return $response;
}
/**
* 刷新用户信息
* @param $token
* @param $user
* @return void
* @throws InvalidArgumentException
*/
private function refreshUserInfo($token, $user): void
{
Cache::set($token, $user, $this->keepTime);
}
/**
@@ -260,7 +291,6 @@ class Auth
/**
* 获取token
* @return array|string|null
*/
public function getToken($token = 'token')
{
@@ -269,15 +299,20 @@ class Auth
/**
* 校验token
* @access protected
* @param $token
* @return void
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function checkToken($token)
{
$user_id = Cache::get($token);
return $user_id ?? false;
return Cache::get($token);
}
/**
* 退出登录
* @return void
* @throws InvalidArgumentException
*/
public function logout()
{
Cache::delete($this->token);
}
/**

View File

@@ -118,7 +118,7 @@ class ParseData
}
/**
* 自动补全图片
* cdn前缀
* @access public
* @param string $image
* @param $data

View File

@@ -3,6 +3,7 @@
* 全局公共函数库
*/
use app\common\library\Auth;
use app\common\model\system\UserThird;
use think\facade\Cache;
use app\common\model\system\Config;
@@ -123,6 +124,51 @@ if (!function_exists('token_field')) {
}
}
if (!function_exists('get_user_id')) {
/**
* 获取会员ID
*/
function get_user_id()
{
return get_user_info('id');
}
}
if (!function_exists('get_user_info')) {
/**
* 获取会员信息
*/
function get_user_info($field = '')
{
$data = Auth::instance()->getUserInfo();
if ($field && isset($data[$field])) {
return $data[$field];
}
return $data;
}
}
if (!function_exists('get_admin_id')) {
/**
* 获取管理员ID
*/
function get_admin_id(string $name = 'AdminLogin')
{
return get_admin_info($name . '.id');
}
}
if (!function_exists('get_admin_info')) {
/**
* 获取管理员信息
*/
function get_admin_info(string $name = 'AdminLogin')
{
return session($name);
}
}
// +----------------------------------------------------------------------
// | 文件操作函数开始
// +----------------------------------------------------------------------

View File

@@ -62,10 +62,10 @@ class Ajax extends HomeController
return $this->error(__('发送频繁'));
}
$userData = User::getByMobile($mobile);
if (in_array($event, ['register', 'changer']) && $userData) {
$user = User::getByMobile($mobile);
if (in_array($event, ['register', 'changer']) && $user) {
return $this->error('当前手机号已被占用');
} else if ($event == 'forgot' && !$userData) {
} else if ($event == 'forgot' && !$user) {
return $this->error('当前手机号未注册');
}
@@ -103,10 +103,10 @@ class Ajax extends HomeController
return $this->error(__('发送频繁'));
}
$userData = User::getByEmail($email);
if (in_array($event, ['register', 'changer']) && $userData) {
$user = User::getByEmail($email);
if (in_array($event, ['register', 'changer']) && $user) {
return $this->error('当前邮箱已被注册');
} else if ($event == 'forgot' && !$userData) {
} else if ($event == 'forgot' && !$user) {
return $this->error('当前邮箱不存在');
}

View File

@@ -99,40 +99,37 @@ class Third extends HomeController
} catch (\Exception $e) {
return $this->error($e->getMessage());
}
$userData = $this->oauth->getUserInfo();
if (!empty($userData) && !$this->auth->isLogin()) {
return $this->register($userData, $this->type);
$user = $this->oauth->getUserInfo();
if (!empty($user) && !$this->auth->isLogin()) {
return $this->register($user, $this->type);
} else if ($this->auth->isLogin()) { // 绑定用户
return $this->doBind($userData, $this->type);
return $this->doBind($user, $this->type);
}
}
/**
* 用户注册操作
* @param array $userDatas
* @param array $info
* @param string|null $type
* @return Response
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
protected function register(array $userDatas = [], string $type = null)
protected function register(array $info = [], string $type = null)
{
$openid = $userDatas['openid'] ?? $userDatas['id'];
$nickname = $userDatas['userData']['name'] ?? $userDatas['userData']['nickname'];
$userData = UserThird::alias('th')
->view('user', '*', 'user.id=th.user_id')
->where(['openid' => $openid, 'type' => $type])
->find();
$openid = $info['openid'] ?? $info['id'];
$nickname = $info['userData']['name'] ?? $info['userData']['nickname'];
$userInfo = UserThird::alias('th')->view('user', '*', 'user.id=th.user_id')->where(['openid' => $openid, 'type' => $type])->find();
if (!empty($userData)) {
$array['id'] = $userData['id'];
if (!empty($userInfo)) {
$array['id'] = $userInfo['id'];
$array['login_time'] = time();
$array['login_ip'] = request()->getRealIp();
$array['login_count'] = $userData['login_count'] + 1;
$array['login_count'] = $userInfo['login_count'] + 1;
if (User::update($array)) {
$response = $this->auth->responseToken($userData);
$response = $this->auth->responseToken($userInfo);
$response->withBody(json_encode(ResultCode::LOGINSUCCESS))->redirect(request()->cookie('redirectUrl', '/'));
}
@@ -140,7 +137,7 @@ class Third extends HomeController
// 注册本地用户
$data['nickname'] = $nickname;
$data['avatar'] = $userDatas['userData']['avatar'];
$data['avatar'] = $info['userData']['avatar'];
if (User::getByNickname($nickname)) {
$data['nickname'] .= Random::alpha(3);
}
@@ -155,11 +152,11 @@ class Third extends HomeController
'user_id' => $result['id'],
'openid' => $openid,
'nickname' => $nickname,
'access_token' => $userDatas['access_token'],
'refresh_token' => $userDatas['refresh_token'],
'expires_in' => $userDatas['expires_in'],
'access_token' => $info['access_token'],
'refresh_token' => $info['refresh_token'],
'expires_in' => $info['expires_in'],
'login_time' => time(),
'expiretime' => time() + $userDatas['expires_in'],
'expiretime' => time() + $info['expires_in'],
];
}
@@ -207,7 +204,7 @@ class Third extends HomeController
}
if ($this->auth->isLogin()) {
$result = $this->auth->userData;
$result = $this->auth->userInfo;
if (!empty($result)) {
if (empty($result['email']) || empty($result['pwd'])) {
@@ -227,18 +224,18 @@ class Third extends HomeController
/**
* 用户绑定操作实例
* @param array $userDatas
* @param array $info
* @param string|null $type
* @return Response|null
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
protected function doBind(array $userDatas = [], string $type = null)
protected function doBind(array $info = [], string $type = null)
{
$openid = $userDatas['openid'] ?? $userDatas['id'];
$nickname = $userDatas['userData']['name'] ?? $userDatas['userData']['nickname'];
$openid = $info['openid'] ?? $info['id'];
$nickname = $info['userData']['name'] ?? $info['userData']['nickname'];
// 查询是否被注册
$where['openid'] = $openid;
@@ -251,11 +248,11 @@ class Third extends HomeController
'user_id' => request()->cookie('uid'),
'openid' => $openid,
'nickname' => $nickname,
'access_token' => $userDatas['access_token'],
'refresh_token' => $userDatas['refresh_token'],
'expires_in' => $userDatas['expires_in'],
'access_token' => $info['access_token'],
'refresh_token' => $info['refresh_token'],
'expires_in' => $info['expires_in'],
'login_time' => time(),
'expiretime' => time() + $userDatas['expires_in'],
'expiretime' => time() + $info['expires_in'],
];
if (UserThird::create($third)) {
@@ -283,6 +280,4 @@ class Third extends HomeController
request()->cookie('redirectUrl', null,1);
return $this->redirect($referer);
}
}

View File

@@ -62,7 +62,7 @@ class User extends HomeController
public function index(): Response
{
// 未读短消息
$unread = UserNotice::where('user_id', \request()->user_id)->where('status', 0)->count();
$unread = UserNotice::where('user_id', get_user_id())->where('status', 0)->count();
return view('/user/index', [
'unread' => $unread,
]);
@@ -165,16 +165,15 @@ class User extends HomeController
}
$where = $email ? ['email' => $email] : ['mobile' => $mobile];
$userData = $this->model->where($where)->find();
if (!$userData) {
$user = $this->model->where($where)->find();
if (!$user) {
return $this->error('用户不存在');
}
try {
$salt = Random::alpha();
$pwd = encryptPwd($pwd, $salt);
$this->model->update(['id' => $userData['id'], 'pwd' => $pwd, 'salt' => $salt]);
$this->model->update(['id' => $user['id'], 'pwd' => $pwd, 'salt' => $salt]);
} catch (\Exception $e) {
return $this->error('修改密码失败,请联系管理员');
}
@@ -207,7 +206,7 @@ class User extends HomeController
return $this->error('当前昵称已被占用,请更换!');
}
if ($this->model->update(['id' => $request->user_id, 'nickname' => $nickname])) {
if ($this->model->update(['id' => get_user_id(), 'nickname' => $nickname])) {
return $this->success('修改昵称成功!', (string)url('/user/index'));
}
@@ -231,7 +230,7 @@ class User extends HomeController
return view('/user/center', [
'newsHtml' => $result ?? '服务器错误',
'userList' => $this->model->order('login_count', 'desc')->limit(12)->select()->toArray(),
'invite_count' => $this->model->where('invite_id', $request->user_id)->count(),
'invite_count' => $this->model->where('invite_id', get_user_id())->count(),
]);
}
@@ -254,7 +253,7 @@ class User extends HomeController
$where[] = ['status', '=', $status];
}
$where[] = ['user_id', '=', \request()->user_id];
$where[] = ['user_id', '=', get_user_id()];
$count = UserNotice::where($where)->count();
$page = ($count <= $limit) ? 1 : $page;
$list = UserNotice::where($where)->order('id', 'desc')->limit((int)$limit)->page((int)$page)->select()->toArray();
@@ -279,7 +278,7 @@ class User extends HomeController
return $this->error('消息不存在');
}
if ($info['user_id'] != \request()->user_id) {
if ($info['user_id'] != get_user_id()) {
return $this->error('非法操作');
}
@@ -293,7 +292,7 @@ class User extends HomeController
}
// 更新未读
$unread = UserNotice::where(['user_id' => \request()->user_id, 'status' => 0])->count();
$unread = UserNotice::where(['user_id' => get_user_id(), 'status' => 0])->count();
return view('/user/viewMessage', [
'info' => $info,
'unread' => $unread,
@@ -311,7 +310,7 @@ class User extends HomeController
$ids = input('id');
$type = input('type', 'del');
$where[] = ['id', 'in', implode(',', $ids)];
$where[] = ['user_id', '=', \request()->user_id];
$where[] = ['user_id', '=', get_user_id()];
if ($type === 'del') {
if (UserNotice::where($where)->delete()) {
return $this->success('删除成功');
@@ -346,14 +345,14 @@ class User extends HomeController
return $this->error($post);
}
if ($nickname != \request()->userData['nickname']
if ($nickname != get_user_info()['nickname']
&&$this->model->where('nickname', $nickname)->find()) {
return $this->error('当前昵称已被占用,请更换!');
}
unset($post['money']);
unset($post['score']);
$user = $this->model->find(\request()->user_id);
$user = $this->model->find(get_user_id());
if ($user->save($post)) {
return $this->success('更新资料成功');
}
@@ -361,9 +360,7 @@ class User extends HomeController
return $this->error();
}
return view('/user/profile',[
'user' => \request()->userData,
]);
return view('/user/profile');
}
/**
@@ -372,14 +369,14 @@ class User extends HomeController
*/
public function certification(): Response
{
$userInfo = get_user_info();
if (request()->isPost()) {
$name = input('name');
$mobile = input('mobile');
$idCard = input('idCard');
$captcha = input('captcha');
if (!empty(\request()->userData['prove'])) {
if (!empty($userInfo['prove'])) {
return $this->error('您已经实名认证过了!');
}
@@ -405,7 +402,7 @@ class User extends HomeController
}
// 更新系统认证信息
$this->model->where('id', \request()->user_id)->update([
$this->model->where('id', get_user_id())->update([
'prove' => 1,
'name' => $name,
'idCard' => $idCard,
@@ -420,7 +417,7 @@ class User extends HomeController
return $this->success('实名认证成功!');
}
return view('/user/certification',['prove' => \request()->userData['prove']]);
return view('/user/certification',['prove' => $userInfo['prove']]);
}
/**
@@ -437,7 +434,7 @@ class User extends HomeController
// 获取数据
$page = input('page', 1);
$limit = input('limit', 1);
$where[] = ['login_id', '=', \request()->user_id];
$where[] = ['login_id', '=', get_user_id()];
$count = UserLog::where($where)->count();
$page = ($count <= $limit) ? 1 : $page;
$list = UserLog::where($where)->order('id', 'desc')->limit((int)$limit)->page((int)$page)->select()->toArray();
@@ -460,15 +457,16 @@ class User extends HomeController
// 获取参数
$pwd = input('pwd');
$oldPwd = input('oldpwd');
$yPwd = encryptPwd($oldPwd, $request->userData->salt);
$userInfo = get_user_info();
$yPwd = encryptPwd($oldPwd, $userInfo['salt']);
if ($yPwd != $request->userData->pwd) {
if ($yPwd != $userInfo['pwd']) {
return $this->error('原密码输入错误!');
}
$salt = Random::alpha();
$pwd = encryptPwd($pwd, $salt);
$result = $this->model->update(['id' => $request->user_id, 'pwd' => $pwd, 'salt' => $salt]);
$result = $this->model->update(['id' => get_user_id(), 'pwd' => $pwd, 'salt' => $salt]);
if (!empty($result)) {
return $this->success('修改密码成功!');
}
@@ -487,8 +485,8 @@ class User extends HomeController
{
if (request()->isPost()) {
$data = array();
$data['id'] = $request->user_id;
$data['app_id'] = 10000 + $request->user_id;
$data['id'] = get_user_id();
$data['app_id'] = 10000 + get_user_id();
$data['app_secret'] = Random::alpha(22);
if ($this->model->update($data)) {
return $this->success();
@@ -527,7 +525,7 @@ class User extends HomeController
if (!empty($email) && !empty($captcha)) {
if ($Ems->check($email, $captcha, $event)) {
$this->model->update(['id' => $request->user_id, 'email' => $email]);
$this->model->update(['id' => get_user_id(), 'email' => $email]);
return $this->success('修改邮箱成功!');
}
@@ -578,7 +576,7 @@ class User extends HomeController
if (!empty($mobile) && !empty($captcha)) {
if ($Sms->check($mobile, $captcha, $event)) {
$this->model->update(['id' => $request->user_id, 'mobile' => (int)$mobile]);
$this->model->update(['id' => get_user_id(), 'mobile' => (int)$mobile]);
return $this->success('修改手机号成功!');
}
@@ -627,9 +625,10 @@ class User extends HomeController
}
try {
$request->userData->question = $question;
$request->userData->answer = $answer;
$request->userData->save();
$userInfo = get_user_info();
$userInfo->question = $question;
$userInfo->answer = $answer;
$userInfo->save();
} catch (\Throwable $th) {
return $this->error();
}
@@ -651,20 +650,21 @@ class User extends HomeController
{
$maxProgress = 5;
$thisProgress = 1;
$userInfo = get_user_info();
if ($request->userData->email) {
if ($userInfo->email) {
$thisProgress++;
}
if ($request->userData->mobile) {
if ($userInfo->mobile) {
$thisProgress++;
}
if ($request->userData->answer) {
if ($userInfo->answer) {
$thisProgress++;
}
if ($request->userData->wechat) {
if ($userInfo->wechat) {
$thisProgress++;
}
@@ -691,8 +691,9 @@ class User extends HomeController
if (!$response) {
return $this->error(Upload::instance()->getError());
}
$request->userData->avatar = $response['url'] . '?' . Random::alpha(12);
if ($request->userData->save()) {
$userInfo = get_user_info();
$userInfo->avatar = $response['url'] . '?' . Random::alpha(12);
if ($userInfo->save()) {
return json($response);
}
}

View File

@@ -38,50 +38,45 @@ class IndexPermissions implements MiddlewareInterface
* 跳转URL地址
* @var string
*/
public string $JumpUrl = '/user/index';
public string $JumpUrl = '/index/user/index';
/**
* 校验权限
* @param Request $request
* @param callable $handler
* @return Response
* @throws \ReflectionException
*/
public function process(Request $request, callable $handler): Response
{
$app = request()->getApp();
$app = request()->getApp();
$controller = request()->getController();
$action = request()->getAction();
$action = request()->getAction();
// 控制器是否存在
$className = '\app' . $app . '\\controller\\' . $controller;
$className = str_replace('/', '\\', $className);
if (class_exists($className)) {
$refClass = new \ReflectionClass($className);
$property = $refClass->getDefaultProperties();
$this->needLogin = $property['needLogin'] ?? false;
$this->noNeedAuth = $property['noNeedAuth'] ?? [];
$this->repeatLogin = $property['repeatLogin'] ?? ['login', 'register'];
$this->JumpUrl = $property['JumpUrl'] ?? '/user/index';
}
$refClass = new \ReflectionClass($request->controller);
$property = $refClass->getDefaultProperties();
$this->needLogin = $property['needLogin'] ?? false;
$this->noNeedAuth = $property['noNeedAuth'] ?? $this->noNeedAuth;
$this->repeatLogin = $property['repeatLogin'] ?? $this->repeatLogin;
$this->JumpUrl = $property['JumpUrl'] ?? $this->JumpUrl;
// 是否验证登录器
$auth = Auth::instance();
if ($auth->isLogin()) {
$request->user_id = $auth->userData['id'];
$request->userData = $auth->userData;
// 禁止重复登录
if (in_array($action, $this->repeatLogin)) {
return redirect($this->JumpUrl);
}
View::assign('user', $auth->userData);
View::assign('user', $auth->userInfo);
} else {
if ($this->needLogin && !in_array($action, $this->noNeedAuth)) {
if (\request()->isAjax()) {
return json(ResultCode::PLEASELOGININ);
} else {
return redirect('/user/login');
return redirect('/index/user/login');
}
}
}

View File

@@ -5,12 +5,11 @@
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" href="/static/js/layui/css/layui.css">
<!-- // 加载font-awesome图标 -->
<link href="/static/js/layui/css/font-awesome.css?v={:config('app.version')}" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="/static/css/center.css?v={:release()}">
<script src="/static/js/layui/layui.js"></script>
<script src="/static/js/common.js?v={:release()}"></script>
<!-- // 加载font-awesome图标 -->
<!--[if lt IE 9]>
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
@@ -21,6 +20,6 @@
.layui-layout-admin .layui-layout-left,
.layui-layout-admin .layui-body,
.layui-layout-admin .layui-footer{left: 0;}
.layui-layout-admin .layui-side{width: 0px;}
.layui-layout-admin .layui-side{width: 0;}
}
</style>

View File

@@ -56,21 +56,22 @@
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label"><span class="red">*</span> 手机号码</label>
<div class="layui-input-inline">
<input class="layui-input layui-disabled" disabled value="{$user.mobile|default='未绑定'}">
</div>
<label class="layui-form-label"><span class="red">*</span> 性别</label>
<div class="layui-input-inline">
<input name="gender" type="radio" value="1" title="男" <eq name="$user['gender']" value="1">checked</eq>>
<input name="gender" type="radio" value="0" title="女" <eq name="$user['gender']" value="0">checked</eq>>
</div>
<label class="layui-form-label"><span class="red">*</span> 身份证号码</label>
<div class="layui-input-inline">
<input name="idcard" placeholder="请输入身份证号" class="layui-input" value="{$user.idcard}">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label"><span class="red">*</span> 手机号码</label>
<label class="layui-form-label"><span class="red">*</span> 身份证号码</label>
<div class="layui-input-inline">
<input class="layui-input layui-disabled" disabled value="{$user.mobile|default='未绑定'}">
<input name="idcard" placeholder="请输入身份证号" class="layui-input" value="{$user.idcard}">
</div>
<label class="layui-form-label"><span class="red">*</span> 邮箱地址</label>
<div class="layui-input-inline">
@@ -99,8 +100,8 @@
<div class="layui-form-item" style="margin-top: 22px;text-align: center">
<label class="layui-form-label"></label>
<div class="layui-input-inline">
<button type="submit" class="layui-btn layui-btn-normal" lay-submit="" lay-filter="submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
<button type="submit" class="layui-btn layui-btn-normal" lay-submit="" lay-filter="submit">立即提交</button>
</div>
</div>

View File

@@ -11,9 +11,17 @@ declare (strict_types=1);
// +----------------------------------------------------------------------
namespace app\queue\redis;
use app\AdminController;
use support\Log;
use Webman\RedisQueue\Redis;
use Webman\RedisQueue\Client;
class Push extends AdminController
/**
* 队列任务
* @package app\queue\redis
* @author meystack
* @date 2022-11-20
*/
class Push
{
/**
* api推送
@@ -22,19 +30,41 @@ class Push extends AdminController
protected mixed $api;
/**
* 构造函数
* 同步推送
* @param $name
* @param $data
* @param int $delay
* @return bool
*/
public function __construct()
public static function queue($name, $data, int $delay = 0): bool
{
parent::__construct();
try {
// 投递消息
Redis::send($name, $data, $delay);
} catch (\Throwable $th) {
Log::info('redis push error:' . $th->getMessage());
return false;
}
return true;
}
/*
* 消息推送首页
* @return mixed
/**
* 异步推送
* @param $name
* @param $data
* @param int $delay
* @return bool
*/
public function index()
public static function client($name, $data, int $delay = 0): bool
{
return response('success');
try {
// 投递消息
Client::send($name, $data, $delay);
} catch (\Throwable $th) {
Log::info('redis Client async error:' . $th->getMessage());
return false;
}
return true;
}
}

41
app/queue/redis/Works.php Normal file
View File

@@ -0,0 +1,41 @@
<?php
namespace app\queue\redis;
use Webman\RedisQueue\Consumer;
/**
* 消费任务
* @package app\queue\redis
* @author meystack
* @date 2022-11-20
*/
class Works implements Consumer
{
/**
* 消费队列名称
* @var string
*/
public string $queue = 'send-mail';
/**
* REDIS连接名称
* @param $data
* @return bool
*/
public string $connection = 'default';
/**
* 默认消费函数
* @param $data
* @return bool
*/
public function consume($data): bool
{
/**
* 无需反序列化
* 请在此编写您的消费逻辑
*/
var_dump($data);
return true;
}
}