first commit

This commit is contained in:
yanwenwu
2018-11-16 17:45:37 +08:00
parent a9865a2982
commit 4d8f109e10
235 changed files with 38293 additions and 36 deletions

1
application/.htaccess Normal file
View File

@@ -0,0 +1 @@
deny from all

View File

@@ -0,0 +1,49 @@
<?php
namespace app\admin\controller;
use think\Controller;
use app\traits\ControllerTrait;
abstract class Base extends Controller
{
use ControllerTrait;
protected $limit = 20;
protected $page = 1;
protected $middleware = ['checkLogin', 'auth'];
/**
* 过滤参数
*
* @time at 2018年11月15日
* @param $params
* @return void
*/
protected function checkParams(&$params)
{
$this->limit = $params['limit'] ?? $this->limit;
$this->page = $params['page'] ?? $this->page;
foreach ($params as $key => $param) {
if (!$param || $key == 'limit' || $key == 'page') {
unset($params[$key]);
}
}
$this->start = $this->start();
}
/**
* Table ID Start
*
* @time at 2018年11月16日
* @return float|int
*/
protected function start()
{
return (int)$this->limit * (int)$this->page;
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace app\admin\controller;
use think\permissions\facade\Permissions;
use think\permissions\facade\Roles;
use app\service\MenuService;
class Index extends Base
{
protected $middleware = [ 'checkLogin' ];
/**
* 首页
*
* @time at 2018年11月15日
* @return mixed|string
*/
public function index(MenuService $menuService)
{
$loginUser = $this->getLoginUser();
$userHasRoles = $loginUser->getRoles();
$permissionIds = [];
$userHasRoles->each(function ($role, $key) use (&$permissionIds) {
$permissionIds = array_merge($permissionIds, Roles::getRoleBy($role->id)->getPermissions(false));
});
$permissions = Permissions::whereIn('id', $permissionIds)->where('is_show', 1)->select();
$this->permissions = $menuService->tree($permissions);
$this->loginUser = $loginUser;
return $this->fetch();
}
public function main()
{
return "this is main";
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace app\admin\controller;
use app\traits\Auth;
use think\Controller;
class Login extends Controller
{
use Auth;
protected $redirect = '/index';
/**
* Login Page
*
* @return mixed
*/
public function login()
{
// 登录逻辑
if ($this->request->isPost()) {
$this->authLogin($this->request);
}
return $this->fetch('/index/login');
}
/**
* 登出
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\think\response\Redirect
*/
public function logout()
{
$this->authLogout();
return redirect(url('login'));
}
/**
* 验证规则
*
* @time at 2018年11月13日
* @return array
*/
protected function rule()
{
return [
$this->name() => 'require',
'password|密码' => 'require',
//'captcha|验证码' => 'require|captcha'
];
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace app\admin\controller;
use think\Collection;
use think\permissions\facade\Permissions;
use app\validates\PermissionValidate;
use app\service\MenuService;
class Permission extends Base
{
public function index(MenuService $menuService)
{
$this->permissions = new Collection($menuService->sort(Permissions::select()));
return $this->fetch();
}
/**
* Create Data
*
* @time at 2018年11月13日
* @return mixed|string
*/
public function create(PermissionValidate $validate, MenuService $menuService)
{
if ($this->request->isPost()) {
$data = $this->request->post();
if ($err = $validate->getErrors($data)) {
$this->error($err);
}
Permissions::store($data) ? $this->success('添加成功', url('permission/index')) : $this->error('添加失败');
}
$this->permissions = $menuService->sort(Permissions::select());
$this->permissionId = $this->request->param('id') ?? 0;
return $this->fetch();
}
/**
* Edit Data
*
* @time at 2018年11月13日
* @return mixed|string
*/
public function edit(PermissionValidate $validate, MenuService $menuService)
{
if ($this->request->isPost()) {
$data = $this->request->post();
if ($err = $validate->getErrors($data)) {
$this->error($err);
}
Permissions::updateBy($data['id'], $data) !== false ? $this->success('编辑成功', url('permission/index')) : $this->error('');
}
$permissionId = $this->request->param('id');
if (!$permissionId) {
$this->error('不存在的数据');
}
$this->permissions = $menuService->sort(Permissions::select());
$this->permission = Permissions::getPermissionBy($permissionId);
return $this->fetch();
}
/**
* Delete Data
*
* @time at 2018年11月13日
* @return void
*/
public function delete()
{
$permissionId = $this->request->post('id');
if (!$permissionId) {
$this->error('不存在数据');
}
if (Permissions::where('pid', $permissionId)->find()) {
$this->error('请先删除子菜单');
}
// 删除权限关联的角色信息
Permissions::detachRole($permissionId);
if (Permissions::deleteBy($permissionId)) {
$this->success('删除成功', url('permission/index'));
}
$this->error('删除失败');
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace app\admin\controller;
use think\permissions\facade\Roles;
use app\validates\RoleValidate;
use think\permissions\facade\Permissions;
use app\service\MenuService;
class Role extends Base
{
public function index()
{
$this->roles = Roles::paginate(10);
return $this->fetch();
}
/**
* create Data
*
* @time at 2018年11月13日
* @return mixed|string
*/
public function create(RoleValidate $validate)
{
if ($this->request->isPost()) {
$data = $this->request->post();
if ($err = $validate->getErrors($data)) {
$this->error($err);
}
Roles::store($data) ? $this->success('创建成功', url('role/index')) : $this->error('创建失败');
}
return $this->fetch();
}
/**
* Edit Data
*
* @time at 2018年11月13日
* @return mixed|string
*/
public function edit(RoleValidate $validate)
{
if ($this->request->isPost()) {
$data = $this->request->post();
if ($err = $validate->getErrors($data)) {
$this->error($err);
}
Roles::updateBy($data['id'], $data) !== false ? $this->success('编辑成功', url('role/index')) : $this->error('编辑失败');
}
$roleId = $this->request->param('id');
$role = Roles::getRoleBy($roleId);
$this->role = $role;
return $this->fetch();
}
/**
* Delete Data
*
* @time at 2018年11月13日
* @return void
*/
public function delete()
{
$roleId = $this->request->post('id');
if (!$roleId) {
$this->error('角色信息不存在');
}
// 删除角色相关的用户
Roles::detachUsers($roleId);
// 删除角色相关的权限
Roles::detachPermissions($roleId);
if (Roles::deleteBy($roleId)) {
$this->success('删除成功', url('role/index'));
}
$this->error('删除失败');
}
/**
* 获取角色权限
*
* @time at 2018年09月21日
* @return void
*/
public function getPermissionsOfRole(MenuService $menuService)
{
$field = ['name', 'id', 'pid'];
$roleId = $this->request->param('role_id');
$permissions = Permissions::field($field)->all();
$roleHasPermissions = Roles::getRoleBy($roleId)->getPermissions(false);
$permissions = $permissions->each(function ($item, $key) use ($roleHasPermissions){
if (!$item->pid) {
$item->open = true;
}
$item->checked = in_array($item->id, $roleHasPermissions) ? true : false;
return $item;
});
$this->success('', '', $menuService->sort($permissions));
}
/**
* 分配权限
*
* @time at 2018年11月15日
* @return mixed|string
*/
public function givePermissions()
{
if ($this->request->isPost()) {
$postData = $this->request->post();
$roleId = $postData['role_id'];
if (!isset($postData['permissions'])) {
Roles::detachPermissions($roleId);
$this->success('分配成功', url('role/index'));
}
$permissions = $postData['permissions'];
Roles::detachPermissions($roleId);
Roles::attachPermissions($roleId, $permissions) ? $this->success('分配成功', url('role/index')) : $this->error('分配失败');
}
$this->role_id = $this->request->param('id');
return $this->fetch('role/givePermissions');
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace app\admin\controller;
use app\model\UserModel;
use app\validates\UserValidate;
use think\permissions\facade\Roles;
class User extends Base
{
/**
* User List
*
* @time at 2018年11月12日
* @return mixed|string
*/
public function index(UserModel $userModel)
{
$params = $this->request->param();
$this->checkParams($params);
$this->users = $userModel->getList($params, $this->limit);
return $this->fetch();
}
/**
* create Data
*
* @time at 2018年11月12日
* @return mixed|string
*/
public function create(UserModel $userModel, UserValidate $validate)
{
if ($this->request->isPost()) {
$data = $this->request->post();
if ($err = $validate->getErrors($data)) {
$this->error($err);
}
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
if ($userId = $userModel->store($data)) {
// 分配角色
$this->giveRoles($userModel, $userId, $data);
$this->success('添加成功', url('user/index'));
}
$this->error('添加失败');
}
$this->roles = Roles::all();
return $this->fetch();
}
/**
* Edit Data
*
* @time at 2018年11月12日
* @return mixed|string
*/
public function edit(UserModel $userModel, UserValidate $validate)
{
if ($this->request->isPost()) {
$data = $this->request->post();
if ($err = $validate->getErrors($data)) {
$this->error($err);
}
$this->giveRoles($userModel, $data['id'], $data);
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
$userModel->updateBy($data['id'], $data) ? $this->success('修改成功', url('user/index')) : $this->error('修改失败');
}
$id = $this->request->param('id');
if (!$id) {
$this->error('数据不存在');
}
$user = $userModel->findBy($id);
$userHasRoles = $user->getRoles(false);
$roles = Roles::all()->each(function($item, $key) use ($userHasRoles){
$item->checked = in_array($item->id, $userHasRoles) ? true : false;
return $item;
});
$this->user = $user;
$this->roles = $roles;
return $this->fetch();
}
/**
* Delete Data
*
* @time at 2018年11月12日
* @return void
*/
public function delete(UserModel $userModel)
{
$id = $this->request->post('id');
if (!$id) {
$this->error('不存在的数据');
}
// 删除用户相关的角色
$userModel->detachRoles($id);
if ($userModel->deleteBy($id)) {
$this->success('删除成功', url('user/index'));
}
$this->error('删除失败');
}
/**
* 分配角色
*
* @time at 2018年11月15日
* @param \app\model\UserModel $userModel
* @param int $userId
* @param $data
* @return bool
*/
protected function giveRoles(UserModel $userModel, int $userId, &$data)
{
if (isset($data['roles'])) {
$rolesIds = $data['roles'];
if (!is_array($rolesIds)) {
$rolesIds = [$rolesIds];
}
$userModel->detachRoles($userId);
$userModel->attachRoles($userId, $rolesIds);
unset($data['roles']);
return true;
}
$userModel->detachRoles($userId);
return true;
}
}

View File

@@ -0,0 +1,20 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/13 0013
* Time: 上午 9:33
*/
namespace app\behavior;
class LoginRecord
{
public function run($params)
{
$user = $params['user'];
## 登录记录
$user->login_at = date('Y-m-d h:i:s', time());
$user->login_ip = request()->ip();
$user->save();
}
}

15
application/command.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
return [
'make:curd' => app\command\MakeCurd::class,
'rbac:publish' => think\permissions\command\PermissionPublish::class,
];

View File

@@ -0,0 +1,93 @@
<?php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class MakeCurd extends Command
{
protected $appPath;
protected $stubPath;
// view 默认的三个模板
protected $views = ['index', 'create', 'edit'];
public function __construct()
{
parent::__construct();
$this->appPath = env('app_path');
$this->stubPath = $this->appPath . 'commands' . DIRECTORY_SEPARATOR . 'stub' .DIRECTORY_SEPARATOR;
}
protected function configure()
{
$this->setName('make:curd')
->addArgument('controller', Argument::OPTIONAL, "controller name")
->addArgument('model', Argument::OPTIONAL, "model name")
->addOption('module', null, Option::VALUE_REQUIRED, 'module name')
->setDescription('Create curd option controller model --module?');
}
protected function execute(Input $input, Output $output)
{
// 首先获取默认模块
$moduleName = config('app.default_module');
$controllerName = trim($input->getArgument('controller'));
if (!$controllerName) {
$output->writeln('Controller Name Must Set');exit;
}
$modelName = trim($input->getArgument('model'));
if (!$modelName) {
$output->writeln('Model Name Must Set');exit;
}
if ($input->hasOption('module')) {
$moduleName = $input->getOption('module');
}
$this->makeController($controllerName, $moduleName);
$output->writeln($controllerName . ' controller create success');
$this->makeModel($modelName, $moduleName);
$output->writeln($modelName . ' model create success');
$this->makeView($controllerName, $moduleName);
$output->writeln($controllerName . ' view create success');
}
// 创建控制器文件
protected function makeController($controllerName, $moduleName)
{
$controllerStub = $this->stubPath . 'Controller.stub';
$controllerStub = str_replace(['$controller', '$module'], [ucfirst($controllerName), strtolower($moduleName)], file_get_contents($controllerStub));
$controllerPath = $this->appPath . $moduleName . DIRECTORY_SEPARATOR . 'controller' . DIRECTORY_SEPARATOR;
if (!is_dir($controllerPath)) {
mkdir($controllerPath, 0777, true);
}
return file_put_contents( $controllerPath . $controllerName . '.php', $controllerStub);
}
// 创建模型文件
public function makeModel($modelName, $moduleName)
{
$modelStub = $this->stubPath . 'Model.stub';
$modelPath = $this->appPath . DIRECTORY_SEPARATOR . 'models';
if (!is_dir($modelPath)) {
mkdir($modelPath, 0777, true);
}
$modelStub = str_replace('$model', ucfirst($modelName), file_get_contents($modelStub));
return file_put_contents($modelPath . DIRECTORY_SEPARATOR . $modelName . 'Model.php', $modelStub);
}
// 创建模板
public function makeView($controllerName, $moduleName)
{
$viewStub = $this->stubPath . 'View.stub';
$viewPath = (config('template.view_base') ? config('template.view_base') . $moduleName . DIRECTORY_SEPARATOR : env('app_path') . $moduleName . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR) . strtolower($controllerName);
if (!is_dir($viewPath)) {
mkdir($viewPath, 0777, true);
}
foreach ($this->views as $view) {
file_put_contents($viewPath . DIRECTORY_SEPARATOR . $view .'.html', file_get_contents($viewStub));
}
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace app\$module\controller;
class $controller extends Base
{
public function index()
{
return $this->fetch();
}
public function create()
{
return $this->fetch();
}
public function edit()
{
return $this->fetch();
}
public function delete()
{}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace app\models;
class $modelModel extends AbstractBaseModel
{
protected $name = '$model';
}

View File

58
application/common.php Normal file
View File

@@ -0,0 +1,58 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
/**
* 钩子行为
*/
if (!function_exists('hook')) {
function hook($behavior, $params) {
\think\facade\Hook::exec($behavior, $params);
}
}
/**
* 编辑按钮
*/
if (!function_exists('editButton')) {
function editButton(string $url, string $name = '编辑') {
return sprintf('<a href="%s"><button class="btn btn-info btn-xs edit" type="button"><i class="fa fa-paste"></i> %s</button></a>', $url, $name);
}
}
/**
* 增加按钮
*/
if (!function_exists('createButton')) {
function createButton(string $url, string $name, $isBig = true) {
return $isBig ? sprintf('<a href="%s"> <button type="button" class="btn btn-w-m btn-primary"><i class="fa fa-check-square-o"></i> %s</button></a>', $url, $name) :
sprintf('<a href="%s"> <button type="button" class="btn btn-xs btn-primary"><i class="fa fa-check-square-o"></i> %s</button></a>', $url, $name);
}
}
/**
* 删除按钮
*/
if (!function_exists('deleteButton')) {
function deleteButton(string $url, int $id, string $name="删除") {
return sprintf('<button class="btn btn-danger btn-xs delete" data-url="%s" data=%d type="button"><i class="fa fa-trash"></i> %s</button>', $url, $id, $name);
}
}
/**
* 搜索按钮
*/
if (!function_exists('searchButton')) {
function searchButton(string $name="搜索") {
return sprintf('<button class="btn btn-white" type="submit"><i class="fa fa-search"></i> %s</button>', $name);
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/16 0016
* Time: 下午 14:51
*/
namespace app\component\upload;
use think\exception\ThrowableError;
use think\facade\Request;
use app\exceptions\UploadException;
class LocalUpload implements UploadInterface
{
protected $name = null;
/**
* Upload File
*
* @time at 2018年11月16日
* @return string
*/
public function file(){}
/**
* Upload Image
*
* @time at 2018年11月16日
* @return string
*/
public function image()
{
try {
$file = Request::file($this->name);
if (!$this->name) {
throw new UploadException('请选择上传的图片');
}
$info = $file->validate(config('admin.image'))->move(config('admin.local_upload_path'));
if (!$info) {
throw new UploadException($file->getError());
}
return $info->getSaveName();
} catch (UploadException $exception) {
return $exception->getMessage();
}
}
/**
* Set Image Name
*
* @time at 2018年11月16日
* @param $name
* @return $this
*/
public function name($name)
{
$this->name = $name;
return $this;
}
}

View File

@@ -0,0 +1,15 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/16 0016
* Time: 下午 14:50
*/
namespace app\component\upload;
interface UploadInterface
{
public function file();
public function image();
}

View File

@@ -0,0 +1,13 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/13 0013
* Time: 上午 10:49
*/
namespace app\exceptions;
class AppException extends \Exception
{
}

View File

@@ -0,0 +1,14 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/16 0016
* Time: 下午 15:03
*/
namespace app\exceptions;
class UploadException extends \Exception
{
}

View File

@@ -0,0 +1,15 @@
<?php
namespace app\http\middleware;
class checkLogin
{
public function handle($request, \Closure $next)
{
if (!$request->session('user')) {
return redirect(url('login'));
}
return $next($request);
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/12 0012
* Time: 上午 11:05
*/
namespace app\model;
use think\Model;
abstract class AbstractBaseModel extends Model
{
const LIMIT = 20;
/**
* Store Data
*
* @time at 2018年11月12日
* @param array $data
* @return bool
*/
public function store(array $data)
{
return $this->save($data) ? $this->id : false;
}
/**
* Find By ID
*
* @time at 2018年11月12日
* @param int $id
* @return array|false|\PDOStatement|string|\think\Model
*/
public function findBy(int $id)
{
return $this->where('id', $id)->find();
}
/**
* Update By ID && Data
*
* @time at 2018年11月12日
* @param int $id
* @param array $data
* @return bool
*/
public function updateBy(int $id, array $data)
{
return $this->save($data, ['id' => $id]);
}
/**
* Delete By ID
*
* @time at 2018年11月12日
* @param int $id
* @return bool|null
*/
public function deleteBy(int $id)
{
return $this->where('id', $id)->delete();
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace app\model;
use think\permissions\traits\hasRoles;
class UserModel extends AbstractBaseModel
{
use hasRoles;
protected $name = 'users';
/**
* Users List
*
* @time at 2018年11月14日
* @param $params
* @return \think\Paginator
*/
public function getList($params, $limit = self::LIMIT)
{
if (!count($params)) {
return $this->paginate($limit);
}
if (isset($params['name'])) {
$user = $this->whereLike('name', '%'.$params['name'].'%');
}
if (isset($params['email'])) {
$user = $this->whereLike('email', '%'.$params['email'].'%');
}
return $user->paginate($limit, false, ['query' => request()->param()]);
}
}

15
application/provider.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用容器绑定定义
return [
];

View File

@@ -0,0 +1,55 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/13 0013
* Time: 上午 10:50
*/
namespace app\service;
use think\Collection;
class MenuService
{
/**
* 树形结构
*
* @time at 2018年11月13日
* @param $menu
* @return Collection
*/
public function tree(Collection $menus, int $pid = 0)
{
$collection = new Collection();
$menus->each(function ($item, $key) use ($pid, $menus, $collection){
if ($item->pid == $pid) {
$collection[$key] = $item;
$collection[$key][$item->id] = $this->tree($menus, $item->id);
}
});
return $collection;
}
/**
* 顺序结构
*
* @time at 2018年11月13日
* @param $menu
* @return Collection
*/
public function sort(Collection $menus, int $pid = 0, int $level = 0)
{
$collection = [];
foreach ($menus as $menu) {
if ($menu->pid == $pid) {
$menu->level = $level;
$collection[] = $menu;
$collection = array_merge($collection, $this->sort($menus, $menu->id, $level+1));
}
}
return $collection;
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/16 0016
* Time: 上午 11:01
*/
namespace app\service;
use think\paginator\driver\Bootstrap;
use think\Collection;
class PaginateService extends Bootstrap
{
/**
* 渲染分页html
* @return mixed
*/
public function render()
{
if ($this->hasPages()) {
if ($this->simple) {
return sprintf(
'<ul class="pager">%s %s</ul>',
$this->getPreviousButton(),
$this->getNextButton()
);
} else {
return sprintf(
'<ul class="pagination">%s %s %s %s</ul>',
$this->getPreviousButton(),
$this->getLinks(),
$this->getNextButton(),
$this->changeLimit()
);
}
}
}
protected function changeLimit()
{
$query = $this->options['query'];
$html = '&nbsp;<li class="project_page">';
$pageLimit = config('admin.page_limit');
$html .= '<select class="page-form-control limit" name="limit">';
foreach ($pageLimit as $limit) {
if (isset($query['limit']) && $query['limit'] == $limit) {
$html .= sprintf('<option value="%s" selected>%s条/页</option>', $limit, $limit);
} else {
$html .= sprintf('<option value="%s">%s条/页</option>', $limit, $limit);
}
}
$html .= '</select></li>&nbsp;<li>';
$html .= sprintf('<input name="page" class="page-form-control-input" value="%s"> 页 ', $query['page'] ?? 1);
$html .='</li>';
$html .= '<li><button class="btn btn-primary btn-xs hrefTo"><i class="fa fa-location-arrow"></i> 跳转</button></li>';
return $html;
}
}

28
application/tags.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用行为扩展定义文件
return [
// 应用初始化
'app_init' => [],
// 应用开始
'app_begin' => [],
// 模块初始化
'module_init' => [],
// 操作开始执行
'action_begin' => [],
// 视图内容过滤
'view_filter' => [],
// 日志写入
'log_write' => [],
// 应用结束
'app_end' => [],
];

174
application/traits/Auth.php Normal file
View File

@@ -0,0 +1,174 @@
<?php
namespace app\traits;
use think\Request;
use think\Validate;
use think\facade\Session;
use think\facade\Cookie;
use app\model\UserModel as User;
use app\behavior\LoginRecord;
trait Auth
{
public function authLogin(Request $request)
{
$err = $this->validateLogin($request);
if ($err) {
$this->error($err);
}
// 正常输入登录
$userModel = new User();
$field = explode('|', $this->name());
$user = $userModel::where($field[0], $request->param($field[0]))->find();
if (!$user) {
$this->error('登录失败');
}
if (password_verify($request->param('password'), $user->password)) {
Session::set('user', $user);
# 记住登录
$this->LoginRemember($user, $request);
# 登录记录
hook(LoginRecord::class, ['user' => $user]);
$this->success('登录成功', url($this->redirect));
}
$this->error('登录失败');
}
/**
* 记住登录
* @return bool
*/
public function rememberLogin()
{
// 如果记住登录
if (!Session::get('user') && Cookie::get('remember_token') && $this->checkRememberToken()) {
return true;
}
return false;
}
/**
* 退出
* @return void
*/
public function authLogout()
{
$user = Session::get('user');
$user->remember_token = null;
$user->save();
Cookie::delete('remember_token');
Session::delete('user');
}
/**
* 验证
* @param Request $request
* @return array|bool
*/
protected function validateLogin(Request $request)
{
$validate = new Validate($this->rule());
if (!$validate->check($request->except(['remember']))) {
return $validate->getError();
}
return false;
}
/**
* 登录验证规则
* @return array
*/
protected function rule()
{
return [
$this->name() => 'require|token|alphaDash',
'password|密码' => 'require|alphaDash',
'captcha|验证码' => 'require|captcha'
];
}
/**
* 设置登录字段
*
* @return string
*/
protected function name()
{
return 'name|用户名';
}
/**
* Remember Token
*
* @return string
*/
public function generateRememberToken()
{
return uniqid(md5(time()+rand(10000, 99999)));
}
/**
* 加密 TOKEN
*
* @param $user_id
* @param $remember_token
* @return string
*/
protected function secretRememberToken($user_id, $remember_token)
{
list($key, $method, $iv) = $this->getSecret();
return base64_encode(openssl_encrypt($user_id . ':' . $remember_token, $method, $key, OPENSSL_RAW_DATA, $iv));
}
/**
* 检查remember token 是否正确
*
* @return bool
*/
protected function checkRememberToken()
{
if (!Cookie::has('remember_token')) {
return false;
}
$rememberToken = Cookie::get('remember_token');
// 解密
list($key, $method, $iv) = $this->getSecret();
list($userID) = explode(':', (openssl_decrypt(base64_decode($rememberToken), $method, $key, OPENSSL_RAW_DATA, $iv)));
// 校验
$user = (new User())->findBy($userID);
Session::set('user', $user);
return $user->remember_token == $rememberToken;
}
/**
* 加密
*
* @return array
*/
protected function getSecret()
{
return ['admin_auth', 'AES-128-CBC', '1234567890123412'];
}
/**
* 记住
*
* @param $user
* @return void
*/
protected function LoginRemember($user, Request $request)
{
if ($request->has('remember')) {
$rememberToken = $this->secretRememberToken($user->id, $this->generateRememberToken());
$user->remember_token = $rememberToken;
Cookie::forever('remember_token', $rememberToken);
}
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/12 0012
* Time: 上午 11:43
*/
namespace app\traits;
use think\facade\Session;
use app\component\upload\UploadInterface;
use app\component\upload\LocalUpload;
trait ControllerTrait
{
protected $vars = [];
/**
* 绑定实现
*
* @time at 2018年11月16日
* @return void
*/
public function initialize()
{
bind(UploadInterface::class, LocalUpload::class);
}
/**
* 是否登录
*
* @time at 2018年11月15日
* @return bool
*/
protected function isLogin()
{
return $this->getLoginUser() ? true : false;
}
/**
* 获取登录用户
*
* @time at 2018年11月15日
* @return mixed
*/
protected function getLoginUser()
{
return Session::get('user');
}
/**
* fetch 重写
*
* @time at 2018年11月15日
* @param string $template
* @param array $vars
* @param array $config
* @return mixed
*/
protected function fetch($template = '', $vars = [], $config = [])
{
$vars = array_merge($this->vars, $vars);
return $this->view->fetch($template, $vars, $config);
}
/**
* Set Template Vars
*
* @time at 2018年11月12日
* @param $name
* @param $value
* @return void
*/
public function __set($name, $value)
{
// TODO: Implement __set() method.
$this->vars[$name] = $value;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/12 0012
* Time: 下午 16:31
*/
namespace app\validates;
use think\Validate;
abstract class AbstractValidate extends Validate
{
/**
* Get Validate Errors
*
* @time at 2018年11月12日
* @param $data
* @return array
*/
public function getErrors($data)
{
$this->check($data);
return $this->getError();
}
}

View File

@@ -0,0 +1,19 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/14 0014
* Time: 下午 18:21
*/
namespace app\validates;
class PermissionValidate extends AbstractValidate
{
protected $rule = [
'name|菜单名称' => 'require|min:2|max:10|chs|unique:permissions',
'module|模块名称' => 'require|min:2|max:10|alpha',
'controller|控制器名称' => 'require|min:2|max:50|alpha',
'action|方法名称' => 'require|min:2|max:50|alpha',
];
}

View File

@@ -0,0 +1,15 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/14 0014
* Time: 下午 17:42
*/
namespace app\validates;
class RoleValidate extends AbstractValidate
{
protected $rule = [
'name|角色名' => 'require|min:3|max:15|chs|unique:roles',
];
}

View File

@@ -0,0 +1,18 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/12 0012
* Time: 下午 16:38
*/
namespace app\validates;
class UserValidate extends AbstractValidate
{
protected $rule = [
'name|用户名' => 'require|min:3|max:15|alphaNum|unique:users',
'email|邮箱' => 'email|unique:users',
'password|密码' => 'confirm|min:6|max:20|alphaDash',
];
}