新增解析功能

This commit is contained in:
JaguarJack 2020-04-29 17:35:29 +08:00
parent 45af3fbc5f
commit 4d444e9bbc
68 changed files with 49 additions and 4863 deletions

View File

@ -1,22 +0,0 @@
<?php
namespace catchAdmin\index\controller;
use catcher\base\CatchController;
use think\facade\Db;
class Index extends CatchController
{
/**
*
* @time 2019年12月12日
* @throws \Exception
* @return string
*/
public function dashboard(): string
{
$mysqlVersion = Db::query('select version() as version');
return $this->fetch([
'mysql_version' => $mysqlVersion['0']['version'],
]);
}
}

View File

@ -1,13 +0,0 @@
{
"name": "首页管理",
"alias": "index",
"description": "",
"keywords": [],
"order": 0,
"services": [
"catchAdmin\\index\\IndexService"
],
"aliases": {},
"files": [],
"requires": []
}

View File

@ -1,5 +0,0 @@
<?php
$router->get('/', '\catchAdmin\index\controller\Index@index');
$router->get('theme', '\catchAdmin\index\controller\Index@theme');
$router->get('dashboard', '\catchAdmin\index\controller\Index@dashboard');

View File

@ -1,82 +0,0 @@
<?php
namespace catchAdmin\login;
use catchAdmin\permissions\model\Users;
use catchAdmin\system\model\LoginLog;
use think\facade\Db;
class LoginLogEvent
{
public function handle($params)
{
$agent = request()->header('user-agent');
$username = Users::where('email', $params['email'])->value('username');
app(LoginLog::class)->storeBy([
'login_name' => $username ? : $params['email'],
'login_ip' => request()->ip(),
'browser' => $this->getBrowser($agent),
'os' => $this->getOs($agent),
'login_at' => time(),
'status' => $params['success'] ? 1 : 2,
]);
}
/**
*
* @time 2019年12月12日
* @param $agent
* @return string
*/
private function getOs($agent): string
{
if (false !== stripos($agent, 'win') && preg_match('/nt 6.1/i', $agent)) {
return 'Windows 7';
}
if (false !== stripos($agent, 'win') && preg_match('/nt 6.2/i', $agent)) {
return 'Windows 8';
}
if(false !== stripos($agent, 'win') && preg_match('/nt 10.0/i', $agent)) {
return 'Windows 10';#添加win10判断
}
if (false !== stripos($agent, 'win') && preg_match('/nt 5.1/i', $agent)) {
return 'Windows XP';
}
if (false !== stripos($agent, 'linux')) {
return 'Linux';
}
if (false !== stripos($agent, 'mac')) {
return 'mac';
}
return '未知';
}
/**
*
* @time 2019年12月12日
* @param $agent
* @return string
*/
private function getBrowser($agent): string
{
if (false !== stripos($agent, "MSIE")) {
return 'MSIE';
}
if (false !== stripos($agent, "Firefox")) {
return 'Firefox';
}
if (false !== stripos($agent, "Chrome")) {
return 'Chrome';
}
if (false !== stripos($agent, "Safari")) {
return 'Safari';
}
if (false !== stripos($agent, "Opera")) {
return 'Opera';
}
return '未知';
}
}

View File

@ -1,63 +0,0 @@
<?php
namespace catchAdmin\login\controller;
use catchAdmin\login\request\LoginRequest;
use catchAdmin\permissions\model\Users;
use catcher\base\CatchController;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\exceptions\LoginFailedException;
class Index extends CatchController
{
/**
* 登陆
*
* @time 2019年11月28日
* @param LoginRequest $request
* @param CatchAuth $auth
* @return bool|string
*/
public function login(LoginRequest $request, CatchAuth $auth)
{
$params = $request->param();
$token = $auth->attempt($params);
$user = $auth->user();
if ($user->status == Users::DISABLE) {
throw new LoginFailedException('该用户已被禁用');
}
// 记录用户登录
$user->last_login_ip = request()->ip();
$user->last_login_time = time();
$user->save();
// 登录事件
$params['success'] = $token;
event('loginLog', $params);
return $token ? CatchResponse::success([
'token' => $token,
], '登录成功') : CatchResponse::success('', '登录失败');
}
/**
* 登出
*
* @time 2019年11月28日
* @param CatchAuth $auth
* @return \think\response\Json
*/
public function logout(CatchAuth $auth): \think\response\Json
{
if ($auth->logout()) {
return CatchResponse::success();
}
return CatchResponse::fail('登出失败');
}
}

View File

@ -1,13 +0,0 @@
{
"name": "登陆",
"alias": "login",
"description": "",
"keywords": [],
"order": 1,
"services": [
"catchAdmin\\login\\LoginService"
],
"aliases": {},
"files": [],
"requires": []
}

View File

@ -1,26 +0,0 @@
<?php
namespace catchAdmin\login\request;
use catcher\base\CatchRequest;
class LoginRequest extends CatchRequest
{
protected $needCreatorId = false;
protected function rules(): array
{
// TODO: Implement rules() method.
return [
'email|用户名' => 'email',
'password|密码' => 'require',
// 'captcha|验证码' => 'require|captcha'
];
}
protected function message(): array
{
// TODO: Implement message() method.
return [];
}
}

View File

@ -1,4 +0,0 @@
<?php
# 登入
$router->post('login', '\catchAdmin\login\controller\Index@login');

View File

@ -1,110 +0,0 @@
<?php
namespace catchAdmin\Auth;
use catchAdmin\permissions\model\Permissions;
use catchAdmin\permissions\model\Users;
use catcher\exceptions\LoginFailedException;
use thans\jwt\facade\JWTAuth;
use think\facade\Session;
class Auth
{
protected const USER_ID = 'catch_uid';
/**
* 登陆
*
* @time 2019年11月28日
* @param $params
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws LoginFailedException
*/
public static function login($params)
{
$user = Users::where('email', $params['email'])->find();
if (!$user) {
throw new LoginFailedException('登陆失败, 请检查用户名和密码');
}
if (!password_verify($params['password'], $user->password)) {
throw new LoginFailedException('登陆失败, 请检查用户名和密码');
}
// Session::set(self::getLoginUserKey(), $user);
return JWTAuth::builder([self::USER_ID => $user->id]);
}
/**
* 退出登陆
*
* @time 2019年11月28日
* @return bool
*/
public static function logout(): bool
{
Session::delete(self::getLoginUserKey());
return true;
}
/**
*
* @time 2019年12月15日
* @return mixed
*/
public static function user()
{
return Users::where('id', JWTAuth::auth()[self::USER_ID])
->field(['id', 'username', 'status'])->find();
}
public static function getUserInfo()
{
$user = self::user();
$roles = $user->getRoles();
$user->permissions = Permissions::whereIn('id', $user->getPermissionsBy())
->field(['permission_name as title', 'route', 'icon'])
->select();
$user->roles = $roles;
return $user;
}
/**
*
* @time 2019年12月15日
* @return string
*/
protected static function getLoginUserKey(): string
{
// return md5(self::USER_KEY);
}
/**
*
* @time 2019年12月15日
* @param $mark
* @param $module
* @return bool
*/
public static function hasPermissions($mark, $module): bool
{
$user = self::user();
$permissionIds = $user->getPermissionsBy($user->id);
$permissionId = Permissions::where('module', $module)
->where('permission_mark', $mark)->value('id');
return in_array($permissionId, $permissionIds);
}
}

View File

@ -1,34 +0,0 @@
<?php
namespace catchAdmin\permissions;
use catcher\Code;
use catcher\exceptions\FailedException;
use thans\jwt\exception\TokenBlacklistException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;
use think\Middleware;
class AuthTokenMiddleware extends Middleware
{
public function handle($request, \Closure $next)
{
try {
JWTAuth::auth();
} catch (\Exception $e) {
if ($e instanceof TokenExpiredException) {
throw new FailedException('token 过期', Code::LOST_LOGIN);
}
if ($e instanceof TokenBlacklistException) {
throw new FailedException('token 被加入黑名单', Code::LOST_LOGIN);
}
if ($e instanceof TokenInvalidException) {
throw new FailedException('token 不合法', Code::LOST_LOGIN);
}
throw new FailedException('登录用户不合法', Code::LOST_LOGIN);
}
return $next($request);
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace catchAdmin\permissions;
use catchAdmin\permissions\model\Permissions;
use catchAdmin\system\model\OperateLog;
use catcher\CatchAdmin;
use think\facade\Db;
class OperateLogEvent
{
public function handle($params)
{
$permission = $params['permission'];
$parentPermission = Permissions::where('id', $permission->parent_id)->value('permission_name');
$requestParams = request()->param();
app(OperateLog::class)->storeBy([
'creator_id' => $params['creator_id'],
'module' => $parentPermission ? : '',
'method' => request()->method(),
'operate' => $permission->permission_name,
'route' => $permission->permission_mark,
'params' => !empty($requestParams) ? json_encode($requestParams, JSON_UNESCAPED_UNICODE) : '',
'created_at' => time(),
'ip' => request()->ip(),
]);
}
}

View File

@ -1,132 +0,0 @@
<?php
namespace catchAdmin\permissions;
use app\Request;
use catchAdmin\permissions\model\Permissions;
use catcher\CatchCacheKeys;
use catcher\Code;
use catcher\exceptions\PermissionForbiddenException;
use think\facade\Cache;
use think\helper\Str;
class PermissionsMiddleware
{
/**
*
* @time 2019年12月12日
* @param Request $request
* @param \Closure $next
* @return mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws PermissionForbiddenException
*/
public function handle(Request $request, \Closure $next)
{
$rule = $request->rule()->getName();
if (!$rule) {
return $next($request);
}
// 模块忽略
[$module, $controller, $action] = $this->parseRule($rule);
// toad
if (in_array($module, $this->ignoreModule())) {
return $next($request);
}
// 用户未登录
$user = $request->user();
if (!$user) {
throw new PermissionForbiddenException('Login is invalid', Code::LOST_LOGIN);
}
//dd($this->parseRule($rule));
$permission = $this->getPermission($module, $controller, $action);
// 记录操作
$this->operateEvent($request->user()->id, $permission);
// 超级管理员
if ($request->user()->id === config('catch.permissions.super_admin_id')) {
return $next($request);
}
// Get 请求
if ($request->isGet() && config('catch.permissions.is_allow_get')) {
return $next($request);
}
if (!$permission || !in_array($permission->id, Cache::get(CatchCacheKeys::USER_PERMISSIONS . $user->id))) {
throw new PermissionForbiddenException();
}
return $next($request);
}
/**
* 解析规则
*
* @time 2020年04月16日
* @param $rule
* @return array
*/
protected function parseRule($rule)
{
[$controller, $action] = explode(Str::contains($rule, '@') ? '@' : '/', $rule);
$controller = explode('\\', $controller);
$controllerName = strtolower(array_pop($controller));
array_pop($controller);
$module = array_pop($controller);
return [$module, $controllerName, $action];
}
/**
*
* @time 2019年12月14日
* @param $module
* @param $controllerName
* @param $action
* @param $request
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return array|bool|\think\Model|null
*/
protected function getPermission($module, $controllerName, $action)
{
$permissionMark = sprintf('%s@%s', $controllerName, $action);
return Permissions::where('module', $module)->where('permission_mark', $permissionMark)->find();
}
/**
* 忽略模块
*
* @time 2020年04月16日
* @return array
*/
protected function ignoreModule()
{
return ['login'];
}
/**
* 操作日志
*
* @time 2020年04月16日
* @param $creatorId
* @param $permission
* @return void
*/
protected function operateEvent($creatorId, $permission)
{
// 操作日志
$permission && event('operateLog', [
'creator_id' => $creatorId,
'permission' => $permission,
]);
}
}

View File

@ -1,68 +0,0 @@
<?php
namespace catchAdmin\permissions\controller;
use catcher\base\CatchController;
use catchAdmin\permissions\model\Department as DepartmentModel;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\Tree;
class Department extends CatchController
{
protected $department;
public function __construct(DepartmentModel $department)
{
$this->department = $department;
}
/**
* 列表
*
* @time 2020年01月09日
* @param CatchRequest $request
* @return \think\response\Json
* @throws \think\db\exception\DbException
*/
public function index(): \think\response\Json
{
return CatchResponse::success(Tree::done($this->department->getList()));
}
/**
* 保存
*
* @time 2020年01月09日
* @param CatchRequest $request
* @return \think\response\Json
*/
public function save(CatchRequest $request): \think\response\Json
{
return CatchResponse::success($this->department->storeBy($request->post()));
}
/**
* 更新
*
* @time 2020年01月09日
* @param $id
* @param CatchRequest $request
* @return \think\response\Json
*/
public function update($id, CatchRequest $request): \think\response\Json
{
return CatchResponse::success($this->department->updateBy($id, $request->post()));
}
/**
* 删除
*
* @time 2020年01月09日
* @param $id
* @return \think\response\Json
*/
public function delete($id): \think\response\Json
{
return CatchResponse::success($this->department->deleteBy($id));
}
}

View File

@ -1,80 +0,0 @@
<?php
namespace catchAdmin\permissions\controller;
use catchAdmin\permissions\model\Job as JobModel;
use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
class Job extends CatchController
{
protected $job;
public function __construct(JobModel $job)
{
$this->job = $job;
}
/**
* 列表
*
* @time 2020年01月09日
* @param CatchRequest $request
* @return \think\response\Json
* @throws \think\db\exception\DbException
*/
public function index(): \think\response\Json
{
return CatchResponse::paginate($this->job->getList());
}
/**
* 保存
*
* @time 2020年01月09日
* @param CatchRequest $request
* @return \think\response\Json
*/
public function save(CatchRequest $request): \think\response\Json
{
return CatchResponse::success($this->job->storeBy($request->post()));
}
/**
* 更新
*
* @time 2020年01月09日
* @param $id
* @param CatchRequest $request
* @return \think\response\Json
*/
public function update($id, CatchRequest $request): \think\response\Json
{
return CatchResponse::success($this->job->updateBy($id, $request->post()));
}
/**
* 删除
*
* @time 2020年01月09日
* @param $id
* @return \think\response\Json
*/
public function delete($id): \think\response\Json
{
return CatchResponse::success($this->job->deleteBy($id));
}
/**
* 获取所有
*
* @return \think\response\Json
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getAll()
{
return CatchResponse::success($this->job->field(['id', 'job_name'])->select());
}
}

View File

@ -1,124 +0,0 @@
<?php
namespace catchAdmin\permissions\controller;
use catcher\base\CatchRequest as Request;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use catcher\Tree;
use catchAdmin\permissions\model\Permissions;
use think\response\Json;
class Permission extends CatchController
{
protected $permissions;
public function __construct(Permissions $permissions)
{
$this->permissions = $permissions;
}
/**
*
* @time 2019年12月11日
* @param Request $request
* @return Json
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\db\exception\DataNotFoundException
*/
public function index(Request $request): Json
{
// 获取菜单类型
$menuList = $this->permissions->getList(true);
// 获取按钮类型并且重新排列
$buttonList = [];
$this->permissions
->whereIn('parent_id', array_unique($menuList->column('id')))
->where('type', Permissions::BTN_TYPE)
->select()->each(function ($item) use (&$buttonList){
$buttonList[$item['parent_id']][] = $item->toArray();
});
// 子节点的 key
$children = $request->param('actionList') ?? 'children';
// 返回树结构
return CatchResponse::success(Tree::done($menuList->each(function (&$item) use ($buttonList, $children){
$item[$children] = $buttonList[$item['id']] ?? [];
})->toArray()));
}
/**
*
* @time 2019年12月11日
* @param Request $request
* @return Json
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\db\exception\DataNotFoundException
*/
public function save(Request $request): Json
{
$params = $request->param();
// 如果是子分类 自动写入父类模块
$parentId = $params['parent_id'] ?? 0;
if ($parentId) {
$parent = $this->permissions->findBy($parentId);
$params['module'] = $parent->module;
}
return CatchResponse::success($this->permissions->storeBy($params));
}
/**
*
* @time 2019年12月11日
* @param $id
* @param Request $request
* @return Json
*/
public function update($id, Request $request): Json
{
$permission = $this->permissions->findBy($id);
$params = array_merge($request->param(), [
'parent_id' => $permission->parent_id,
'level' => $permission->level
]);
// 如果是父分类需要更新所有子分类的模块
if (!$permission->parent_id) {
$this->permissions->updateBy($permission->parent_id, [
'module' => $permission->module,
], 'parent_id');
}
return CatchResponse::success($this->permissions->updateBy($id, $params));
}
/**
*
* @time 2019年12月11日
* @param $id
* @throws FailedException
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return Json
*/
public function delete($id): Json
{
if ($this->permissions->where('parent_id', $id)->find()) {
throw new FailedException('存在子菜单,无法删除');
}
$this->permissions->findBy($id)->roles()->detach();
return CatchResponse::success($this->permissions->deleteBy($id));
}
}

View File

@ -1,148 +0,0 @@
<?php
namespace catchAdmin\permissions\controller;
use catchAdmin\permissions\model\Permissions;
use catcher\base\CatchRequest as Request;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use catcher\Tree;
use think\response\Json;
class Role extends CatchController
{
protected $role;
public function __construct(\catchAdmin\permissions\model\Roles $role)
{
$this->role = $role;
}
/**
*
* @time 2019年12月09日
* @param Request $request
* @return string
*/
public function index()
{
return CatchResponse::success(Tree::done($this->role->getList()));
}
/**
*
* @time 2019年12月11日
* @param Request $request
* @return Json
* @throws \think\db\exception\DbException
*/
public function save(Request $request)
{
$this->role->storeBy($request->param());
$permissions = $request->param('permissions');
if (!empty($permissions)) {
$this->role->attach(array_unique($permissions));
}
if (!empty($request->param('departments'))) {
$this->role->attachDepartments($request->param('departments'));
}
// 添加角色
return CatchResponse::success();
}
public function read($id)
{
$role = $this->role->findBy($id);
$role->permissions = $role->getPermissions();
$role->departments = $role->getDepartments();
return CatchResponse::success($role);
}
/**
*
* @time 2019年12月11日
* @param $id
* @param Request $request
* @return Json
* @throws \think\db\exception\DbException
*/
public function update($id, Request $request): Json
{
$this->role->updateBy($id, $request->param());
$role = $this->role->findBy($id);
$role->detach();
$permissions = $request->param('permissions');
if (!empty($permissions)) {
$this->role->attach(array_unique($permissions));
}
if (!empty($request->param('departments'))) {
$role->detachDepartments();
$role->attachDepartments($request->param('departments'));
}
return CatchResponse::success();
}
/**
*
* @time 2019年12月11日
* @param $id
* @throws FailedException
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return Json
*/
public function delete($id): Json
{
if ($this->role->where('parent_id', $id)->find()) {
throw new FailedException('存在子角色,无法删除');
}
$role = $this->role->findBy($id);
// 删除权限
$role->detach();
// 删除部门关联
$role->detachDepartments();
// 删除用户关联
$role->users()->detach();
// 删除
$this->role->deleteBy($id);
return CatchResponse::success();
}
/**
*
* @time 2019年12月11日
* @param Request $request
* @param \catchAdmin\permissions\model\Permissions $permission
* @return Json
*/
public function getPermissions(Request $request, \catchAdmin\permissions\model\Permissions $permission): Json
{
$parentRoleHasPermissionIds = [];
if ($request->param('parent_id')) {
$permissions = $this->role->findBy($request->param('parent_id'))->getPermissions();
foreach ($permissions as $_permission) {
$parentRoleHasPermissionIds[] = $_permission->pivot->permission_id;
}
}
$permissions = Tree::done(Permissions::whereIn('id', $parentRoleHasPermissionIds)->select()->toArray());
$permissionIds = [];
if ($request->param('role_id')) {
$roleHasPermissions = $this->role->findBy($request->param('role_id'))->getPermissions();
foreach ($roleHasPermissions as $_permission) {
$permissionIds[] = $_permission->pivot->permission_id;
}
}
return CatchResponse::success([
'permissions' => $permissions,
'hasPermissions' => $permissionIds,
]);
}
}

View File

@ -1,229 +0,0 @@
<?php
namespace catchAdmin\permissions\controller;
use catcher\base\CatchRequest as Request;
use catchAdmin\permissions\model\Permissions;
use catchAdmin\permissions\model\Roles;
use catchAdmin\permissions\model\Users;
use catchAdmin\permissions\request\CreateRequest;
use catchAdmin\permissions\request\UpdateRequest;
use catcher\base\CatchController;
use catcher\CatchAuth;
use catcher\CatchCacheKeys;
use catcher\CatchResponse;
use catcher\Tree;
use catcher\Utils;
use think\facade\Cache;
class User extends CatchController
{
protected $user;
public function __construct(Users $user)
{
$this->user = $user;
}
/**
*
* @time 2020年04月24日
* @param Request $request
* @throws \think\db\exception\DbException
* @return \think\response\Json
*/
public function index(Request $request)
{
return CatchResponse::paginate($this->user->getList($request->param()));
}
/**
* 获取用户信息
*
* @time 2020年01月07日
* @param CatchAuth $auth
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return \think\response\Json
*/
public function info(CatchAuth $auth)
{
$user = $auth->user();
$roles = $user->getRoles();
$permissionIds = $user->getPermissionsBy($user->id);
// 缓存用户权限
Cache::set(CatchCacheKeys::USER_PERMISSIONS . $user->id, $permissionIds);
$user->permissions = Permissions::getCurrentUserPermissions($permissionIds);
$user->roles = $roles;
// 用户数据权限
// $user->data_range = Roles::getDepartmentUserIdsBy($roles);
return CatchResponse::success($user);
}
/**
*
* @time 2019年12月06日
* @throws \Exception
* @return string
*/
public function create()
{}
/**
*
* @param CreateRequest $request
* @time 2019年12月06日
* @return \think\response\Json
*/
public function save(CreateRequest $request)
{
$this->user->storeBy($request->post());
$this->user->attach($request->param('roles'));
$this->user->attachJobs($request->param('jobs'));
return CatchResponse::success('', '添加成功');
}
/**
*
* @time 2019年12月04日
* @param $id
* @return \think\response\Json
*/
public function read($id)
{
$user = $this->user->findBy($id);
$user->roles = $user->getRoles();
$user->jobs = $user->getJobs();
return CatchResponse::success($user);
}
/**
* @param $id
* @return string
* @throws \Exception
*/
public function edit($id){}
/**
*
* @time 2019年12月04日
* @param $id
* @param UpdateRequest $request
* @return \think\response\Json
*/
public function update($id, UpdateRequest $request)
{
$this->user->updateBy($id, $request->post());
$user = $this->user->findBy($id);
$user->detach();
$user->detachJobs();
if (!empty($request->param('roles'))) {
$user->attach($request->param('roles'));
}
if (!empty($request->param('jobs'))) {
$user->attachJobs($request->param('jobs'));
}
return CatchResponse::success();
}
/**
*
* @time 2019年12月04日
* @param $id
* @return \think\response\Json
*/
public function delete($id)
{
$ids = Utils::stringToArrayBy($id);
foreach ($ids as $_id) {
$user = $this->user->findBy($_id);
// 删除角色
$user->detach();
// 删除岗位
$user->detachJobs();
$this->user->deleteBy($_id);
}
return CatchResponse::success();
}
/**
*
* @time 2019年12月07日
* @param $id
* @return \think\response\Json
*/
public function switchStatus($id): \think\response\Json
{
$ids = Utils::stringToArrayBy($id);
foreach ($ids as $_id) {
$user = $this->user->findBy($_id);
$this->user->updateBy($_id, [
'status' => $user->status == Users::ENABLE ? Users::DISABLE : Users::ENABLE,
]);
}
return CatchResponse::success([], '操作成功');
}
/**
*
* @time 2019年12月07日
* @param $id
* @return \think\response\Json
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\db\exception\DataNotFoundException
*/
public function recover($id): \think\response\Json
{
$trashedUser = $this->user->findBy($id, ['*'], true);
if ($this->user->where('email', $trashedUser->email)->find()) {
return CatchResponse::fail(sprintf('该恢复用户的邮箱 [%s] 已被占用', $trashedUser->email));
}
return CatchResponse::success($this->user->recover($id));
}
/**
*
* @time 2019年12月11日
* @param Request $request
* @param Roles $roles
* @return \think\response\Json
*/
public function getRoles(Request $request, Roles $roles): \think\response\Json
{
$roles = Tree::done($roles->getList());
$roleIds = [];
if ($request->param('uid')) {
$userHasRoles = $this->user->findBy($request->param('uid'))->getRoles();
foreach ($userHasRoles as $role) {
$roleIds[] = $role->pivot->role_id;
}
}
return CatchResponse::success([
'roles' => $roles,
'hasRoles' => $roleIds,
]);
}
}

View File

@ -1,45 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Users extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('users',array('engine'=>'Innodb', 'comment' => '用户表', 'signed' => false));
$table->addColumn('username', 'string',array('limit' => 15,'default'=>'','comment'=>'用户名'))
->addColumn('password', 'string',array('limit' => 255,'comment'=>'用户密码'))
->addColumn('email', 'string',array('limit' => 100, 'comment'=>'邮箱 登录'))
->addColumn('creator_id', 'integer',['default' => 0, 'comment'=>'创建人ID'])
->addColumn('department_id', 'integer',['default' => 0, 'comment'=>'部门ID'])
->addColumn('status', 'boolean',array('limit' => 1,'default'=> 1,'comment'=>'用户状态 1 正常 2 禁用'))
->addColumn('last_login_ip', 'string',array('limit' => 50,'default'=>0,'comment'=>'最后登录IP'))
->addColumn('last_login_time', 'integer',array('default'=>0,'comment'=>'最后登录时间', 'signed' => false))
->addColumn('created_at', 'integer', array('default'=>0,'comment'=>'创建时间', 'signed' => false ))
->addColumn('updated_at', 'integer', array('default'=>0,'comment'=>'更新时间', 'signed' => false))
->addColumn('deleted_at', 'integer', array('default'=>0,'comment'=>'删除状态0未删除 >0 已删除', 'signed' => false))
->create();
}
}

View File

@ -1,42 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Roles extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('roles',['engine'=>'Innodb', 'comment' => '角色表', 'signed' => false]);
$table->addColumn('role_name', 'string',['limit' => 15,'default'=>'','comment'=>'角色名'])
->addColumn('parent_id', 'integer',['default'=>0,'comment'=>'父级ID', 'signed' => false])
->addColumn('description', 'string',['default'=> '','comment'=>'角色备注'])
->addColumn('data_range', 'integer',['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY,'default'=> 0,'comment'=>'1 全部数据 2 自定义数据 3 仅本人数据 4 部门数据 5 部门及以下数据'])
->addColumn('creator_id', 'integer',['default' => 0, 'comment'=>'创建人ID'])
->addColumn('created_at', 'integer', array('default'=>0,'comment'=>'创建时间', 'signed' => false ))
->addColumn('updated_at', 'integer', array('default'=>0,'comment'=>'更新时间', 'signed' => false))
->addColumn('deleted_at', 'integer', array('default'=>0,'comment'=>'删除状态0未删除 >0 已删除', 'signed' => false))
->create();
}
}

View File

@ -1,48 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Permissions extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('permissions',['engine'=>'Innodb', 'comment' => '菜单表', 'signed' => false]);
$table->addColumn('permission_name', 'string',['limit' => 15,'default'=>'','comment'=>'菜单名称'])
->addColumn('parent_id', 'integer',['default'=>0,'comment'=>'父级ID', 'signed' => false])
->addColumn('route', 'string', ['default' => '', 'comment' => '路由', 'limit' => 50])
->addColumn('icon', 'string', ['default' => '', 'comment' => '菜单图标', 'limit' => 50])
->addColumn('module', 'string', ['default' => '', 'comment' => '模块', 'limit' => 20])
->addColumn('creator_id', 'integer',['default' => 0, 'comment'=>'创建人ID'])
->addColumn('method', 'string', ['default' => 'get', 'comment' => '路由请求方法', 'limit' => 15])
->addColumn('permission_mark', 'string', ['null' => false, 'comment' => '权限标识', 'limit' => 50])
->addColumn('type', 'integer',['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY,'default'=> 1,'comment'=>'1 菜单 2 按钮'])
->addColumn('sort', 'integer',['default'=> 0,'comment'=>'排序字段'])
->addColumn('created_at', 'integer', array('default'=>0,'comment'=>'创建时间', 'signed' => false ))
->addColumn('updated_at', 'integer', array('default'=>0,'comment'=>'更新时间', 'signed' => false))
->addColumn('deleted_at', 'integer', array('default'=>0,'comment'=>'删除状态null 未删除 timestamp 已删除', 'signed' => false))
->create();
}
}

View File

@ -1,36 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class UserHasRoles extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('user_has_roles',['engine'=>'Innodb', 'comment' => '用户角色表', 'signed' => false]);
$table->addColumn('uid', 'integer',['comment'=>'用户ID', 'signed' => false])
->addColumn('role_id', 'integer', ['comment'=>'角色ID', 'signed' => false])
->create();
}
}

View File

@ -1,36 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class RoleHasPermissions extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('role_has_permissions',['engine'=>'Innodb', 'comment' => '角色权限表', 'signed' => false]);
$table->addColumn('role_id', 'integer',['comment'=>'角色ID', 'signed' => false])
->addColumn('permission_id', 'integer', ['comment'=>'权限ID', 'signed' => false])
->create();
}
}

View File

@ -1,45 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Department extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('departments',['engine'=>'Innodb', 'comment' => '部门表', 'signed' => false]);
$table->addColumn('department_name', 'string',['limit' => 15,'default'=>'','comment'=>'部门名称'])
->addColumn('parent_id', 'integer',['default'=>0,'comment'=>'父级ID', 'signed' => false])
->addColumn('principal', 'string', ['default' => '', 'comment' => '负责人', 'limit' => 20])
->addColumn('mobile', 'string', ['default' => '', 'comment' => '联系电话', 'limit' => 20])
->addColumn('email', 'string', ['default' => '', 'comment' => '联系又想', 'limit' => 100])
->addColumn('creator_id', 'integer',['default' => 0, 'comment'=>'创建人ID'])
->addColumn('status', 'integer',['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY,'default'=> 1,'comment'=>'1 正常 2 停用'])
->addColumn('sort', 'integer',['default'=> 0,'comment'=>'排序字段'])
->addColumn('created_at', 'integer', array('default'=>0,'comment'=>'创建时间', 'signed' => false ))
->addColumn('updated_at', 'integer', array('default'=>0,'comment'=>'更新时间', 'signed' => false))
->addColumn('deleted_at', 'integer', array('default'=>0,'comment'=>'删除状态null 未删除 timestamp 已删除', 'signed' => false))
->create();
}
}

View File

@ -1,43 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Job extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('jobs',['engine'=>'Innodb', 'comment' => '岗位表', 'signed' => false]);
$table->addColumn('job_name', 'string',['limit' => 15,'default'=>'','comment'=>'岗位名称'])
->addColumn('coding', 'string', ['default' => '', 'comment' => '编码', 'limit' => 50])
->addColumn('creator_id', 'integer',['default' => 0, 'comment'=>'创建人ID'])
->addColumn('status', 'integer',['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY,'default'=> 1,'comment'=>'1 正常 2 停用'])
->addColumn('sort', 'integer',['default'=> 0,'comment'=>'排序字段'])
->addColumn('description', 'string', ['default' => '', 'comment' => '描述', 'limit' => 255])
->addColumn('created_at', 'integer', array('default'=>0,'comment'=>'创建时间', 'signed' => false ))
->addColumn('updated_at', 'integer', array('default'=>0,'comment'=>'更新时间', 'signed' => false))
->addColumn('deleted_at', 'integer', array('default'=>0,'comment'=>'删除状态null 未删除 timestamp 已删除', 'signed' => false))
->create();
}
}

View File

@ -1,36 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class UserRelateJob extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('user_has_jobs',['engine'=>'Innodb', 'comment' => '用户角色表', 'signed' => false]);
$table->addColumn('uid', 'integer',['comment'=>'用户ID', 'signed' => false])
->addColumn('job_id', 'integer', ['comment'=>'岗位ID', 'signed' => false])
->create();
}
}

View File

@ -1,36 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class RoleHasDepartments extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('role_has_departments',['engine'=>'Innodb', 'comment' => '角色部门表', 'signed' => false]);
$table->addColumn('role_id', 'integer',['comment'=>'角色ID', 'signed' => false])
->addColumn('department_id', 'integer', ['comment'=>'部门ID', 'signed' => false])
->create();
}
}

View File

@ -1,41 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class ChangePermissions extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
if ($this->hasTable('permissions')) {
$table = $this->table('permissions');
$table->addColumn('component', 'string', ['default' => '', 'comment' => '组件名称', 'limit' => '255', 'after' => 'permission_mark'])
->addColumn('redirect', 'string', ['default' => '', 'comment' => '跳转地址', 'limit' => '255', 'after' => 'component'])
->addColumn('hide_children_in_menu', 'integer', ['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY, 'default' => 1, 'comment' => '1 显示 2隐藏', 'after' => 'redirect'])
->addColumn('keepalive', 'integer', ['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY, 'default' => 1, 'comment' => '1 缓存 2 不存在 ', 'after' => 'hide_children_in_menu'])
->update();
}
}
}

View File

@ -1,38 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class PermissionsAddColumn extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
if ($this->hasTable('permissions')) {
$table = $this->table('permissions');
$table->addColumn('level', 'string', ['default' => '', 'comment' => '层级', 'limit' => '50', 'after' => 'parent_id'])
->update();
}
}
}

View File

@ -1,39 +0,0 @@
<?php
use think\migration\Seeder;
class DepartmentsSeed extends Seeder
{
/**
* Run Method.
*
* Write your database seeder using this method.
*
* More information on writing seeders is available here:
* http://docs.phinx.org/en/latest/seeding.html
*/
public function run()
{
$data = [
[
'id' => 1,
'department_name' => '总部',
'parent_id' => 0,
],
[
'id' => 2,
'department_name' => '北京总部',
'parent_id' => 1,
],
[
'id' => 3,
'department_name' => '南京总部',
'parent_id' => 1,
],
];
foreach ($data as $item) {
\catchAdmin\permissions\model\Department::create($item);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +0,0 @@
<?php
use think\migration\Seeder;
class UsersSeed extends Seeder
{
/**
* Run Method.
*
* Write your database seeder using this method.
*
* More information on writing seeders is available here:
* http://docs.phinx.org/en/latest/seeding.html
*/
public function run()
{
return \catchAdmin\permissions\model\Users::create([
'username' => 'admin',
'password' => 'admin',
'email' => 'admin@gmail.com',
'creator_id' => 1,
]);
}
}

View File

@ -1,43 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
use catchAdmin\permissions\model\search\DepartmentSearch;
use catcher\base\CatchModel;
class Department extends CatchModel
{
use DepartmentSearch;
protected $name = 'departments';
protected $field = [
'id', //
'department_name', // 部门名称
'parent_id', // 父级ID
'principal', // 负责人
'mobile', // 联系电话
'email', // 联系又想
'creator_id', // 创建人ID
'status', // 1 正常 2 停用
'sort', // 排序字段
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除状态null 未删除 timestamp 已删除
];
/**
* 列表数据
*
* @time 2020年01月09日
* @param $params
* @return array
* @throws \think\db\exception\DbException
*/
public function getList(): array
{
return $this->withoutField(['department_name'])
->addFields(['department_name as title'])
->catchSearch()
->select()->toArray();
}
}

View File

@ -1,57 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
trait HasDepartmentsTrait
{
/**
*
* @time 2019年12月08日
* @return mixed
*/
public function departments()
{
return $this->belongsToMany(Department::class, 'role_has_departments', 'department_id', 'role_id');
}
/**
*
* @time 2019年12月08日
* @return mixed
*/
public function getDepartments()
{
return $this->departments()->select();
}
/**
*
* @time 2019年12月08日
* @param array $departments
* @return mixed
*/
public function attachDepartments(array $departments)
{
if (empty($departments)) {
return true;
}
sort($departments);
return $this->departments()->attach($departments);
}
/**
*
* @time 2019年12月08日
* @param array $departments
* @return mixed
*/
public function detachDepartments(array $departments = [])
{
if (empty($departments)) {
return $this->departments()->detach();
}
return $this->departments()->detach($departments);
}
}

View File

@ -1,58 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
trait HasJobsTrait
{
/**
*
* @time 2019年12月08日
* @return mixed
*/
public function jobs()
{
return $this->belongsToMany(Job::class, 'user_has_jobs', 'job_id', 'uid');
}
/**
*
* @time 2019年12月08日
* @param array $fields
* @return mixed
*/
public function getJobs()
{
return $this->jobs()->select();
}
/**
*
* @time 2019年12月08日
* @param array $jobs
* @return mixed
*/
public function attachJobs(array $jobs)
{
if (empty($jobs)) {
return true;
}
sort($jobs);
return $this->jobs()->attach($jobs);
}
/**
*
* @time 2019年12月08日
* @param array $jobs
* @return mixed
*/
public function detachJobs(array $jobs = [])
{
if (empty($jobs)) {
return $this->jobs()->detach();
}
return $this->jobs()->detach($jobs);
}
}

View File

@ -1,76 +0,0 @@
<?php
/**
* @filename HasPermissionsTrait.php
* @createdAt 2020/1/14
* @project https://github.com/yanwenwu/catch-admin
* @document http://doc.catchadmin.com
* @author JaguarJack <njphper@gmail.com>
* @copyright By CatchAdmin
* @license https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt
*/
namespace catchAdmin\permissions\model;
trait HasPermissionsTrait
{
/**
*
* @time 2019年12月09日
* @return \think\model\relation\BelongsToMany
*/
public function permissions(): \think\model\relation\BelongsToMany
{
return $this->belongsToMany(Permissions::class, 'role_has_permissions', 'permission_id', 'role_id');
}
/**
*
* @time 2019年12月08日
* @param array $condition
* @param array $field
* @return mixed
*/
public function getPermissions($condition = [], $field = [])
{
return $this->permissions()
->when(!empty($field), function ($query) use ($field){
$query->field($field);
})
->when(!empty($condition), function ($query) use ($condition){
$query->where($condition);
})
->select();
}
/**
*
* @time 2019年12月08日
* @param array $permissions
* @return mixed
* @throws \think\db\exception\DbException
*/
public function attach(array $permissions)
{
if (empty($permissions)) {
return true;
}
sort($permissions);
return $this->permissions()->attach($permissions);
}
/**
*
* @time 2019年12月08日
* @param array $roles
* @return mixed
*/
public function detach(array $roles = [])
{
if (empty($roles)) {
return $this->permissions()->detach();
}
return $this->permissions()->detach($roles);
}
}

View File

@ -1,58 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
trait HasRolesTrait
{
/**
*
* @time 2019年12月08日
* @return mixed
*/
public function roles()
{
return $this->belongsToMany(Roles::class, 'user_has_roles', 'role_id', 'uid');
}
/**
*
* @time 2019年12月08日
* @param array $fields
* @return mixed
*/
public function getRoles()
{
return $this->roles()->select();
}
/**
*
* @time 2019年12月08日
* @param array $roles
* @return mixed
*/
public function attach(array $roles)
{
if (empty($roles)) {
return true;
}
sort($roles);
return $this->roles()->attach($roles);
}
/**
*
* @time 2019年12月08日
* @param array $roles
* @return mixed
*/
public function detach(array $roles = [])
{
if (empty($roles)) {
return $this->roles()->detach();
}
return $this->roles()->detach($roles);
}
}

View File

@ -1,36 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
use catcher\base\CatchModel;
class Job extends CatchModel
{
protected $name = 'jobs';
protected $field = [
'id', //
'job_name', // 岗位名称
'coding', // 编码
'creator_id', // 创建人ID
'status', // 1 正常 2 停用
'sort', // 排序字段
'description', // 描述
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除状态null 未删除 timestamp 已删除
];
/**
* 列表
*
* @time 2020年01月09日
* @param $params
* @throws \think\db\exception\DbException
* @return \think\Paginator
*/
public function getList()
{
return $this->catchSearch()
->paginate();
}
}

View File

@ -1,103 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
use catchAdmin\permissions\model\search\PermissionsSearch;
use catcher\base\CatchModel;
use think\Model;
class Permissions extends CatchModel
{
use PermissionsSearch;
protected $name = 'permissions';
protected $field = [
'id', //
'permission_name', // 菜单名称
'parent_id', // 父级ID
'icon',
'component', // 组件
'redirect',
'keepalive',
'hide_children_in_menu',
'creator_id',
'module', // 模块
'route', // 路由
'method', // 请求方法
'permission_mark', // 权限标识
'type', // 1 菜单 2 按钮
'sort', // 排序字段
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除状态null 未删除 timestamp 已删除
];
public const MENU_TYPE = 1;
public const BTN_TYPE = 2;
public const GET = 'get';
public const POST = 'post';
public const PUT = 'put';
public const DELETE = 'delete';
public function getList($isMenu = false)
{
return $this->catchSearch()
->order('sort', 'desc')
->order('id', 'desc')
->when($isMenu, function ($query){
$query->where('type', self::MENU_TYPE);
})
->select();
}
public function roles(): \think\model\relation\BelongsToMany
{
return $this->belongsToMany(Roles::class, 'role_has_permissions', 'role_id', 'permission_id');
}
/**
* 获取当前用户权限
*
* @time 2020年01月14日
* @param array $permissionIds
* @return \think\Collection
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\db\exception\DataNotFoundException
*/
public static function getCurrentUserPermissions(array $permissionIds): \think\Collection
{
return parent::whereIn('id', $permissionIds)
->field(['permission_name as title', 'id', 'parent_id',
'route', 'icon', 'component', 'redirect',
'keepalive as keepAlive', 'hide_children_in_menu', 'type'
])
->select();
}
/**
* 插入后回调 更新 level
*
* @time 2020年04月22日
* @param Model $model
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return array|bool|Model|void|null
*/
public static function onAfterInsert(Model $model)
{
$model = self::where('id', $model->id)->find();
if ($model && $model->parent_id) {
$parent = self::where('id', $model->parent_id)->find();
$level = $parent->level ? $parent->level . '-' . $parent->id : $parent->id;
return $model->where('id', $model->id)->update([
'level' => $level
]);
}
return true;
}
}

View File

@ -1,90 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
use catchAdmin\permissions\model\search\RolesSearch;
use catcher\base\CatchModel;
class Roles extends CatchModel
{
use HasDepartmentsTrait;
use HasPermissionsTrait;
use RolesSearch;
protected $name = 'roles';
public const ALL_DATA = 1; // 全部数据
public const SELF_CHOOSE = 2; // 自定义数据
public const SELF_DATA = 3; // 本人数据
public const DEPARTMENT_DATA = 4; // 部门数据
public const DEPARTMENT_DOWN_DATA = 5; // 部门及以下数据
protected $field = [
'id', //
'role_name', // 角色名
'parent_id', // 父级ID
'creator_id', // 创建者
'data_range', // 数据范围
'description', // 角色备注
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除状态0未删除 >0 已删除
];
public function getList()
{
return $this->catchSearch()
->order('id', 'desc')
->select()
->toArray();
}
/**
*
* @time 2019年12月08日
* @return \think\model\relation\BelongsToMany
*/
public function users(): \think\model\relation\BelongsToMany
{
return $this->belongsToMany(Users::class, 'user_has_roles', 'uid', 'role_id');
}
public static function getDepartmentUserIdsBy($roles)
{
$uids = [];
$isAll = false;
$user = request()->user();
foreach ($roles as $role) {
switch ($role->data_range) {
case self::ALL_DATA:
$isAll = true;
break;
case self::SELF_CHOOSE:
$departmentIds = array_merge(array_column($role->getDepartments()->toArray(), 'id'));
$uids = array_merge($uids, Users::getUserIdsByDepartmentIds($departmentIds));
break;
case self::SELF_DATA:
$uids[] = $user->id;
break;
case self::DEPARTMENT_DOWN_DATA:
case self::DEPARTMENT_DATA:
$uids = array_merge($uids, Users::getUserIdsByDepartmentIds([$user->department_id]));
break;
default:
break;
}
// 如果有全部数据 直接跳出
if ($isAll) {
break;
}
}
return $uids;
}
}

View File

@ -1,85 +0,0 @@
<?php
namespace catchAdmin\permissions\model;
use catchAdmin\permissions\model\search\UserSearch;
use catcher\base\CatchModel;
class Users extends CatchModel
{
use HasRolesTrait;
use HasJobsTrait;
use UserSearch;
protected $name = 'users';
protected $field = [
'id', //
'username', // 用户名
'password', // 用户密码
'email', // 邮箱 登录
'creator_id', // 创建者ID
'department_id', // 部门ID
'status', // 用户状态 1 正常 2 禁用
'last_login_ip', // 最后登录IP
'last_login_time', // 最后登录时间
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除状态0未删除 >0 已删除
];
/**
* set password
*
* @time 2019年12月07日
* @param $value
* @return false|string
*/
public function setPasswordAttr($value)
{
return password_hash($value, PASSWORD_DEFAULT);
}
/**
* 用户列表
*
* @time 2019年12月08日
* @throws \think\db\exception\DbException
* @return \think\Paginator
*/
public function getList(): \think\Paginator
{
return $this->withoutField(['updated_at'], true)
->catchSearch()
->catchLeftJoin(Department::class, 'id', 'department_id', ['department_name'])
->order($this->getTable() . '.id', 'desc')
->paginate();
}
/**
* 获取权限
*
* @time 2019年12月12日
* @param $uid
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return array
*/
public function getPermissionsBy($uid = 0): array
{
// 获取超级管理配置 超级管理员全部权限
if ($uid == config('catch.permissions.super_admin_id')) {
return Permissions::select()->column('id');
}
$roles = $uid ? $this->findBy($uid)->getRoles() : $this->getRoles();
$permissionIds = [];
foreach ($roles as $role) {
$permissionIds = array_merge($permissionIds, $role->getPermissions()->column('id'));
}
return array_unique($permissionIds);
}
}

View File

@ -1,15 +0,0 @@
<?php
namespace catchAdmin\permissions\model\search;
trait DepartmentSearch
{
public function searchDepartmentNameAttr($query, $value, $data)
{
return $query->whereLike('department_name', $value);
}
public function searchStatusAttr($query, $value, $data)
{
return $query->where('status', $value);
}
}

View File

@ -1,20 +0,0 @@
<?php
namespace catchAdmin\permissions\model\search;
trait JobsSearch
{
public function searchJobNameAttr($query, $value, $data)
{
return $query->whereLike('job_name', $value);
}
public function searchCodingAttr($query, $value, $data)
{
return $query->whereLike('coding', $value);
}
public function searchStatusAttr($query, $value, $data)
{
return $query->where('status', $value);
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace catchAdmin\permissions\model\search;
use catchAdmin\permissions\model\Roles;
trait PermissionsSearch
{
public function searchPermissionNameAttr($query, $value, $data)
{
return $query->whereLike('permission_name', $value);
}
public function searchIdAttr($query, $value, $data)
{
$query->where('parent_id', $value)->whereOr('id', $value);
}
public function searchRoleIdAttr($query, $value, $data)
{
$permissionIds = [];
$permissions = Roles::where('id', $value)->find()->getPermissions();
foreach ($permissions as $_permission) {
$permissionIds[] = $_permission->pivot->permission_id;
}
if(!empty($permissionIds)) {
$query->whereIn('id', $permissionIds);
}
}
}

View File

@ -1,16 +0,0 @@
<?php
namespace catchAdmin\permissions\model\search;
trait RolesSearch
{
public function searchRoleNameAttr($query, $value, $data)
{
return $query->whereLike('role_name', $value);
}
public function searchIdAttr($query, $value, $data)
{
$query->where('parent_id', $value)->whereOr('id', $value);
}
}

View File

@ -1,25 +0,0 @@
<?php
namespace catchAdmin\permissions\model\search;
trait UserSearch
{
public function searchUsernameAttr($query, $value, $data)
{
return $query->whereLike('username', $value);
}
public function searchEmailAttr($query, $value, $data)
{
return $query->whereLike('email', $value);
}
public function searchStatusAttr($query, $value, $data)
{
return $query->where($this->aliasField('status'), $value);
}
public function searchDepartmentIdAttr($query, $value, $data)
{
return $query->where($this->aliasField('department_id'), $value);
}
}

View File

@ -1,11 +0,0 @@
{
"name": "权限管理",
"alias": "permissions",
"description": "",
"keywords": [],
"order": 2,
"services": [],
"aliases": {},
"files": [],
"requires": []
}

View File

@ -1,24 +0,0 @@
<?php
namespace catchAdmin\permissions\request;
use catchAdmin\permissions\model\Users;
use catcher\base\CatchRequest;
class CreateRequest extends CatchRequest
{
protected function rules(): array
{
// TODO: Implement rules() method.
return [
'username|用户名' => 'require|max:20',
'password|密码' => 'require|min:5|max:12',
'email|邮箱' => 'require|email|unique:'.Users::class,
];
}
protected function message(): array
{
// TODO: Implement message() method.
}
}

View File

@ -1,23 +0,0 @@
<?php
namespace catchAdmin\permissions\request;
use catchAdmin\permissions\model\Users;
use catcher\base\CatchRequest;
class UpdateRequest extends CatchRequest
{
protected function rules(): array
{
// TODO: Implement rules() method.
return [
'username|用户名' => 'require|max:20',
'password|密码' => 'sometimes|min:5|max:12',
'email|邮箱' => 'require|email|unique:'.Users::class,
];
}
protected function message(): array
{
// TODO: Implement message() method.
}
}

View File

@ -1,21 +0,0 @@
<?php
// 角色
$router->resource('roles', '\catchAdmin\permissions\controller\Role');
// 角色列表
$router->get('/role/get/permissions', '\catchAdmin\permissions\controller\Role@getPermissions');
// 权限
$router->resource('permissions', '\catchAdmin\permissions\controller\Permission');
// 部门
$router->resource('departments', '\catchAdmin\permissions\controller\Department');
// 岗位
$router->resource('jobs', '\catchAdmin\permissions\controller\Job');
$router->get('jobs/all', '\catchAdmin\permissions\controller\Job@getAll');
// 用户
$router->resource('users', '\catchAdmin\permissions\controller\User');
// 切换状态
$router->put('users/switch/status/<id>', '\catchAdmin\permissions\controller\User@switchStatus');
$router->put('users/recover/<id>', '\catchAdmin\permissions\controller\User@recover');
$router->get('users/get/roles', '\catchAdmin\permissions\controller\User@getRoles');
$router->get('user/info', '\catchAdmin\permissions\controller\User@info');

View File

@ -1,31 +0,0 @@
<?php
namespace catchAdmin\system\controller;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catchAdmin\system\model\Attachments as AttachmentsModel;
use catcher\Utils;
use think\facade\Filesystem;
class Attachments extends CatchController
{
public function index(AttachmentsModel $model)
{
return CatchResponse::paginate($model->getList());
}
public function delete($id, AttachmentsModel $model)
{
$ids = Utils::stringToArrayBy($id);
foreach ($ids as $id) {
$attachment = $model->findBy($id);
if ($attachment && $model->deleteBy($id)) {
Filesystem::delete($attachment->path);
}
}
return CatchResponse::success();
}
}

View File

@ -1,65 +0,0 @@
<?php
namespace catchAdmin\system\controller;
use app\Request;
use catcher\base\CatchController;
use catchAdmin\system\model\Config as ConfigModel;
use catcher\CatchResponse;
use think\response\Json;
class Config extends CatchController
{
protected $configModel;
public function __construct(ConfigModel $configModel)
{
$this->configModel = $configModel;
}
/**
* 获取父级别配置
*
* @time 2020年04月17日
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return Json
*/
public function parent()
{
return CatchResponse::success($this->configModel->getParentConfig());
}
/**
* 存储配置
*
* @time 2020年04月17日
* @param Request $request
* @return Json
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\db\exception\DataNotFoundException
*/
public function save(Request $request)
{
return CatchResponse::success([
'id' => $this->configModel->storeBy($request->param()),
'parents' => $this->configModel->getParentConfig(),
]);
}
/**
* 获取配置
*
* @time 2020年04月20日
* @param $id
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return Json
*/
public function read($id)
{
return CatchResponse::success($this->configModel->getConfig($id));
}
}

View File

@ -1,106 +0,0 @@
<?php
namespace catchAdmin\system\controller;
use catcher\base\CatchRequest as Request;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use think\facade\Console;
use think\facade\Db;
use think\Paginator;
class DataDictionary extends CatchController
{
/**
*
* @time 2019年12月13日
* @param Request $request
* @return \think\response\Json
*/
public function tables(Request $request): \think\response\Json
{
$tables = Db::query('show table status');
$tablename = $request->get('tablename');
$engine = $request->get('engine');
$searchTables = [];
$searchMode = false;
if ($tablename || $engine) {
$searchMode = true;
}
foreach ($tables as $key => &$table) {
$table = array_change_key_case($table);
$table['index_length'] = $table['index_length'] > 1024 ? intval($table['index_length']/1024) .'MB' : $table['index_length'].'KB';
$table['data_length'] = $table['data_length'] > 1024 ? intval($table['data_length']/1024) .'MB' : $table['data_length'].'KB';
$table['create_time'] = date('Y-m-d', strtotime($table['create_time']));
// 搜索
if ($tablename && !$engine && stripos($table['name'], $tablename) !== false) {
$searchTables[] = $table;
}
// 搜索
if (!$tablename && $engine && stripos($table['engine'], $engine) !== false) {
$searchTables[] = $table;
}
if ($tablename && $engine && stripos($table['engine'], $engine) !== false && stripos($table['name'], $tablename) !== false) {
$searchTables[] = $table;
}
}
return CatchResponse::paginate(Paginator::make(!$searchMode ? $tables : $searchTables, $request->get('limit') ?? 10, $request->get('page') ?? 1, $searchMode ? count($searchTables) : count($tables), false, []));
}
/**
*
* @time 2019年12月13日
* @param $table
* @return \think\response\Json
* @throws \Exception
*/
public function view($table): \think\response\Json
{
$fields = Db::query('show full columns from ' . $table);
array_walk($fields, function (&$item){
$item = array_change_key_case($item);
});
return CatchResponse::success($fields);
}
/**
*
* @time 2019年12月13日
* @return \think\response\Json
*/
public function optimize(): \think\response\Json
{
$tables = \request()->post('data');
foreach ($tables as $table) {
Db::query(sprintf('optimize table %s', $table));
}
return CatchResponse::success([], '优化成功');
}
/**
*
* @time 2019年12月13日
* @throws FailedException
* @return \think\response\Json
*/
public function backup(): \think\response\Json
{
try {
Console::call('backup:data', [trim(implode(',', \request()->post('data')), ','), '-z']);
}catch (\Exception $e) {
throw new FailedException($e->getMessage());
}
return CatchResponse::success([], '备份成功');
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace catchAdmin\system\controller;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\generate\Generator;
use think\Request;
class Generate extends CatchController
{
public function save(Request $request, Generator $generator)
{
return CatchResponse::success($generator->done($request->param()));
}
/**
* 预览
*
* @time 2020年04月29日
* @param Request $request
* @param Generator $generator
* @return \think\response\Json
*/
public function preview(Request $request, Generator $generator)
{
return CatchResponse::success($generator->preview($request->param()));
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace catchAdmin\system\controller;
use catcher\base\CatchController;
use catcher\CatchResponse;
use think\facade\Db;
use catchAdmin\system\model\LoginLog as Log;
class LoginLog extends CatchController
{
/**
*
* @time 2020年04月28日
* @param Log $log
* @throws \think\db\exception\DbException
* @return \think\response\Json
*/
public function list(Log $log)
{
return CatchResponse::paginate($log->paginate());
}
/**
* 清空
*
* @time 2020年04月28日
* @param Log $log
* @throws \Exception
* @return \think\response\Json
*/
public function empty(Log $log)
{
return CatchResponse::success($log->where('id', '>', 0)->delete(), '清空成功');
}
}

View File

@ -1,34 +0,0 @@
<?php
namespace catchAdmin\system\controller;
use catcher\base\CatchController;
use catcher\CatchResponse;
use think\facade\Db;
use catchAdmin\system\model\OperateLog as Log;
class OperateLog extends CatchController
{
/**
*
* @time 2020年04月28日
* @param Log $log
* @throws \think\db\exception\DbException
* @return \think\response\Json
*/
public function list(Log $log)
{
return CatchResponse::paginate($log->getList());
}
/**
*
* @time 2020年04月28日
* @param Log $log
* @throws \Exception
* @return \think\response\Json
*/
public function empty(Log $log)
{
return CatchResponse::success($log->where('id', '>', 0)->delete(), '清空成功');
}
}

View File

@ -1,57 +0,0 @@
<?php
/**
* @filename Upload.php
* @createdAt 2020/1/25
* @project https://github.com/yanwenwu/catch-admin
* @document http://doc.catchadmin.com
* @author JaguarJack <njphper@gmail.com>
* @copyright By CatchAdmin
* @license https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt
*/
namespace catchAdmin\system\controller;
use catchAdmin\system\model\Attachments;
use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\CatchUpload;
class Upload extends CatchController
{
protected $attachment;
public function __construct(Attachments $attachment)
{
$this->attachment = $attachment;
}
/**
* image upload
*
* @time 2020年01月25日
* @param CatchRequest $request
* @param CatchUpload $upload
* @return \think\response\Json
*/
public function image(CatchRequest $request, CatchUpload $upload): \think\response\Json
{
$images = $request->file();
return CatchResponse::success($upload->checkImages($images)->multiUpload($images['image']));
}
/**
* file upload
*
* @time 2020年01月25日
* @param CatchRequest $request
* @param CatchUpload $upload
* @return \think\response\Json
*/
public function file(CatchRequest $request, CatchUpload $upload): \think\response\Json
{
$files = $request->file();
return CatchResponse::success($upload->checkFiles($files)->multiUpload($files['file']));
}
}

View File

@ -1,40 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class LoginLog extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('login_log',['engine'=>'Myisam', 'comment' => '登录日志', 'signed' => false]);
$table->addColumn('login_name', 'string',['limit' => 50,'default'=>'','comment'=>'用户名'])
->addColumn('login_ip', 'string',['default'=>0, 'limit' => 20, 'comment'=>'登录地点ip', 'signed' => false])
->addColumn('browser', 'string',['default'=> '','comment'=>'浏览器'])
->addColumn('os', 'string',['default'=> '','comment'=>'操作系统'])
->addColumn('login_at', 'integer', array('default'=>0,'comment'=>'登录时间', 'signed' => false ))
->addColumn('status', 'integer',['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY,'default'=> 1,'comment'=>'1 成功 2 失败'])
->create();
}
}

View File

@ -1,42 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class OperateLog extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('operate_log',['engine'=>'Myisam', 'comment' => '操作日志', 'signed' => false]);
$table->addColumn('module', 'string',['limit' => 50,'default'=>'','comment'=>'模块名称'])
->addColumn('operate', 'string',['default'=> '', 'limit' => 20, 'comment'=>'操作模块'])
->addColumn('route', 'string',['default'=> '','limit' => 100, 'comment'=>'路由'])
->addColumn('params', 'string',['default'=> '','limit' => 1000, 'comment'=>'参数'])
->addColumn('ip', 'string',['default'=>'', 'limit' => 20,'comment'=>'ip', 'signed' => false])
->addColumn('creator_id', 'integer',['default'=> 0,'comment'=>'创建人ID', 'signed' => false])
->addColumn('method', 'string',['default'=> '','comment'=>'请求方法'])
->addColumn('created_at', 'integer', array('default'=>0,'comment'=>'登录时间', 'signed' => false ))
->create();
}
}

View File

@ -1,44 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Attachments extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('attachments',['engine'=>'Myisam', 'comment' => '附件管理', 'signed' => false]);
$table->addColumn('path', 'string',['limit' => 50,'default'=>'','comment'=>'附件存储路径'])
->addColumn('url', 'string',['default'=> '', 'limit' => 100, 'comment'=>'资源地址'])
->addColumn('mime_type', 'string',['default'=> '', 'limit' => 100, 'comment'=>'资源mimeType'])
->addColumn('file_ext', 'string',['default'=> '','limit' => 100, 'comment'=>'资源后缀'])
->addColumn('file_size', 'integer',['default'=> 0, 'comment'=>'资源大小'])
->addColumn('filename', 'string',['default'=>'', 'limit' => 255, 'comment'=>'资源名称'])
->addColumn('driver', 'string',['default'=> 0, 'limit' => 20, 'comment' => 'local,oss,qcloud,qiniu'])
->addColumn('created_at', 'integer', array('default'=>0, 'comment'=>'创建时间', 'signed' => false ))
->addColumn('updated_at', 'integer', array('default'=>0, 'comment'=>'更新时间', 'signed' => false ))
->addColumn('deleted_at', 'integer', array('default'=>0, 'comment'=>'删除时间', 'signed' => false ))
->create();
}
}

View File

@ -1,44 +0,0 @@
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class Config extends Migrator
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('config',['engine'=>'InnoDB', 'comment' => '配置管理', 'signed' => false]);
$table->addColumn('name', 'string',['limit' => 50,'default'=>'','comment'=>'配置名称'])
->addColumn('pid', 'integer', array('default'=> 0,'comment'=>'父级配置', 'signed' => false ))
->addColumn('component', 'string', ['default'=> '', 'limit' => 100, 'comment'=>'tab 引入的组件名称'])
->addColumn('key', 'string',['default'=> '', 'limit' => 100, 'comment'=>'配置键名'])
->addColumn('value', 'string',['default'=> '', 'limit' => 255, 'comment'=>'配置键值'])
->addColumn('status', 'integer',['limit' => \Phinx\Db\Adapter\MysqlAdapter::INT_TINY,'default'=> 1,'comment'=>'1 启用 2 禁用'])
->addColumn('creator_id', 'integer', array('default'=> 0,'comment'=>'创建人', 'signed' => false ))
->addColumn('created_at', 'integer', ['default'=> 0,'comment'=>'创建时间', 'signed' => false])
->addColumn('updated_at', 'integer', ['default'=> 0,'comment'=>'更新时间', 'signed' => false])
->addColumn('deleted_at', 'integer', ['default'=> 0,'comment'=>'删除时间', 'signed' => false])
->create();
}
}

View File

@ -1,36 +0,0 @@
<?php
use think\migration\Seeder;
class ConfigSeed extends Seeder
{
/**
* Run Method.
*
* Write your database seeder using this method.
*
* More information on writing seeders is available here:
* http://docs.phinx.org/en/latest/seeding.html
*/
public function run()
{
$data = [
[
'name' => '基础配置',
'pid' => 0,
'component' => 'basis',
'key' => 'basis',
],
[
'name' => '上传配置',
'pid' => 0,
'component' => 'upload',
'key' => 'upload',
],
];
foreach ($data as $item) {
\catchAdmin\system\model\Config::create($item);
}
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace catchAdmin\system\model;
use catcher\base\CatchModel;
class Attachments extends CatchModel
{
protected $name = 'attachments';
protected $field = [
'id', //
'path', // 附件存储路径
'url', // 资源地址
'mime_type', // 资源mimeType
'file_ext', // 资源后缀
'file_size', // 资源大小
'filename', // 资源名称
'driver', // local,oss,qcloud,qiniu
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除时间
];
public function getList()
{
return $this->order('id', 'desc')
->catchSearch()
->paginate();
}
public function searchFileExtAttr($query, $value, $data)
{
return $query->where('file_ext', $value);
}
public function searchMimeTypesAttr($query, $value, $data)
{
return $query->where('mime_type', $value);
}
public function searchDriver($query, $value, $data)
{
return $query->where('driver', $value);
}
}

View File

@ -1,210 +0,0 @@
<?php
namespace catchAdmin\system\model;
use catcher\base\CatchModel;
use thans\jwt\exception\UserNotDefinedException;
use think\Model;
class Config extends CatchModel
{
protected $name = 'config';
protected $pk = 'id';
protected $field = [
'id', //
'name', // 配置名称
'pid', // 父级配置
'key', // 配置键名
'value', // 配置键值
'component', // 组件
'status', // 1 启用 2 禁用
'creator_id', // 创建人
'created_at', // 创建时间
'updated_at', // 更新时间
'deleted_at', // 删除时间
];
/**
*
* @time 2020年04月17日
* @return \think\Collection
*@throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\db\exception\DataNotFoundException
*/
public function getParentConfig()
{
return $this->where('pid', 0)
->field(['id', 'name', 'component'])->select();
}
/**
* 存储配置
*
* @time 2020年04月20日
* @param array $data
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return bool
*/
public function storeBy(array $data)
{
if (empty($data)) {
return true;
}
// 子配置
if ($data['pid'] ?? false) {
$config = \json_decode($data['config'], true);
$pid = $data['pid'];
unset($data['pid']);
/**[
'key' => [
'k' => 'v'
],
'k' => 'v'
]*/
foreach ($config as $key => $value) {
if (empty($value)) {
continue;
}
// 如果二级配置存在
$secondLevel = $this->isExistConfig($key, $pid);
if ($secondLevel) {
// value 是字符串
if (!is_array($value)) {
if ($value != $secondLevel->value) {
$secondLevel->value = $value;
$secondLevel->save();
}
} else {
// 数组
$thirdLevel = [];
$this->subConfig($secondLevel->id, ['id', 'key', 'value'])
->each(function ($item, $key) use (&$thirdLevel){
$thirdLevel[$item['key']] = $item;
});
if (!empty($value)) {
$new = [];
foreach ($value as $k => $v) {
if (isset($thirdLevel[$k])) {
if ($v != $thirdLevel[$k]->value) {
$thirdLevel[$k]->value = $v;
$thirdLevel[$k]->save();
}
} else {
$new[] = [
'pid' => $secondLevel->id,
'key' => $k,
'value' => $v,
];
}
}
if (!empty($new)) {
parent::insertAllBy($new);
}
}
}
} else {
if (!is_array($value)) {
parent::createBy([
'pid' => $pid,
'key' => $key,
'value' => $value,
]);
} else {
$id = parent::createBy([
'pid' => $pid,
'key' => $key,
]);
if (!empty($value)) {
$newConfig = [];
foreach ($value as $k => $v) {
$newConfig[] = [
'key' => $k,
'value' => $v,
'pid' => $id,
];
}
parent::insertAllBy($newConfig);
}
}
}
}
return true;
}
return parent::storeBy($data);
}
/**
* 配置是否存在
*
* @time 2020年04月19日
* @param $key
* @param int $pid
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return array|Model|null
*/
public function isExistConfig($key, $pid = 0)
{
return $this->where('pid', $pid)
->where('key', $key)
->find();
}
/**
* 获取子配置
*
* @time 2020年04月19日
* @param int $pid
* @param array $field
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return \think\Collection
*/
public function subConfig($pid = 0, array $field = ['*'])
{
return $this->where('pid', $pid)
->field($field)
->select();
}
/**
* 获取配置
*
* @time 2020年04月20日
* @param int $pid
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @return array|mixed
*/
public function getConfig($pid = 0)
{
$data = [];
$configs = $this->where('pid', $pid)
->field('id,`key` as k,value,pid')
->select();
foreach ($configs as $config) {
if ($config->value !== '') {
$data[$config->k] = $config->value;
} else {
$data[$config->k] = $this->getConfig($config->id);
}
}
return $data;
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace catchAdmin\system\model;
use catcher\traits\db\BaseOptionsTrait;
class LoginLog extends \think\Model
{
use BaseOptionsTrait;
protected $name = 'login_log';
protected $field = [
'id', //
'login_name', // 用户名
'login_ip', // 登录地点ip
'browser', // 浏览器
'os', // 操作系统
'login_at', // 登录时间
'status', // 1 成功 2 失败
];
}

View File

@ -1,40 +0,0 @@
<?php
namespace catchAdmin\system\model;
use catchAdmin\permissions\model\Users;
use catcher\traits\db\BaseOptionsTrait;
class OperateLog extends \think\Model
{
use BaseOptionsTrait;
protected $name = 'operate_log';
protected $field = [
'id', //
'module', // 模块名称
'operate', // 操作模块
'route', // 路由
'params', // 参数
'ip', // ip
'creator_id', // 创建人ID
'method', // 请求方法
'created_at', // 登录时间
];
/**
* get list
*
* @time 2020年04月28日
* @param $params
* @throws \think\db\exception\DbException
* @return void
*/
public function getList()
{
return $this->field([$this->aliasField('*')])
->catchJoin(Users::class, 'id', 'creator_id', ['username as creator'])
->order($this->aliasField('id'), 'desc')
->paginate();
}
}

View File

@ -1,11 +0,0 @@
{
"name": "系统管理",
"alias": "system",
"description": "",
"keywords": [],
"order": 2,
"services": [],
"aliases": {},
"files": [],
"requires": []
}

View File

@ -1,28 +0,0 @@
<?php
// 登录日志
$router->get('log/login', '\catchAdmin\system\controller\LoginLog@list');
$router->delete('loginLog/empty', '\catchAdmin\system\controller\LoginLog@empty');
// 操作日志
$router->get('log/operate', '\catchAdmin\system\controller\OperateLog@list');
$router->delete('operateLog/empty', '\catchAdmin\system\controller\OperateLog@empty');
// 数据字典
$router->get('tables', '\catchAdmin\system\controller\DataDictionary@tables');
$router->get('table/view/<table>', '\catchAdmin\system\controller\DataDictionary@view');
$router->post('table/optimize', '\catchAdmin\system\controller\DataDictionary@optimize');
$router->post('table/backup', '\catchAdmin\system\controller\DataDictionary@backup');
// 上传
$router->post('upload/image', '\catchAdmin\system\controller\Upload@image');
$router->post('upload/file', '\catchAdmin\system\controller\Upload@file');
// 附件
$router->resource('attachments', '\catchAdmin\system\controller\Attachments');
// 配置
$router->get('config/parent', '\catchAdmin\system\controller\Config@parent');
$router->resource('config', '\catchAdmin\system\controller\Config');
// 代码生成
$router->post('generate', '\catchAdmin\system\controller\Generate@save');
$router->post('generate/preview', '\catchAdmin\system\controller\Generate@preview'); // 预览

View File

@ -79,27 +79,38 @@ class CompressPackageCommand extends Command
{
$zip = new \ZipArchive();
//dd($zip->open(CatchAdmin::directory() . 'permissions.zip'));
$res = $zip->open(CatchAdmin::directory() . 'permissions.zip');
$extractToPath = CatchAdmin::directory() . 'goods';
// 创建解压包的临时目录
$tempExtractToPath = runtime_path('module' . DIRECTORY_SEPARATOR . date('YmdHis'));
CatchAdmin::makeDirectory($tempExtractToPath);
/**$extractToPath = CatchAdmin::directory();
if (is_dir($extractToPath)) {
$this->rmDir($extractToPath);
}
}*/
$extractToPath = CatchAdmin::makeDirectory($extractToPath);
$res = $zip->open(CatchAdmin::directory() . 'permissions.zip');
if ($res === true) {
$zip->extractTo($extractToPath);
$zip->extractTo($tempExtractToPath);
$zip->close();
$this->output->info('unzip successfully');
$this->copyFileToModule($tempExtractToPath, 'permissions', $tempExtractToPath);
$this->rmDir($tempExtractToPath);
$this->output->info('更新成功');
return true;
}
$this->output->error('unzip failed');
}
/**
* 删除目录
*
* @time 2020年04月29日
* @param $packageDir
* @return void
*/
protected function rmDir($packageDir)
{
$fileSystemIterator = new \FilesystemIterator($packageDir);
@ -123,6 +134,37 @@ class CompressPackageCommand extends Command
rmdir($packageDir);
}
/**
*
* @time 2020年04月29日
* @param $path
* @param string $moduleName
* @param $tempExtractToPath
* @return void
*/
protected function copyFileToModule($path, $moduleName = '', $tempExtractToPath)
{
$fileSystemIterator = new \FilesystemIterator($path . $moduleName ? : '');
foreach ($fileSystemIterator as $fileSystem) {
if ($fileSystem->isDir()) {
$this->copyFileToModule($fileSystem->getPathname(), '', $tempExtractToPath);
} else {
// 原模块文件
$originModuleFile = str_replace($tempExtractToPath, CatchAdmin::directory(), $fileSystem->getPathname());
// md5 校验 文件是否修改过
if (md5_file($originModuleFile) != md5_file($fileSystem->getPathname())) {
if (!copy($fileSystem->getPathname(), $originModuleFile)) {
$this->output->error($originModuleFile . ' 更新失败');
} else {
$this->output->error($originModuleFile . ' 更新成功');
}
}
}
}
}
/**
* get files from dir
*