修复:用户登录 - 图形验证码校验失败

This commit is contained in:
wuhui_zzw 2024-01-08 16:03:57 +08:00
parent c9d2d37e03
commit a8cc8f3d3f
52 changed files with 1228 additions and 104 deletions

View File

@ -5,6 +5,9 @@ declare (strict_types = 1);
namespace app;
use crmeb\services\SystemConfigService;
use crmeb\services\GroupDataService;
use crmeb\utils\Json;
use think\Service;
/**
@ -12,6 +15,11 @@ use think\Service;
*/
class AppService extends Service
{
public $bind = [
// 'json' => Json::class,
'sysConfig' => SystemConfigService::class,
'sysGroupData' => GroupDataService::class
];
public function register()
{

View File

@ -13,6 +13,11 @@ class Request extends \think\Request
use Macro;
protected $cache = [];
/**
* 不过滤变量名
* @var array
*/
protected $except = ['menu_path', 'api_url', 'unique_auth', 'description', 'custom_form', 'product_detail_diy', 'value'];
public function __construct()
{
@ -125,7 +130,6 @@ class Request extends \think\Request
return $this->file[$name] ?? null;
}
protected function dealUploadFile(array $files, string $name): array
{
$array = [];
@ -184,4 +188,92 @@ class Request extends \think\Request
}
return $array;
}
/**
* 获取get参数
* @param array $params
* @param bool $suffix
* @param bool $filter
* @return array
*/
public function getMore(array $params, bool $suffix = false, bool $filter = true): array
{
return $this->more($params, $suffix, $filter);
}
/**
* 获取post参数
* @param array $params
* @param bool $suffix
* @param bool $filter
* @return array
*/
public function postMore(array $params, bool $suffix = false, bool $filter = true): array
{
return $this->more($params, $suffix, $filter);
}
/**
* 获取请求的数据
* @param array $params
* @param bool $suffix
* @param bool $filter
* @return array
*/
public function more(array $params, bool $suffix = false, bool $filter = true): array
{
$p = [];
$i = 0;
foreach ($params as $param) {
if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $this->filterWord(is_string($this->param($param)) ? trim($this->param($param)) : $this->param($param), $filter && !in_array($param, $this->except));
} else {
if (!isset($param[1])) $param[1] = null;
if (!isset($param[2])) $param[2] = '';
if (is_array($param[0])) {
$name = is_array($param[1]) ? $param[0][0] . '/a' : $param[0][0] . '/' . $param[0][1];
$keyName = $param[0][0];
} else {
$name = is_array($param[1]) ? $param[0] . '/a' : $param[0];
$keyName = $param[0];
}
$p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $keyName)] = $this->filterWord(is_string($this->param($name, $param[1], $param[2])) ? trim($this->param($name, $param[1], $param[2])) : $this->param($name, $param[1], $param[2]), $filter && !in_array($keyName, $this->except));
}
}
return $p;
}
/**
* 过滤接受的参数
* @param $str
* @param bool $filter
* @return array|mixed|string|string[]
*/
public function filterWord($str, bool $filter = true)
{
if (!$str || !$filter) return $str;
// 把数据过滤
$farr = [
"/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
"/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
"/select|join|where|drop|like|modify|rename|insert|update|table|database|alter|truncate|\'|\/\*|\.\.\/|\.\/|union|into|load_file|outfile/is"
];
if (is_array($str)) {
foreach ($str as &$v) {
if (is_array($v)) {
foreach ($v as &$vv) {
if (!is_array($vv)) $vv = preg_replace($farr, '', $vv);
}
} else {
$v = preg_replace($farr, '', $v);
}
}
} else {
$str = preg_replace($farr, '', $str);
}
return $str;
}
}

View File

@ -8,6 +8,7 @@ use app\common\repositories\system\groupData\GroupDataRepository;
use crmeb\services\UploadService;
use Swoole\Lock;
use think\db\BaseQuery;
use think\facade\Log;
if (!function_exists('go')) {
function go(): bool
@ -243,7 +244,7 @@ if (!function_exists('getModelTime')) {
$model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('yesterday')), date('Y-m-d H:i:s', strtotime('today -1second'))]);
break;
case 'quarter':
list($startTime, $endTime) = getMonth();
[$startTime, $endTime] = getMonth();
$model = $model->where($prefix, '>', $startTime);
$model = $model->where($prefix, '<', $endTime);
break;
@ -255,7 +256,7 @@ if (!function_exists('getModelTime')) {
break;
default:
if (strstr($section, $field) !== false) {
list($startTime, $endTime) = explode($field, $section);
[$startTime, $endTime] = explode($field, $section);
if (strlen($startTime) == 4) {
$model->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($section)), date('Y-m-d H:i:s', strtotime($section . ' +1day -1second')));
} else {
@ -427,7 +428,7 @@ if (!function_exists('getStartModelTime')) {
case 'year':
return date('Y-m-d', strtotime('this year 1/1'));
case 'quarter':
list($startTime, $endTime) = getMonth();
[$startTime, $endTime] = getMonth();
return $startTime;
case 'lately7':
return date('Y-m-d', strtotime("-7 day"));
@ -435,7 +436,7 @@ if (!function_exists('getStartModelTime')) {
return date('Y-m-d', strtotime("-30 day"));
default:
if (strstr($section, '-') !== false) {
list($startTime, $endTime) = explode('-', $section);
[$startTime, $endTime] = explode('-', $section);
return date('Y-m-d H:i:s', strtotime($startTime));
}
return date('Y-m-d H:i:s');
@ -779,7 +780,7 @@ if (!function_exists('setSharePoster')) {
if (isset($config['text']) && !empty($config['text'])) {
foreach ($config['text'] as $key => $val) {
$val = array_merge($textDefault, $val);
list($R, $G, $B) = explode(',', $val['fontColor']);
[$R, $G, $B] = explode(',', $val['fontColor']);
$fontColor = imagecolorallocate($imageRes, $R, $G, $B);
$val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
$val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
@ -1053,9 +1054,11 @@ if (!function_exists('aj_captcha_check_two')) {
* @param string $pointJson
* @return bool
*/
function aj_captcha_check_two(string $captchaType, string $captchaVerification )
function aj_captcha_check_two(string $captchaType, string $captchaVerification,string $token)
{
aj_get_serevice($captchaType)->verificationByEncryptCode($captchaVerification);
// aj_get_serevice($captchaType)->verificationByEncryptCode($captchaVerification);
aj_get_serevice($captchaType)->verificationByEncryptCodeV2($captchaVerification,$token);
return true;
}
}
@ -1088,6 +1091,7 @@ if (!function_exists('aj_get_serevice')) {
default:
throw new \think\exception\ValidateException('captchaType参数不正确'.$captchaType);
}
return $service;
}
}
@ -1117,5 +1121,125 @@ if (!function_exists('checkSuffix')) {
}
}
if (!function_exists('sys_data')) {
/**
* 获取系统单个配置
* @param string $name
* @return string
*/
function sys_data(string $name, int $limit = 0)
{
return app('sysGroupData')->getData($name, $limit);
}
}
if (!function_exists('sys_config')) {
/**
* 获取系统单个配置
* @param string $name
* @param string $default
* @return string
*/
function sys_config(string $name, $default = '')
{
if (empty($name))
return $default;
$sysConfig = app('sysConfig')->get($name);
if (is_array($sysConfig)) {
foreach ($sysConfig as &$item) {
if (strpos($item, '/uploads/system/') !== false || strpos($item, '/statics/system_images/') !== false) $item = set_file_url($item);
}
} else {
if (strpos($sysConfig, '/uploads/system/') !== false || strpos($sysConfig, '/statics/system_images/') !== false) $sysConfig = set_file_url($sysConfig);
}
$config = is_array($sysConfig) ? $sysConfig : trim($sysConfig);
if ($config === '' || $config === false) {
return $default;
} else {
return $config;
}
}
}
if (!function_exists('set_file_url')) {
/**
* 设置附加路径
* @param $url
* @return bool
*/
function set_file_url($image, $siteUrl = '')
{
if (!strlen(trim($siteUrl))) $siteUrl = sys_config('site_url');
if (!$image) return $image;
if (is_array($image)) {
foreach ($image as &$item) {
$domainTop1 = substr($item, 0, 4);
$domainTop2 = substr($item, 0, 2);
if ($domainTop1 != 'http' && $domainTop2 != '//')
$item = $siteUrl . str_replace('\\', '/', $item);
}
} else {
$domainTop1 = substr($image, 0, 4);
$domainTop2 = substr($image, 0, 2);
if ($domainTop1 != 'http' && $domainTop2 != '//')
$image = $siteUrl . str_replace('\\', '/', $image);
}
return $image;
}
}
if (!function_exists('debug')) {
function debug($info){
echo "<pre>";
print_r($info);
die;
}
}
if (!function_exists('debugLog')) {
function debugLog($info,$title = '调试信息'){
Log::info("{$title}".var_export($info,1));
}
}
if (!function_exists('sort_list_tier')) {
/**
* 分级排序
* @param $data
* @param int $pid
* @param string $field
* @param string $pk
* @param string $html
* @param int $level
* @param bool $clear
* @return array
*/
function sort_list_tier($data, $pid = 0, $field = 'pid', $pk = 'id', $html = '|-----', $level = 1, $clear = true)
{
static $list = [];
if ($clear) $list = [];
foreach ($data as $k => $res) {
if ($res[$field] == $pid) {
$res['html'] = str_repeat($html, $level);
$list[] = $res;
unset($data[$k]);
sort_list_tier($data, $res[$pk], $field, $pk, $html, $level + 1, false);
}
}
return $list;
}
}
if (!function_exists('get_file_link')) {
/**
* 获取文件带域名的完整路径
* @param string $link
* @return string
*/
function get_file_link(string $link)
{
if (!$link) {
return '';
}
if (substr($link, 0, 4) === "http" || substr($link, 0, 2) === "//") {
return $link;
} else {
return app()->request->domain() . $link;
}
}
}

View File

@ -387,4 +387,36 @@ class MenuDao extends BaseDao
->where('is_menu',$isMenu)
->order('path ASC')->find();
}
/**
* 获取权限菜单列表
* @param array $where
* @param array $field
* @return \think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getMenusRoule(array $where, ?array $field = [])
{
if (!$field) {
// $field = ['menu_id', 'menu_name', 'icon', 'pid', 'sort', 'menu_path', 'is_show', 'header', 'is_header', 'is_show_path'];
$field = ['*'];
}
return $this->search($where)->field($field)->order('sort DESC,menu_id DESC')->failException(false)->append(['id'])->select();
}
/**
* 获取菜单中的唯一权限
* @param array $where
* @return array
*/
public function getMenusUnique(array $where)
{
return [];//$this->search($where)->where('unique_auth', '<>', '')->column('unique_auth', '');
}
}

View File

@ -16,6 +16,7 @@ use app\Request;
use app\services\supplier\LoginServices;
use crmeb\interfaces\MiddlewareInterface;
use think\facade\Config;
use think\Response;
/**
* Class AuthTokenMiddleware
@ -32,7 +33,7 @@ class AuthTokenMiddleware implements MiddlewareInterface
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function handle(Request $request, \Closure $next)
public function handle(Request $request, \Closure $next): Response
{
$token = trim(ltrim($request->header(Config::get('cookie.token_name', 'Authori-zation')), 'Bearer'));
/** @var LoginServices $services */

View File

@ -7,6 +7,7 @@ namespace app\common\model\system\admin;
use app\common\model\BaseModel;
use app\common\model\system\auth\Role;
use app\model\supplier\SystemSupplier;
class Admin extends BaseModel
{
@ -68,4 +69,18 @@ class Admin extends BaseModel
{
$query->whereLike('real_name',"%{$value}%");
}
/**
* 供应商
* @return \think\model\relation\HasOne
*/
public function supplier()
{
return $this->hasOne(SystemSupplier::class, 'admin_id', 'admin_id')->field(['id', 'supplier_name', 'admin_id', 'avatar', 'is_show'])->bind([
'supplier_id' => 'id',
'supplier_name',
'avatar',
'is_show'
]);
}
}

View File

@ -32,7 +32,7 @@ class Common extends AuthController
public function getLogo(SystemSupplierServices $supplierServices)
{
$supplier = $supplierServices->get((int)$this->supplierId, ['id', 'name']);
return $this->success([
return app('json')->success('' ,[
'logo' => sys_config('site_logo'),
'logo_square' => sys_config('site_logo_square'),
'site_name' => $supplier && isset($supplier['name']) && $supplier['name'] ? $supplier['name'] : sys_config('site_name')
@ -44,7 +44,7 @@ class Common extends AuthController
*/
public function getConfig()
{
return $this->success([
return app('json')->success('' , [
'tengxun_map_key' => sys_config('tengxun_map_key'),
'open_erp' => !!sys_config('erp_open')
]);
@ -57,7 +57,7 @@ class Common extends AuthController
*/
public function city(CityAreaServices $services, $pid = 0)
{
return $this->success($services->getCityTreeList((int)$pid));
return app('json')->success('' , $services->getCityTreeList((int)$pid));
}
/**
@ -91,7 +91,8 @@ class Common extends AuthController
}
$data[$key]['menu_path'] = preg_replace('/^\/cashier/', '', $item['menu_path']);
}
return $this->success(sort_list_tier($data));
return app('json')->success('' , sort_list_tier($data));
}
/**
@ -106,7 +107,8 @@ class Common extends AuthController
], true);
$time = $orderServices->timeHandle($time, true);
$data = $orderServices->homeStatics((int)$this->supplierId, $time);
return $this->success($data);
return app('json')->success('' , $data);
}
/**
@ -121,7 +123,8 @@ class Common extends AuthController
], true);
$time = $orderServices->timeHandle($time, true);
$data = $orderServices->orderCharts((int)$this->supplierId, $time);
return $this->success($data);
return app('json')->success('' , $data);
}
/**
@ -136,7 +139,8 @@ class Common extends AuthController
], true);
$time = $orderServices->timeHandle($time, true);
$data = $orderServices->getOrderType((int)$this->supplierId, $time);
return $this->success($data);
return app('json')->success('' , $data);
}
/**
@ -151,7 +155,8 @@ class Common extends AuthController
], true);
$time = $orderServices->timeHandle($time, true);
$data = $orderServices->getOrderChannel((int)$this->supplierId, $time);
return $this->success($data);
return app('json')->success('' , $data);
}
/**
@ -182,7 +187,8 @@ class Common extends AuthController
'url' => '/' . config('admin.supplier_prefix') . '/order/refund'
];
}
return $this->success($this->noticeData($value));
return app('json')->success('' , $value);
}
/**
@ -251,14 +257,14 @@ class Common extends AuthController
*/
public function getCopyright()
{
try {
$copyright = $this->__z6uxyJQ4xYa5ee1mx5();
} catch (\Throwable $e) {
// try {
// $copyright = $this->__z6uxyJQ4xYa5ee1mx5();
// } catch (\Throwable $e) {
$copyright = ['copyrightContext' => '', 'copyrightImage' => ''];
}
// }
$copyright['version'] = get_crmeb_version();
$copyright['extract_min_price'] = sys_config('supplier_extract_min_price');
$copyright['extract_max_price'] = sys_config('supplier_extract_max_price');
return $this->success($copyright);
return app('json')->success('' , $copyright);
}
}

View File

@ -14,7 +14,7 @@ namespace app\controller\supplier;
use app\Request;
use crmeb\utils\Captcha;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService;
use app\services\supplier\LoginServices;
use think\exception\ValidateException;
use app\validate\api\user\RegisterValidates;
@ -81,6 +81,7 @@ class Login
['pointJson', ''],
['captchaType', ''],
], true);
try {
aj_captcha_check_one($captchaType, $token, $pointJson);
return app('json')->success();
@ -117,7 +118,8 @@ class Login
*/
public function login(Request $request)
{
[$account, $password, $captchaType, $captchaVerification] = $request->postMore([
[$token,$account, $password, $captchaType, $captchaVerification] = $request->postMore([
['token', ''],
'account',
'pwd',
['captchaType', ''],
@ -134,15 +136,15 @@ class Login
}
//二次验证
try {
aj_captcha_check_two($captchaType, $captchaVerification);
aj_captcha_check_two($captchaType, $captchaVerification, $token);
} catch (\Throwable $e) {
return app('json')->fail($e->getError());
return app('json')->fail($e->getMessage());
}
}
$res = $this->services->login($account, $password, 'supplier');
if ($res) {
Cache::delete($key);
}
if ($res) Cache::delete($key);
return app('json')->success($res);
}
@ -155,7 +157,7 @@ class Login
public function logout(Request $request)
{
$key = trim(ltrim($request->header(Config::get('cookie.token_name')), 'Bearer'));
CacheService::redisHandler()->delete(md5($key));
SupplierCacheService::redisHandler()->delete(md5($key));
return app('json')->success();
}
@ -172,7 +174,7 @@ class Login
} catch (ValidateException $e) {
return app('json')->fail($e->getError());
}
$verifyCode = CacheService::get('code_' . $account);
$verifyCode = SupplierCacheService::get('code_' . $account);
if (!$verifyCode)
return app('json')->fail('请先获取验证码');
$verifyCode = substr($verifyCode, 0, 6);
@ -184,7 +186,7 @@ class Login
if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
$resetStatus = $this->services->reset($account, $password);
if ($resetStatus) {
CacheService::delete('code_' . $account);
SupplierCacheService::delete('code_' . $account);
return app('json')->success('修改成功');
}
return app('json')->fail('修改失败');

View File

@ -9,4 +9,6 @@ return [
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class
// 跨域支持
// \think\middleware\AllowCrossDomain::class
];

View File

@ -42,7 +42,7 @@ class SystemSupplier extends BaseModel
*/
public function admin()
{
return $this->hasOne(Admin::class, 'id', 'admin_id')->field(['id', 'account', 'pwd', 'admin_type', 'is_del', 'level', 'roles'])->bind([
return $this->hasOne(Admin::class, 'admin_id', 'admin_id')->field(['admin_id', 'account', 'pwd', 'admin_type', 'is_del', 'level', 'roles'])->bind([
'account',
'pwd',
'admin_type',

View File

@ -24,7 +24,7 @@ use app\services\product\sku\StoreProductAttrServices;
use app\services\product\sku\StoreProductAttrValueServices;
use app\services\store\SystemStoreServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
/**
* 活动

View File

@ -29,7 +29,7 @@ use app\services\system\attachment\SystemAttachmentServices;
use app\services\user\UserServices;
use app\jobs\product\ProductLogJob;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\UploadService;
use crmeb\services\UtilService;
use crmeb\services\wechat\MiniProgram;

View File

@ -31,7 +31,7 @@ use app\services\product\sku\StoreProductAttrValueServices;
use app\jobs\product\ProductLogJob;
use app\services\user\UserServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\SystemConfigService;
use think\exception\ValidateException;

View File

@ -21,7 +21,7 @@ use app\services\other\QrcodeServices;
use app\services\user\UserServices;
use app\services\system\attachment\SystemAttachmentServices;
use app\jobs\activity\pink\PinkJob;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\UploadService;
use crmeb\services\UtilService;
use crmeb\services\wechat\MiniProgram;

View File

@ -20,7 +20,7 @@ use app\services\product\sku\StoreProductAttrServices;
use app\services\product\sku\StoreProductAttrValueServices;
use app\services\user\label\UserLabelServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
/**
* 优惠套餐

View File

@ -25,7 +25,7 @@ use app\services\product\sku\StoreProductAttrServices;
use app\services\product\sku\StoreProductAttrValueServices;
use app\jobs\product\ProductLogJob;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;
/**

View File

@ -22,7 +22,7 @@ use app\services\user\label\UserLabelRelationServices;
use app\services\user\UserMoneyServices;
use app\services\user\UserServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;
/**

View File

@ -33,7 +33,7 @@ use app\services\product\sku\StoreProductAttrServices;
use app\services\product\sku\StoreProductAttrValueServices;
use app\jobs\product\ProductLogJob;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\SystemConfigService;
use think\exception\ValidateException;

View File

@ -21,7 +21,7 @@ use app\services\order\StoreOrderCartInfoServices;
use app\services\order\StoreOrderServices;
use app\services\system\config\ConfigServices;
use app\services\wechat\WechatUserServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;

View File

@ -25,7 +25,7 @@ use app\services\user\UserServices;
use app\services\wechat\WechatQrcodeServices;
use app\services\wechat\WechatReplyServices;
use app\services\wechat\WechatUserServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\SystemConfigService;
use crmeb\services\wechat\Messages;
use crmeb\services\wechat\OfficialAccount;

View File

@ -34,7 +34,7 @@ use app\services\user\member\MemberCardServices;
use app\services\user\UserAddressServices;
use app\services\user\UserServices;
use app\jobs\product\ProductLogJob;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\traits\OptionTrait;
use crmeb\traits\ServicesTrait;
use think\exception\ValidateException;

View File

@ -13,7 +13,7 @@ namespace app\services\order;
use app\dao\order\StoreOrderCartInfoDao;
use app\services\BaseServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\SystemConfigService;
use crmeb\traits\OptionTrait;
use crmeb\traits\ServicesTrait;

View File

@ -27,7 +27,7 @@ use app\services\product\shipping\ShippingTemplatesRegionServices;
use app\services\product\shipping\ShippingTemplatesServices;
use app\services\wechat\WechatUserServices;
use app\services\BaseServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use app\common\dao\store\order\StoreOrderDao;
use app\services\user\UserServices;
use crmeb\traits\ServicesTrait;

View File

@ -30,7 +30,7 @@ use app\services\user\UserMoneyServices;
use app\services\user\UserServices;
use app\services\wechat\WechatUserServices;
use crmeb\services\AliPayService;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\FormBuilder as Form;
use crmeb\services\wechat\Payment;
use crmeb\traits\ServicesTrait;

View File

@ -34,7 +34,7 @@ use app\services\product\product\StoreProductReplyServices;
use app\services\user\UserAddressServices;
use app\services\user\level\UserLevelServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService;
use crmeb\services\FileService;
use crmeb\services\FormBuilder as Form;
use crmeb\services\printer\Printer;
@ -1744,7 +1744,7 @@ HTML;
/** @var StoreOrderCreateServices $storeOrderCreateService */
$storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
$key = md5($storeOrderCreateService->getNewOrderId((string)$uid) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8));
CacheService::redisHandler()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other', 'addr', 'invalidCartInfo', 'deduction'), $cacheTime);
SupplierCacheService::redisHandler()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other', 'addr', 'invalidCartInfo', 'deduction'), $cacheTime);
return $key;
}
@ -1757,8 +1757,8 @@ HTML;
public function getCacheOrderInfo(int $uid, string $key)
{
$cacheName = 'user_order_' . $uid . $key;
if (!CacheService::redisHandler()->has($cacheName)) return null;
return CacheService::redisHandler()->get($cacheName);
if (!SupplierCacheService::redisHandler()->has($cacheName)) return null;
return SupplierCacheService::redisHandler()->get($cacheName);
}
/**
@ -2650,7 +2650,7 @@ HTML;
if ($new) {
$cartIds = explode(',', $cartIds);
$cartInfo = [];
$redis = CacheService::redisHandler();
$redis = SupplierCacheService::redisHandler();
foreach ($cartIds as $key) {
$info = $redis->get($key);
if ($info) {

View File

@ -18,7 +18,7 @@ use think\facade\Log;
use app\services\BaseServices;
use crmeb\traits\ServicesTrait;
use app\dao\order\StoreOrderDao;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;
use app\services\order\StoreOrderCartInfoServices;

View File

@ -15,7 +15,7 @@ namespace app\services\other;
use app\dao\other\CityAreaDao;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\FormBuilder as Form;
/**

View File

@ -16,7 +16,7 @@ use app\dao\other\ExpressDao;
use app\services\BaseServices;
use app\services\serve\ServeServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\ExpressService;
use crmeb\services\FormBuilder as Form;

View File

@ -15,7 +15,7 @@ namespace app\services\other;
use app\dao\other\SystemCityDao;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\FormBuilder as Form;
/**

View File

@ -28,7 +28,7 @@ use app\services\user\label\UserLabelRelationServices;
use app\services\user\label\UserLabelServices;
use app\services\user\UserServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;
use think\facade\Log;

View File

@ -19,7 +19,7 @@ use app\services\order\StoreOrderCartInfoServices;
use app\services\order\StoreOrderServices;
use app\services\user\UserServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;
/**

View File

@ -15,7 +15,7 @@ namespace app\services\product\shipping;
use app\dao\product\shipping\ShippingTemplatesFreeDao;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\utils\Arr;
/**

View File

@ -15,7 +15,7 @@ namespace app\services\product\shipping;
use app\dao\product\shipping\ShippingTemplatesRegionDao;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\utils\Arr;
/**

View File

@ -16,7 +16,7 @@ use app\services\BaseServices;
use app\dao\product\shipping\ShippingTemplatesDao;
use app\services\product\product\StoreProductServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
/**
* 运费模板

View File

@ -26,7 +26,7 @@ use app\services\product\product\StoreProductStockRecordServices;
// use app\webscoket\SocketPush;
use crmeb\exceptions\AdminException;
use app\services\product\product\StoreProductServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\traits\ServicesTrait;
use think\exception\ValidateException;

View File

@ -21,7 +21,7 @@ use app\services\system\SystemRoleServices;
use crmeb\exceptions\AdminException;
use app\dao\system\admin\SystemAdminDao;
use crmeb\exceptions\AuthException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService;
use crmeb\traits\ServicesTrait;
use crmeb\utils\ApiErrorCode;
use crmeb\utils\JwtAuth;
@ -107,8 +107,7 @@ class LoginServices extends BaseServices
$supplierInfo->last_ip = app('request')->ip();
$supplierInfo->login_count++;
$supplierInfo->save();
$tokenInfo = $this->createToken($supplierInfo['id'], $type, $supplierInfo->pwd);
$tokenInfo = $this->createToken($supplierInfo['admin_id'], $type, $supplierInfo->pwd);
/** @var SystemMenusServices $services */
$services = app()->make(SystemMenusServices::class);
[$menus, $uniqueAuth] = $services->getMenusList($supplierInfo->roles, 0, 4);
@ -119,9 +118,9 @@ class LoginServices extends BaseServices
'menus' => $menus,
'unique_auth' => $uniqueAuth,
'user_info' => [
'id' => $supplierInfo->getData('id'),
'id' => $supplierInfo->getData('admin_id'),
'account' => $supplierInfo->getData('account'),
'avatar' => $supplierInfo->getData('head_pic'),
'avatar' => $supplierInfo->getData('avatar'),
],
'logo' => sys_config('site_logo'),
'logo_square' => sys_config('site_logo_square'),
@ -157,21 +156,21 @@ class LoginServices extends BaseServices
*/
public function parseToken(string $token): array
{
/** @var CacheService $cacheService */
$cacheService = app()->make(CacheService::class);
/** @var SupplierCacheService $supplierCacheService */
$supplierCacheService = app()->make(SupplierCacheService::class);
if (!$token || $token === 'undefined') {
throw new AuthException(ApiErrorCode::ERR_LOGIN);
}
//检测token是否过期
$md5Token = md5($token);
if (!$cacheService->hasToken($md5Token) || !($cacheToken = $cacheService->getTokenBucket($md5Token))) {
if (!$supplierCacheService->hasToken($md5Token) || !($cacheToken = $supplierCacheService->getTokenBucket($md5Token))) {
throw new AuthException(ApiErrorCode::ERR_LOGIN);
}
//是否超出有效次数
if (isset($cacheToken['invalidNum']) && $cacheToken['invalidNum'] >= 3) {
if (!request()->isCli()) {
$cacheService->clearToken($md5Token);
$supplierCacheService->clearToken($md5Token);
}
throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
}
@ -183,28 +182,24 @@ class LoginServices extends BaseServices
//验证token
try {
$jwtAuth->verifyToken();
$cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
$supplierCacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
} catch (ExpiredException $e) {
$cacheToken['invalidNum'] = isset($cacheToken['invalidNum']) ? $cacheToken['invalidNum']++ : 1;
$cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
$supplierCacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
} catch (\Throwable $e) {
if (!request()->isCli()) {
$cacheService->clearToken($md5Token);
$supplierCacheService->clearToken($md5Token);
}
throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
}
//获取管理员信息
$adminInfo = $this->adminDao->getOne(['id' => $id, 'is_del' => 0, 'status' => 1]);
if(!$adminInfo){
throw new AuthException(ApiErrorCode::ERR_ADMINID_VOID);
}
if ($auth !== md5($adminInfo->pwd)) {
throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
}
$supplierInfo = $this->dao->getOne(['id' =>(int)$adminInfo->relation_id, 'is_del' => 0], '*', ['admin']);
$adminInfo = $this->adminDao->getOne(['admin_id' => $id, 'is_del' => 0, 'status' => 1]);
if(!$adminInfo) throw new AuthException(ApiErrorCode::ERR_ADMINID_VOID);
if ($auth !== md5($adminInfo->pwd)) throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
$supplierInfo = $this->dao->getOne(['admin_id' =>(int)$adminInfo->admin_id, 'is_del' => 0], '*', ['admin']);
if (!$supplierInfo || !$supplierInfo->account || $supplierInfo->admin_is_del) {
if (!request()->isCli()) {
$cacheService->clearToken($md5Token);
$supplierCacheService->clearToken($md5Token);
}
throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS);
}

View File

@ -18,7 +18,7 @@ use app\dao\system\SystemRoleDao;
use app\services\store\SystemStoreStaffServices;
use crmeb\exceptions\AuthException;
use crmeb\utils\ApiErrorCode;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
/**

View File

@ -19,7 +19,7 @@ use app\services\user\UserExtractServices;
use crmeb\exceptions\AdminException;
use app\common\dao\system\admin\AdminDao;
use app\services\system\SystemMenusServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\FormBuilder;
use app\services\system\SystemRoleServices;
use crmeb\services\SystemConfigService;

View File

@ -17,7 +17,7 @@ use app\services\BaseServices;
use app\common\dao\user\UserDao;
use app\services\message\sms\SmsRecordServices;
use app\services\wechat\WechatUserServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\exception\ValidateException;
use think\facade\Config;

View File

@ -17,7 +17,7 @@ use app\dao\user\UserBillDao;
use app\services\user\level\UserLevelServices;
use think\Exception;
use think\exception\ValidateException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use think\facade\Log;
/**

View File

@ -17,7 +17,7 @@ use app\services\BaseServices;
use app\services\order\StoreOrderCartInfoServices;
use app\services\order\StoreOrderServices;
use think\exception\ValidateException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
/**
* 用户佣金

View File

@ -14,7 +14,7 @@ namespace app\services\user;
use app\dao\user\UserMoneyDao;
use app\services\BaseServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\exceptions\AdminException;
/**

View File

@ -43,7 +43,7 @@ use app\services\wechat\WechatUserServices;
use app\services\work\WorkClientServices;
use app\services\work\WorkMemberServices;
use crmeb\exceptions\AdminException;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\FormBuilder as Form;
use crmeb\services\FormBuilder;
use crmeb\services\SystemConfigService;

View File

@ -14,7 +14,7 @@ namespace app\services\user\label;
use app\dao\other\CategoryDao;
use app\services\BaseServices;
use crmeb\services\CacheService;
use crmeb\services\SupplierCacheService as CacheService;
use crmeb\services\FormBuilder;
use crmeb\traits\ServicesTrait;
use think\exception\ValidateException;

View File

@ -0,0 +1,54 @@
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\validate\supplier;
use think\Validate;
class SupplierTicketPrintValidate extends Validate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'develop_id' => 'require|gt:0',
'api_key' => 'require|max:100',
'client_id' => 'require|max:100',
'terminal_number' => 'require|max:100',
'status' => 'require|number',
];
/**
* 定义错误信息
* 格式:'字段名.规则名' => '错误信息'
*
* @var array
*/
protected $message = [
'develop_id.require' => '请填写用户ID',
'develop_id.gt' => '用户ID参数错误',
'api_key.require' => '请填写秘钥',
'api_key.max' => '秘钥最多不能超过100个字符',
'client_id.require' => '请填写应用ID',
'client_id.max' => '应用ID最多不能超过100个字符',
'terminal_number.require' => '请填写终端号',
'terminal_number.max' => '终端号最多不能超过100个字符',
'status.require' => '开关',
'status.number' => '开关',
];
protected $scene = [
'update' => ['develop_id', 'api_key', 'client_id', 'terminal_number', 'status'],
];
}

View File

@ -0,0 +1,74 @@
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\validate\supplier;
use think\Validate;
class SystemSupplierValidate extends Validate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'supplier_name' => 'require|max:25',
'name' => 'max:25',
'phone' => 'require|mobile',
'email' => 'email|max:50',
'address' => 'max:255',
'province' => 'require|gt:0',
'city' => 'require|gt:0',
'area' => 'require|gt:0',
'detailed_address' => 'max:255',
'account' => 'require|length:4,64',
'pwd' => ['require', 'length:4,64'],
'mark' => 'max:255',
];
/**
* 定义错误信息
* 格式:'字段名.规则名' => '错误信息'
*
* @var array
*/
protected $message = [
'supplier_name.require' => '请填写供应商名称',
'supplier_name.max' => '供应商名称最多不能超过25个字符',
'name.max' => '名称最多不能超过25个字符',
'phone.require' => '请填写手机号',
'phone.mobile' => '手机号格式不正确',
'email.email' => '邮箱格式不正确',
'email.max' => '邮箱最多不能超过100个字符',
'address.max' => '供应商地址最多不能超过255个字符',
'mark.max' => '备注最多不能超过255个字符',
'province.require' => '请选择省份',
'province.gt' => '请选择省份',
'city.require' => '请选择城市',
'city.gt' => '请选择城市',
'area.require' => '请选择地区',
'area.gt' => '请选择地区',
'detailed_address.max' => '详细地址最多不能超过255个字符',
'account.require' => '请填写供应商登录用户名',
'account.length' => '供应商登录用户名4-64长度字符',
'pwd.require' => '请输入密码',
'pwd.length' => '密码长度4-64位字符',
];
protected $scene = [
'login' => ['account', 'pwd'],
'update' => ['supplier_name', 'name', 'phone', 'email', 'address', 'detailed_address', 'province', 'city', 'area'],
'save' => ['supplier_name', 'name', 'phone', 'email', 'address', 'detailed_address', 'province', 'city', 'area','account', 'pwd', 'mark'],
'admin_update' => ['supplier_name', 'name', 'phone', 'email', 'address', 'detailed_address', 'province', 'city', 'area','account', 'mark'],
];
}

View File

@ -20,6 +20,14 @@ class BlockPuzzleCaptchaService extends baseBlockPuzzleCaptchaService
$this->setOriginData($token);
//数据处理类
$blockData = $this->factory->makeBlockData();
// 数据处理 解密处理
$pattern = '/^[a-zA-Z0-9\/\r\n+]*={0,2}$/'; // Base64编码规则正则表达式
$isBase64 = preg_match($pattern, $pointJson);
if($isBase64){
// 如果是base64 则是加密数据,需要解密
$decoded = base64_decode($pointJson);
$pointJson = openssl_decrypt($decoded, 'AES-128-ECB', $this->originData['secretKey'],OPENSSL_RAW_DATA,NULL);
}
$pointJson = json_decode($pointJson);
//解码出来的前端坐标
$targetPoint = new PointVo($pointJson->x, $pointJson->y);
@ -35,12 +43,9 @@ class BlockPuzzleCaptchaService extends baseBlockPuzzleCaptchaService
}
}
public function verificationByEncryptCode(string $encryptCode)
{
public function verificationByEncryptCode(string $encryptCode){
$result = explode('---',$encryptCode);
if(empty($result)){
throw new ParamException('参数错误!');
}
if(empty($result)) throw new ParamException('参数错误!');
$this->validate($result[0], $result[1], function () use ($result,$encryptCode) {
$cacheEntity = $this->factory->getCacheInstance();
$cacheEntity->delete($result['token']);
@ -48,4 +53,33 @@ class BlockPuzzleCaptchaService extends baseBlockPuzzleCaptchaService
});
}
public function verificationByEncryptCodeV2(string $encryptCode,string $token){
$decoded = base64_decode($encryptCode);
if($decoded !== false && json_last_error() === JSON_ERROR_NONE){
//获取并设置 $this->originData
$this->setOriginData($token);
// 如果是base64 则是加密数据,需要解密
$encryptCode = openssl_decrypt($decoded, 'AES-128-ECB', $this->originData['secretKey'],OPENSSL_RAW_DATA,NULL);
}
$result = explode('---',$encryptCode);
if(empty($result)) throw new ParamException('参数错误!');
$this->validate($result[0], $result[1], function () use ($result,$encryptCode) {
$cacheEntity = $this->factory->getCacheInstance();
$cacheEntity->delete($result['token']);
$cacheEntity->delete($encryptCode);
});
}
}

View File

@ -5,6 +5,7 @@ namespace crmeb\services;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Cache as CacheStatic;
use think\facade\Config;
/**
@ -157,4 +158,63 @@ class CacheService
return $this->handler->remember($this->cacheKey($key), $value, $expire);
}
/**
* 放入令牌桶
* @param string $key
* @param array $value
* @param string $type
* @return bool
*/
public static function setTokenBucket(string $key, $value, $expire = null, string $type = 'admin')
{
try {
$redisCahce = self::redisHandler($type);
return $redisCahce->set($key, $value, $expire);
} catch (\Throwable $e) {
return false;
}
}
/**
* 获取token令牌桶
* @param string $key
* @return mixed|null
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public static function getTokenBucket(string $key)
{
try {
return self::redisHandler()->get($key, null);
} catch (\Throwable $e) {
return null;
}
}
/**
* 查看令牌是否存在
* @param string $key
* @return bool
*/
public static function hasToken(string $key)
{
try {
return self::redisHandler()->has($key);
} catch (\Throwable $e) {
return false;
}
}
/**
* Redis缓存句柄
*
* @return \think\cache\TagSet|CacheStatic
*/
public static function redisHandler(string $type = null)
{
if ($type) {
return CacheStatic::store('redis')->tag($type);
} else {
return CacheStatic::store('redis');
}
}
}

View File

@ -0,0 +1,88 @@
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace crmeb\services;
use app\services\system\config\SystemGroupDataServices;
/**
* 获取组合数据配置
* Class GroupDataService
* @package crmeb\services
*/
class GroupDataService
{
/**
* 获取单个值
* @param string $config_name 配置名称
* @param int $limit 截取多少条
* @param bool $isCaChe 是否读取缓存
* @return array
*/
public static function getData(string $config_name, int $limit = 0, bool $isCaChe = false): array
{
$callable = function () use ($config_name, $limit) {
event('get.config');
try {
/** @var SystemGroupDataServices $service */
$service = app()->make(SystemGroupDataServices::class);
return $service->getConfigNameValue($config_name, $limit);
} catch (\Exception $e) {
return [];
}
};
try {
$cacheName = $limit ? "data_{$config_name}_{$limit}" : "data_{$config_name}";
if ($isCaChe)
return $callable();
return CacheService::get($cacheName, $callable);
} catch (\Throwable $e) {
return $callable();
}
}
/**
* 根据id 获取单个值
* @param int $id
* @param bool $isCaChe 是否读取缓存
* @return array
*/
public static function getDataNumber(int $id, bool $isCaChe = false): array
{
$callable = function () use ($id) {
try {
/** @var SystemGroupDataServices $service */
$service = app()->make(SystemGroupDataServices::class);
$data = $service->getDateValue($id);
if (is_object($data))
$data = $data->toArray();
return $data;
} catch (\Exception $e) {
return [];
}
};
try {
$cacheName = "data_number_{$id}";
if ($isCaChe)
return $callable();
return CacheService::get($cacheName, $callable);
} catch (\Throwable $e) {
return $callable();
}
}
}

View File

@ -0,0 +1,407 @@
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace crmeb\services;
use think\facade\Cache as CacheStatic;
/**
* crmeb 缓存类
* Class SupplierCacheService
* @package crmeb\services
* @mixin \Redis
*/
class SupplierCacheService
{
//副屏相关
const CASHIER_AUX_SCREEN_TAG = 'auxScreen';
/**
* 标签名
* @var string
*/
protected static $globalCacheName = '_cached_1515146130';
/**
* 缓存队列key
* @var string[]
*/
protected static $redisQueueKey = [
0 => 'product',
1 => 'seckill',
2 => 'bargain',
3 => 'combination',
4 => 'integral',
5 => 'discounts',
6 => 'lottery'
];
/**
* 过期时间
* @var int
*/
protected static $expire;
/**
* 获取缓存过期时间
* @param int|null $expire
* @return int
*/
protected static function getExpire(int $expire = null): int
{
if (self::$expire) {
return (int)self::$expire;
}
$expire = !is_null($expire) ? $expire : SystemConfigService::get('cache_config', null, true);
if (!is_int($expire))
$expire = (int)$expire;
return self::$expire = $expire;
}
/**
* 判断缓存是否存在
* @param string $name
* @return bool
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public static function has(string $name): bool
{
try {
return CacheStatic::has($name);
} catch (\Throwable $e) {
return false;
}
}
/**
* 写入缓存
* @param string $name 缓存名称
* @param mixed $value 缓存值
* @param int $expire 缓存时间为0读取系统缓存时间
* @return bool
*/
public static function set(string $name, $value, int $expire = null): bool
{
try {
return self::handler()->set($name, $value, $expire ?? self::getExpire($expire));
} catch (\Throwable $e) {
return false;
}
}
/**
* 如果不存在则写入缓存
* @param string $name
* @param bool $default
* @return mixed
*/
public static function get(string $name, $default = false, int $expire = null)
{
try {
return self::handler()->remember($name, $default, $expire ?? self::getExpire($expire));
} catch (\Throwable $e) {
try {
if (is_callable($default)) {
return $default();
} else {
return $default;
}
} catch (\Throwable $e) {
return null;
}
}
}
/**
* 如果不存在则写入缓存
* @param string $name
* @param bool $default
* @return mixed
*/
public static function remember(string $name, $default = false, int $expire = null)
{
try {
return self::handler()->remember($name, $default, $expire ?? self::getExpire($expire));
} catch (\Throwable $e) {
try {
if (is_callable($default)) {
return $default();
} else {
return $default;
}
} catch (\Throwable $e) {
return null;
}
}
}
/**
* 删除缓存
* @param string $name
* @return bool
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public static function delete(string $name)
{
return CacheStatic::delete($name);
}
/**
* 缓存句柄
*
* @return \think\cache\TagSet|CacheStatic
*/
public static function handler(?string $cacheName = null)
{
return CacheStatic::tag($cacheName ?: self::$globalCacheName);
}
/**
* 清空缓存池
* @return bool
*/
public static function clear()
{
return self::handler()->clear();
}
/**
* Redis缓存句柄
*
* @return \think\cache\TagSet|CacheStatic
*/
public static function redisHandler(string $type = null)
{
if ($type) {
return CacheStatic::store('redis')->tag($type);
} else {
return CacheStatic::store('redis');
}
}
/**
* 放入令牌桶
* @param string $key
* @param array $value
* @param string $type
* @return bool
*/
public static function setTokenBucket(string $key, $value, $expire = null, string $type = 'admin')
{
try {
$redisCahce = self::redisHandler($type);
return $redisCahce->set($key, $value, $expire);
} catch (\Throwable $e) {
return false;
}
}
/**
* 清除所有令牌桶
* @param string $type
* @return bool
*/
public static function clearTokenAll(string $type = 'admin')
{
try {
return self::redisHandler($type)->clear();
} catch (\Throwable $e) {
return false;
}
}
/**
* 清除令牌桶
* @param string $type
* @return bool
*/
public static function clearToken(string $key)
{
try {
return self::redisHandler()->delete($key);
} catch (\Throwable $e) {
return false;
}
}
/**
* 查看令牌是否存在
* @param string $key
* @return bool
*/
public static function hasToken(string $key)
{
try {
return self::redisHandler()->has($key);
} catch (\Throwable $e) {
return false;
}
}
/**
* 获取token令牌桶
* @param string $key
* @return mixed|null
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public static function getTokenBucket(string $key)
{
try {
return self::redisHandler()->get($key, null);
} catch (\Throwable $e) {
return null;
}
}
/**
* 获取指定分数区间的成员
* @param $key
* @param int $start
* @param int $end
* @param array $options
* @return mixed
*/
public static function zRangeByScore($key, $start = '-inf', $end = '+inf', array $options = [])
{
return self::redisHandler()->zRangeByScore($key, $start, $end, $options);
}
/**
* 设置redis入库队列
* @param string $unique
* @param int $number
* @param int $type
* @param bool $isPush true :重置 false:累加
* @return bool
*/
public static function setStock(string $unique, int $number, int $type = 1, bool $isPush = true)
{
if (!$unique || !$number) return false;
$name = (self::$redisQueueKey[$type] ?? '') . '_' . $type . '_' . $unique;
/** @var self $cache */
$cache = self::redisHandler();
$res = true;
if ($isPush) {
$cache->del($name);
}
$data = [];
for ($i = 1; $i <= $number; $i++) {
$data[] = $i;
}
$res = $res && $cache->lPush($name, ...$data);
return $res;
}
/**
* 弹出redis队列中的库存条数
* @param string $unique
* @param int $number
* @param int $type
* @return bool
*/
public static function popStock(string $unique, int $number, int $type = 1)
{
if (!$unique || !$number) return false;
$name = (self::$redisQueueKey[$type] ?? '') . '_' . $type . '_' . $unique;
/** @var self $cache */
$cache = self::redisHandler();
$res = true;
if ($number > $cache->lLen($name)) {
return false;
}
for ($i = 1; $i <= $number; $i++) {
$res = $res && $cache->lPop($name);
}
return $res;
}
/**
* 是否有库存|返回库存
* @param string $unique
* @param int $number
* @param int $type
* @return bool
*/
public static function checkStock(string $unique, int $number = 0, int $type = 1)
{
$name = (self::$redisQueueKey[$type] ?? '') . '_' . $type . '_' . $unique;
if ($number) {
return self::redisHandler()->lLen($name) >= $number;
} else {
return self::redisHandler()->lLen($name);
}
}
/**
* 检查锁
* @param int $uid
* @param int $timeout
* @return bool
* @author 等风来
* @email 136327134@qq.com
* @date 2022/11/22
*/
public static function setMutex(string $key, int $timeout = 10)
{
$curTime = time();
$readMutexKey = "redis:mutex:{$key}";
$mutexRes = self::redisHandler()->handler()->setnx($readMutexKey, $curTime + $timeout);
if ($mutexRes) {
return true;
}
//就算意外退出下次进来也会检查key防止死锁
$time = self::redisHandler()->handler()->get($readMutexKey);
if ($curTime > $time) {
self::redisHandler()->handler()->del($readMutexKey);
return self::redisHandler()->handler()->setnx($readMutexKey, $curTime + $timeout);
}
return false;
}
/**
* 删除锁
* @param $uid
* @author 等风来
* @email 136327134@qq.com
* @date 2022/11/22
*/
public static function delMutex(string $key)
{
$readMutexKey = "redis:mutex:{$key}";
self::redisHandler()->handler()->del($readMutexKey);
}
/**
* 魔术方法
* @param $name
* @param $arguments
* @return mixed
*/
public static function __callStatic($name, $arguments)
{
return self::redisHandler()->{$name}(...$arguments);
}
/**
* 魔术方法
* @param $name
* @param $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
return self::redisHandler()->{$name}(...$arguments);
}
}

View File

@ -61,11 +61,11 @@ class Arr
$temp['path'] = $v['menu_path'];
$temp['title'] = $v['menu_name'];
$temp['icon'] = $v['icon'];
$temp['header'] = $v['header'];
$temp['is_header'] = $v['is_header'];
if ($v['is_show_path']) {
$temp['auth'] = ['hidden'];
}
$temp['header'] = $v['header'] ?? '';
$temp['is_header'] = $v['is_header'] ?? '';
// if ($v['is_show_path']) {
// $temp['auth'] = ['hidden'];
// }
if (!empty($v['children'])) {
$temp['children'] = self::toIviewUi($v['children']);
}
@ -87,7 +87,7 @@ class Arr
$dataSort = array_column($childs, 'sort');
array_multisort($dataSort, SORT_DESC, $childs);
foreach ($childs as $key => $navItem) {
$resChild = self::getTree($data, $navItem['id']);
$resChild = self::getTree($data, $navItem['menu_id']);
if (null != $resChild) {
$childs[$key]['children'] = $resChild;
}

130
crmeb/utils/Json.php Normal file
View File

@ -0,0 +1,130 @@
<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace crmeb\utils;
use think\facade\Config;
use think\facade\Lang;
use think\Log;
use think\Response;
/**
* Json输出类
* Class Json
* @package crmeb\utils
*/
class Json
{
private $code = 200;
public function code(int $code): self
{
$this->code = $code;
return $this;
}
/**
* 压缩数据
* @param $str
* @return string
* @author 等风来
* @email 136327134@qq.com
* @date 2022/11/10
*/
protected function compress($str)
{
return base64_encode(gzdeflate(json_encode($str, JSON_UNESCAPED_UNICODE), 9));
}
/**
* @param int $status
* @param string $msg
* @param array|null $data
* @return Response
* @author 等风来
* @email 136327134@qq.com
* @date 2022/11/10
*/
public function make(int $status, string $msg, ?array $data = null): Response
{
$request = app()->request;
$res = compact('status', 'msg');
if (!is_null($data)) {
$jsonData = json_encode($data);
//在debug关闭的时候返回压缩数据
$compressData = null;
if (strstr('/' . app()->request->rule()->getRule(), '/api/') !== false && strlen($jsonData) > 1024 && app()->config->get('cache.is_gzde', false)) {
$compressData = $this->compress($data);
$res['gzde'] = 1;
}
$res['data'] = $compressData ?: $data;
}
if ($res['msg'] && !is_numeric($res['msg'])) {
if (!$range = $request->get('lang')) {
$range = $request->cookie(Config::get('lang.cookie_var'));
}
$langData = array_values(Config::get('lang.accept_language', []));
if (!in_array($range, $langData)) {
$range = 'zh-cn';
}
$res['msg'] = Lang::get($res['msg'], [], $range);
}
//记录原始数据
$response = $res;
$response['data'] = $data;
response_log_write((array)$res, Log::INFO);
return Response::create($res, 'json', $this->code);
}
public function success($msg = 'ok', ?array $data = null): Response
{
if (is_array($msg)) {
$data = $msg;
$msg = 'ok';
}
return $this->make(200, $msg, $data);
}
public function successful(...$args): Response
{
return $this->success(...$args);
}
public function fail($msg = 'fail', ?array $data = null): Response
{
if (is_array($msg)) {
$data = $msg;
$msg = 'ok';
}
return $this->make(400, $msg, $data);
}
public function status($status, $msg = 'ok', $result = [])
{
$status = strtoupper($status);
if (is_array($msg)) {
$result = $msg;
$msg = 'ok';
}
return $this->success($msg, compact('status', 'result'));
}
}