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,7 +73,7 @@ class BaseController
// 支持场景
[$validate, $scene] = explode('.', $validate);
}
$class = false !== strpos($validate, '\\') ? $validate : $this->parseClass('validate', $validate);
$class = str_contains($validate, '\\') ? $validate : $this->parseClass('validate', $validate);
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
@@ -141,14 +103,14 @@ class BaseController
$array = explode('\\', $name);
$class = Str::studly(array_pop($array));
$path = $array ? implode('\\', $array) . '\\' : '';
return 'app'. '\\' . $layer . '\\' . $path . $class;
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
{
@@ -344,9 +344,9 @@ class Auth
* 超级管理员
* @access public
* @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 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,7 +41,7 @@ class AdminPermissions implements MiddlewareInterface
* @throws DataNotFoundException
* @throws DbException
* @throws InvalidArgumentException
* @throws ModelNotFoundException
* @throws ModelNotFoundException|\ReflectionException
*/
public function process(Request $request, callable $handler): Response
{
@@ -53,12 +53,16 @@ class AdminPermissions implements MiddlewareInterface
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,6 +39,7 @@ class ApiPermissions implements MiddlewareInterface
* @param Request $request
* @param callable $handler
* @return Response
* @throws \ReflectionException
*/
public function process(Request $request, callable $handler): Response
{
@@ -46,21 +47,17 @@ class ApiPermissions implements MiddlewareInterface
$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);
$refClass = new \ReflectionClass($request->controller);
$property = $refClass->getDefaultProperties();
$this->needLogin = $property['needLogin'] ?? false;
$this->noNeedAuth = $property['noNeedAuth'] ?? [];
}
$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)) {
// 验证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->userData = UserModel::with('group')->find($uid);
$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,13 +38,14 @@ 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
{
@@ -52,36 +53,30 @@ class IndexPermissions implements MiddlewareInterface
$controller = request()->getController();
$action = request()->getAction();
// 控制器是否存在
$className = '\app' . $app . '\\controller\\' . $controller;
$className = str_replace('/', '\\', $className);
if (class_exists($className)) {
$refClass = new \ReflectionClass($className);
$refClass = new \ReflectionClass($request->controller);
$property = $refClass->getDefaultProperties();
$this->needLogin = $property['needLogin'] ?? false;
$this->noNeedAuth = $property['noNeedAuth'] ?? [];
$this->repeatLogin = $property['repeatLogin'] ?? ['login', 'register'];
$this->JumpUrl = $property['JumpUrl'] ?? '/user/index';
}
$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 mixed
return true;
}
/**
* 异步推送
* @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;
}
}

View File

@@ -48,7 +48,8 @@
"php-di/php-di": "^6.4",
"yansongda/pay": "~3.1.0",
"overtrue/wechat": "~5.0",
"ext-json": "*"
"ext-json": "*",
"ext-zip": "*"
},
"suggest": {
"ext-event": "For better performance. "

View File

@@ -23,7 +23,8 @@ return [
'monitor_dir' => [
app_path(),
config_path(),
base_path() . '/plugin',
// 插件开发者请开启此项
// base_path() . '/plugin',
base_path() . '/process',
base_path() . '/support',
base_path() . '/resource',

View File

@@ -1,3 +1,9 @@
/*!
* center.css 用户中心样式表 - 2022-10-10
* https://github.com/meystack/swiftadmin
* Copyright (c) meystack
* Licensed Apache2.0
*/
body {
background-color: #eee;
}
@@ -110,7 +116,7 @@ b.msg {
box-shadow: 0 0px 2px 0 rgb(0 0 0 / 15%);
}
.logo-text, layui-logo {
.logo-text, .layui-logo {
color: #959890!important;
}

View File

@@ -1,4 +1,8 @@
/*!
* 前端简易样式表
* Copyright (c) meystack
* Licensed Apache2.0
*/
body {
background: #fff;
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;

View File

@@ -1,193 +0,0 @@
.fl {
float: left;
}
.fr {
float: right;
}
.clear {
clear: both;
}
i {
cursor: pointer;
}
.layui-nav .layui-this:after, .layui-nav-bar {
background: 0 !important;
}
body {
background-color: #eee;
}
.logo-text, layui-logo {
color: #959890 !important;
}
.logo-text {
margin-left: 22px;
font-size: 20px;
}
.layui-btn {
height: 33px;
line-height: 33px;
}
.layui-form-fixed {
padding-right: 35px;
padding-top: 30px;
}
.layui-center {
text-align: center;
}
.layui-layout-admin .layui-header, .layui-logo, .layui-nav-tree .layui-nav-bar {
background: #2a94de !important;
}
.layui-nav {
background-color: unset;
}
.layui-nav-tree .layui-nav-item:hover, .layui-nav-tree .layui-this {
background-color: #37424f;
}
.layui-nav-tree .layui-nav-child dd.layui-this, .layui-nav-tree .layui-nav-child dd.layui-this a, .layui-nav-tree .layui-this, .layui-nav-tree .layui-this > a, .layui-nav-tree .layui-this > a:hover {
background-color: #37424f;
}
/* 主题布局 */
#content {
padding: 25px;
}
/*// 个人中心*/
#content .goindex {
height: 80px;
line-height: 80px;
overflow: hidden;
}
#content .goindex div {
display: inline-block;
}
#content .goindex .tips {
font-size: 18px;
}
#content .goindex div img {
width: 80%;
}
#content #profile {
padding: 20px;
overflow: hidden;
}
#profile .contract-title {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
line-height: 24px;
margin: 20px 0 6px;
font-size: 14px;
color: #a2a0a0;
}
#content #profile .layui-col-md3 {
margin-bottom: 15px;
}
#content #profile i {
cursor: pointer;
}
#content #profile i:hover {
color: #2a94de;
}
#content #account {
padding: 48px;
background: #2a94de;
border-radius: 3px;
color: #fff;
padding-bottom: 20px;
}
#content #account .layui-btn {
background-color: #6ebbf1 !important;
}
#imgHead img {
width: 90px;
height: 90px;
border-radius: 50px;
cursor: pointer;
}
.layui-user-avatar {
position: relative;
display: inline-block;
cursor: pointer;
text-align: center;
}
.layui-user-avatar:hover:after {
content: '\e65d';
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
color: #eee;
background: rgba(0, 0, 0, 0.5);
font-family: layui-icon;
font-size: 24px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
cursor: pointer;
line-height: 110px;
border-radius: 50%;
}
#content .nickname {
line-height: 37px;
font-size: 35px;
margin-top: 36px;
color: #fff;
margin-bottom: 10px;
}
#content #thrid {
margin-top: 20px;
}
#content #appkey {
overflow: hidden;
}
.layui-comment {
padding-top: 15px !important;
}
.layui-table-cell div {
display: inline-block;
}
a.layui-table-text {
cursor: pointer;
}
a[lay-event="del"] {
color: #FE232D;
}

View File

@@ -1,9 +1,10 @@
/**
* 前端CommonJS
* 默认提供一些基础的页面交互操作
* 插件开发请勿直接将JS代码写入此文件
/*!
* CommonJS For Home - v1.0.0 - 2022-10-10
* https://github.com/meystack/swiftadmin
* Copyright (c) meystack
* Licensed Apache2.0
*/
layui.use(['jquery','form','upload','table','dropdown'], function(){
layui.use(['jquery', 'form', 'upload', 'table', 'dropdown'], function () {
let $ = layui.$;
let form = layui.form;
@@ -17,7 +18,7 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
* @param count
*/
window.bellMessage = function (count) {
let msg = dropdown.render({
dropdown.render({
elem: '#notice'
, trigger: 'hover'
, align: 'center'
@@ -25,7 +26,8 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
title: !count ? '暂无消息' : '您有<b class="msg">' + count + '</b>条未读消息'
}], ready: function (elemPanel, elem) {
}
, click: function (data, othis) {
, click: function (data, index) {
console.log(data, index);
let elem = $('.layui-nav-tree li [lay-href="/user/message"]');
$(elem).parents('.layui-nav-item').addClass('layui-nav-itemed');
$(elem).trigger('click');
@@ -33,46 +35,52 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
});
}
// 注册为全局对象
/**
* 前端全局对象
* @access object
* screen: 屏幕宽度
* event: 事件对象
* Cookie: Cookie操作对象
* */
window.Home = {
screen: function(){
let width =$(window).width()
if(width > 1200){
screen: function () {
let width = $(window).width()
if (width > 1200) {
return 3; //大屏幕
} else if(width > 992){
} else if (width > 992) {
return 2; //中屏幕
} else if(width > 768){
} else if (width > 768) {
return 1; //小屏幕
} else {
return 0; //超小屏幕
}
},
event: {
closeDialog:function(that) {
closeDialog: function (that) {
that = that || this;
let _type = $(that).parents(".layui-layer").attr("type");
if (typeof _type === "undefined") {
parent.layer.close(parent.layer.getFrameIndex(window.name));
}else {
} else {
let layerId = $(that).parents(".layui-layer").attr("id").substring(11);
layer.close(layerId);
}
}
},
// cookie
Cookie : { // 获取cookies
Cookie: { // 获取cookies
'Set': function (name, value, days) {
let exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toUTCString();
},
'Get': function (name) {
let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return unescape(arr[2]);
return null;
}
return null;
},
'Del': function (name) {
let exp = new Date();
@@ -85,16 +93,23 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
}
}
// 监听全局form表单
form.on('submit(submitIframe)', function(data){
/**
* 监听全局form表单提交
* @param data
* @param callback
* @type button lay-filter="submitIframe"
*/
form.on('submit(submitIframe)', function (data) {
let that = $(this), _form = that.parents('form'),
_url = _form.attr("action") || false,
_close = that.data("close") || undefined,
_reload = that.data('reload');
$.post(_url,
data.field,function(res){
if(res.code === 200){
// 开启节流
that.attr("disabled", true);
$.post(_url,
data.field, function (res) {
if (res.code === 200) {
top.layer.msg(res.msg);
switch (_reload) {
case 'top':
@@ -117,9 +132,8 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
if (_close === undefined) {
Home.event.closeDialog(that);
}
}
else{
top.layui.layer.msg(res.msg,'error');
} else {
top.layui.layer.msg(res.msg, 'error');
}
try {
@@ -130,8 +144,9 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
if (typeof res.data.__token__ !== 'undefined') {
$('input#__token__').val(res.data.__token__);
}
} catch (e) {}
} catch (e) {
}
that.attr("disabled", false);
}, 'json');
return false;
@@ -139,10 +154,11 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
/**
* 监听form表单搜索
* 默认表格ID: lay-tableList
*/
form.on('submit(formSearch)', function (data) {
var field = data.field;
let field = data.field;
for (const key in field) {
if (!field[key]) {
delete field[key];
@@ -162,35 +178,33 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
obj && obj.call(this, $(this));
});
var uploadURL = '/index/user/upload';
let uploadURL = '/index/user/upload';
layui.each($('*[lay-upload]'), function (index, elem) {
var that = $(this),
let that = $(this),
name = $(elem).attr('lay-upload') || undefined,
type = $(elem).data('type') || 'normal',
size = $(elem).data('size') || 51200, // 限制最大5M
accept = $(elem).data('accept') || 'images',
multiple = $(elem).data('multiple') || false,
callback = $(elem).attr('callback') || undefined;
accept = $(elem).data('accept') || 'file';
// 文件上传函数
var uploadFiles = {
// 文件上传回调
let uploadFiles = {
normal: function (res, name) {
$('input.' + name).prop('value', res.url);
$('img.' + name).prop('src', res.url);
},
images: function (res, name) {
var o = $('img.' + name);
let o = $('img.' + name);
o.prop('src', res.url);
o.parent('div').removeClass('layui-hide');
$('input.' + name).val(res.url);
$(elem).find('p,i,hr').addClass('layui-hide');
},
multiple: function (res, name) {
var index = $('.layui-imagesbox .layui-input-inline');
let index = $('.layui-imagesbox .layui-input-inline');
index = index.length ? index.length - 1 : 0;
var html = '<div class="layui-input-inline">';
html += '<img src="' + res.url + '" >';
let html = '<div class="layui-input-inline">';
html += '<img src="' + res.url + '" alt="alt" >';
html += '<input type="text" name="' + name + '[' + index + '][src]" class="layui-hide" value="' + res.url + '">';
html += '<input type="text" name="' + name + '[' + index + '][title]" class="layui-input" placeholder="图片简介">';
html += '<span class="layui-badge layui-badge-red" onclick="layui.$(this).parent().remove();">删除</span></div>';
@@ -204,17 +218,13 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
, url: uploadURL
, method: 'post'
, size: size
, accept: 'file'
, accept: accept
, before: function (res) {
// 关闭按钮点击
that.prop("disabled", true);
}, done: function (res, index, file) {
that.prop("disabled", false);
if (res.code === 200 && res.url !== '') {
if (typeof res.chunkId != 'undefined' ) {
if (typeof res.chunkId != 'undefined') {
layer.close(window[res.chunkId]);
}
@@ -223,26 +233,24 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
} else {
// 错误消息
layer.error(res.msg);
}
that.prop("disabled", false);
}
}
})
})
// 全局监听打开窗口
$(document).on('click',"*[lay-open]",function(){
let clickthis = $(this),
$(document).on('click', "*[lay-open]", function () {
let clickThis = $(this),
config = {
url: clickthis.data('url') || undefined,
object: clickthis.data('object') || 'self',
type: clickthis.data('type') || 2,
area: clickthis.data('area') || "auto",
offset: clickthis.data('offset') || "25%",
title: clickthis.data('title') || false,
maxmin: clickthis.data('maxmin') || false,
auto: clickthis.data('auto') || "undefined",
url: clickThis.data('url') || undefined,
object: clickThis.data('object') || 'self',
type: clickThis.data('type') || 2,
area: clickThis.data('area') || "auto",
offset: clickThis.data('offset') || "25%",
title: clickThis.data('title') || false,
maxmin: clickThis.data('maxmin') || false,
auto: clickThis.data('auto') || "undefined",
iframeAuto: false
}
@@ -264,15 +272,17 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
}
}
var layObject = self;
/**
* 获取窗口索引
* @type {Window | (WorkerGlobalScope & Window)}
*/
let hierarchy = self;
if (config.object === 'top') {
layObject = top;
hierarchy = top;
} else if (config.object === 'parent') {
layObject = parent;
hierarchy = parent;
}
// 打开窗口
layObject.layer.open({
hierarchy.layer.open({
type: config.type,
area: config.area,
title: config.title,
@@ -281,18 +291,20 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
shadeClose: true,
scrollbar: true,
content: config.url,
success:function(layero,index){
success: function (layero, index) {
config.iframeAuto && layer.iframeAuto(index);
// 页面层才渲染
if (config.type === 1) {
layui.form.render();
layui.form.on("submit(submitPage)",function(post){
let that = $(this), _pageUrl = that.parents('form').attr('action');
layui.form.on("submit(submitPage)", function (post) {
let that = $(this),
url = that.parents('form').attr('action');
// 开始POST提交数据
$.post(_pageUrl,
post.field, function(res){
that.attr('disabled', true);
$.post(url, post.field, function (res) {
if (res.code === 200) {
Home.event.closeDialog(that);
if ($(that).data('reload')) {
@@ -300,9 +312,9 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
}
layer.msg(res.msg);
} else {
layer.msg(res.msg,'error');
layer.msg(res.msg, 'error');
}
that.attr('disabled', false);
}, 'json');
return false;
@@ -312,13 +324,17 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
})
})
/**
* 表格批量操作
* @param obj
*/
$(document).on("click", "*[lay-batch]", function (obj) {
var othis = $(this)
, tableId = othis.data("table") || null
, fields = othis.data("field") || undefined
let that = $(this)
, tableId = that.data("table") || null
, fields = that.data("field") || undefined
, list = table.checkStatus(tableId);
var field = ['id'];
let field = ['id'];
if (typeof fields !== 'undefined') {
field = field.concat(fields.split(','));
}
@@ -328,11 +344,11 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
return false;
}
var data = {};
for (var n in field) {
var e = field[n];
let data = {};
for (let n in field) {
let e = field[n];
field[e] = [];
for (var i in list.data) {
for (let i in list.data) {
field[e].push(list.data[i][e]);
}
data[e] = field[e];
@@ -341,7 +357,7 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
layer.confirm('确定执行批量操作', function (index) {
$.ajax({
url: othis.data("url"),
url: that.data("url"),
type: 'post',
data: data,
dataType: 'json',
@@ -358,32 +374,35 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
})
})
// 监听ajax操作
$(document).on("click","*[lay-ajax]",function(obj) {
/**
* 监听ajax操作
* @param obj
*/
$(document).on("click", "*[lay-ajax]", function (obj) {
let clickthis = $(this),config = {
url : clickthis.attr('data-url')|| "undefined",
type : clickthis.data('type') || 'post',
dataType : clickthis.data('dataType') || 'json',
timeout : clickthis.data('timeout') || '6000',
tableId : clickthis.data('table') || clickthis.data('batch'),
reload : clickthis.data('reload'),
jump : clickthis.data('jump') || false,
confirm : clickthis.data('confirm'),
let clickThis = $(this), config = {
url: clickThis.attr('data-url') || "undefined",
type: clickThis.data('type') || 'post',
dataType: clickThis.data('dataType') || 'json',
timeout: clickThis.data('timeout') || '6000',
tableId: clickThis.data('table') || clickThis.data('batch'),
reload: clickThis.data('reload'),
jump: clickThis.data('jump') || false,
confirm: clickThis.data('confirm'),
}, defer = $.Deferred();
// 定义初始化对象
let data = {}
// 获取拼接参数
, packet = clickthis.attr("data-data") || null
, object = clickthis.attr("data-object") || undefined;
, packet = clickThis.attr("data-data") || null
, object = clickThis.attr("data-object") || undefined;
if (config.confirm !== undefined) {
config.confirm = config.confirm || '确定执行此操作吗?';
layer.confirm(config.confirm, function(index){
runAjax(config);
layer.confirm(config.confirm, function (index) {
runningAjax(config);
layer.close(index);
},function(index){
}, function (index) {
layer.close(index);
return false;
})
@@ -394,25 +413,24 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
object = object.split(',');
for (let i = 0; i < object.length; i++) {
let ele = object[i].split(":");
let val = $('.'+ele[1]).val();
data[ele[0]] = val;
data[ele[0]] = $('.' + ele[1]).val();
}
}
// 传递对象数据
if (packet !== 'null') {
packet = new Function("return "+packet)();
data = $.extend({},data,packet);
packet = new Function("return " + packet)();
data = $.extend({}, data, packet);
}
// 传递input表单数据
let input = clickthis.data('input') || undefined;
let input = clickThis.data('input') || undefined;
if (typeof input !== undefined) {
let attribute = layui.$('.'+input).val();
let attribute = layui.$('.' + input).val();
}
// 回调函数
let runAjax = function(config) {
let runningAjax = function (config) {
// 执行AJAX操作
$.ajax({
url: config.url,
@@ -420,17 +438,16 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
dataType: config.dataType,
timeout: config.timeout,
data: data,
// 需要支持跨域访问
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function(res) {
success: function (res) {
if (res.code === 200) {
layer.msg(res.msg);
if (typeof res.data.text !== 'undefined') {
$(clickthis).text(res.data.text);
$(clickThis).text(res.data.text);
}
switch (config.reload) {
@@ -451,17 +468,17 @@ layui.use(['jquery','form','upload','table','dropdown'], function(){
}
} else {
layer.msg(res.msg,'error');
layer.msg(res.msg, 'error');
}
},
error: function(res) {
layer.msg('Access methods failure','error');
error: function (res) {
layer.msg('Access methods failure', 'error');
}
})
}
if (!config.confirm) {
runAjax(config);
runningAjax(config);
}
})
})

View File

@@ -11,22 +11,22 @@
layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'slider', 'upload', 'laydate', 'dropdown', 'colorpicker', 'cascader', 'content', 'tags'], function (exports) {
"use strict";
var $ = layui.jquery;
var i18n = layui.i18n;
var layer = layui.layer;
var form = layui.form;
var rate = layui.rate;
var table = layui.table;
var slider = layui.slider;
var element = layui.element;
var laydate = layui.laydate;
var cascader = layui.cascader;
var upload = layui.upload;
var content = layui.content;
var colorpicker = layui.colorpicker;
let $ = layui.jquery;
let i18n = layui.i18n;
let layer = layui.layer;
let form = layui.form;
let rate = layui.rate;
let table = layui.table;
let slider = layui.slider;
let element = layui.element;
let laydate = layui.laydate;
let cascader = layui.cascader;
let upload = layui.upload;
let content = layui.content;
let colorpicker = layui.colorpicker;
// 系统常量
var TABFILTER = 'swiftadmin-tabs', BODY = '.layui-body', LAYOUTBODY = ".layui-layout-body",
let TABFILTER = 'swiftadmin-tabs', BODY = '.layui-body', LAYOUTBODY = ".layui-layout-body",
LAYOUTADMIN = ".layui-layout-admin"
, TABS = BODY + ">.layui-tab", FLEXIBLEID = "flexible", MENUFILTER = "lay-side-menu",
LAYTOPMENU = "lay-top-menu", LAYSIDESHRINK = "layadmin-side-shrink"
@@ -36,10 +36,10 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
BODYSHADECLASS = ".layadmin-body-shade", LAYERCONTENT = ".layui-layer-content";
// 对象初始化
var admin = {
let admin = {
options: {
tplName: 'swiftadmin', // 数据标识
version: '1.2.0', // 版本
version: '1.x', // 版本
moreLabel: true, // 是否开启多标签
cacheTab: true, // 缓存多标签
maxTabNum: 20, // 最大打开标签
@@ -229,12 +229,11 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
iframe = $(TABS + " .layui-tab-item").find("iframe");
for (let i = 0; i < iframe.length; i++) {
var layid = $(iframe[i]).attr('lay-id');
if (layid == id) {
if (layid === id) {
iframe[i].contentWindow.location.reload(true);
$(iframe[i]).next("#loading").css({'overflow': 'hidden', 'display': "block"});
}
}
}
, globalStyleCss: function () {
var css = '<style id="style-light">';
@@ -256,8 +255,6 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
css += '.layadmin-side-shrink .layui-side-menu .layui-nav>.layui-nav-itemed>a{background: #f2f2f2;}';
css += '.layui-nav-tree .layui-nav-child dd.layui-this, .layui-nav-tree .layui-nav-child dd.layui-this a, .layui-nav-tree .layui-this,';
css += '.layui-nav-tree .layui-this>a {background-color: #e6f7ff!important;border-right: 1px solid #1890ff!important;color: #1890ff!important;}';
css += '</style>';
return css;
}
@@ -394,9 +391,7 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
refresh: function () {
admin.refresh(admin.getConfig("activeTab"));
},
back: function () {
},
back: function () {},
theme: function () {
var n = $(this).data("url");
admin.event.popupRight({
@@ -481,15 +476,15 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
if ($(window).width() < 768) {
n.offset = "15px"
} else {
if (window == top) {
if (window === top) {
n.offset = "25%"
} else {
n.offset = "20%"
}
}
}
n.resize = n.resize != undefined ? n.resize : false;
n.shade = n.shade != undefined ? n.shade : 0.1;
n.resize = n.resize !== undefined ? n.resize : false;
n.shade = n.shade !== undefined ? n.shade : 0.1;
return layer.open(n)
}
, pupupTop: function (n) {
@@ -518,7 +513,7 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
n.area || (n.area = "336px");
n.skin || (n.skin = "layui-anim layui-anim-rl layui-layer-adminRight");
n.move = false;
if (n.fixed == undefined) {
if (n.fixed === undefined) {
n.fixed = true
}
@@ -728,6 +723,8 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
postUrl = _global_.app + '/' + _global_.controller + '/' + action;
}
othat.attr("disabled", true);
$.ajax({
url: postUrl,
type: 'post',
@@ -742,6 +739,7 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
}
}
if (res.code === 200) {
switch (reload) {
@@ -765,6 +763,8 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
} else {
layer.error(res.msg)
}
othat.attr("disabled", false);
},
error: function (res) {
layer.msg(i18n.prop('访问方法失败'), 'error');
@@ -960,7 +960,6 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
if (router.supersAdmin === false
&& curl.indexOf('://') === -1 && !recursive(router.authorities)) {
layer.msg(i18n.prop('无权操作'), 'error');
throw '没有权限';
}
}
} catch (e) {
@@ -1543,15 +1542,15 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
*/
form.on('submit(submitIframe)', function (data) {
var that = $(this), _form = that.parents('form'),
let that = $(this), _form = that.parents('form'),
_close = that.data("close") || undefined,
_url = _form.attr("action") || false;
if (_url === false || _url === '') {
try {
var app = _global_.app;
var action = _global_.action;
var controller = _global_.controller;
let app = _global_.app;
let action = _global_.action;
let controller = _global_.controller;
_url = app + '/' + controller + '/' + action;
} catch (error) {
console.warn(error);
@@ -1563,13 +1562,13 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
return false;
}
var _parent = that.data('reload') || false;
let _parent = that.data('reload') || false;
that.attr("disabled", true);
$.post(_url, data.field, function (res) {
if (res.code === 200) {
top.layer.msg(res.msg);
that.attr("disabled", true);
if (_close === undefined) {
admin.event.closeDialog(that);
}
@@ -1588,17 +1587,9 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
if (typeof res.data.__token__ !== 'undefined') {
$('input#__token__').val(res.data.__token__);
}
} catch (e) {
// 默认不处理异常
}
}, 'json');
// 延迟释放按钮
setTimeout(function (e) {
} catch (e) {}
that.attr("disabled", false);
}, 2000);
}, 'json');
return false;
});
@@ -1607,7 +1598,7 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
*/
form.on('submit(formSearch)', function (data) {
var field = data.field;
let field = data.field;
for (const key in field) {
if (!field[key]) {
delete field[key];
@@ -1624,7 +1615,7 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
*/
table.on("tool(lay-tableList)", function (obj) {
var data = obj.data
let data = obj.data
, reqData = {}
, selector = $(this).parents('table').find('tbody tr')
, callback = {
@@ -1788,7 +1779,7 @@ layui.define(['jquery', 'i18n', 'element', 'layer', 'form', 'rate', 'table', 'sl
return false;
}
var data = {};
data = {};
for (var n in field) {
var e = field[n];
field[e] = [];

Binary file not shown.

View File

@@ -23,29 +23,6 @@ use system\Random;
class Request extends \Webman\Http\Request
{
/**
* 用户ID
* @var int
*/
public mixed $user_id = 0;
/**
* 用户信息
*/
public mixed $userData = [];
/**
* 管理员ID
* @var int
*/
public mixed $admin_id = 0;
/**
* 管理员信息
* @return string
*/
public mixed $adminData = [];
/**
* 生成请求令牌
* @access public
@@ -68,7 +45,6 @@ class Request extends \Webman\Http\Request
* @param string $token 令牌名称
* @param array $data 表单数据
* @return bool
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function checkToken(string $token = '__token__', array $data = []): bool
{