ayHaru 4 gadi atpakaļ
vecāks
revīzija
f2562d7cab

+ 137 - 0
application/common.php

@@ -20,6 +20,30 @@ function pre($content, $is_die = true)
 }
 
 /**
+ * 异常处理函数
+ * @param string $code
+ * @param string $msg
+ */
+function json_error_exception($code = '', $msg = '')
+{
+    $error = config('errorCode.');
+    $errorCode = isset($error[$code]) ? $code : 10000;
+    $errorMsg = $msg != '' ? (isset($error[$code]) ? $error[$code] . " :" . $msg : $msg) : (isset($error[$code]) ? $error[$code] : "请求错误");
+    return array('code' => $errorCode, 'msg' => $errorMsg);
+}
+
+/**
+ * 成功Json返回函数
+ * @param string $code
+ * @param array  $data
+ * @param string $msg
+ */
+function json_return($code,$data=[],$msg='')
+{
+    exit(json_encode(['code'=>$code,'data'=>$data,'msg'=>$msg],JSON_UNESCAPED_UNICODE ));
+}
+
+/**
  * php发送http请求
  * @param array $params 相关请求参数
  * @param booble $is_json  数据格式,默认false为数组,true为json
@@ -88,4 +112,117 @@ function _curl(array $params,$is_json=false )
     curl_close($ch);
 
     return $result;
+}
+
+/**
+ * 整理菜单住方法
+ * @param $param
+ * @return array
+ */
+function prepareMenu($param)
+{
+    $param = objToArray($param);
+    $parent = []; //父类
+    $child = [];  //子类
+
+    foreach($param as $key=>$vo){
+
+        if(0 == $vo['type_id']){
+            $vo['href'] = '#';
+            $parent[] = $vo;
+        }else{
+            $vo['href'] = url($vo['control_name'] .'/'. $vo['action_name']); //跳转地址
+            $child[] = $vo;
+        }
+    }
+
+    foreach($parent as $key=>$vo){
+        foreach($child as $k=>$v){
+
+            if($v['type_id'] == $vo['id']){
+                $parent[$key]['child'][] = $v;
+            }
+        }
+    }
+    unset($child);
+
+    return $parent;
+}
+
+/**
+ * 统一返回信息
+ * @param $code
+ * @param $data
+ * @param $msge
+ */
+function msg($code, $data, $msg)
+{
+    return compact('code', 'data', 'msg');
+}
+
+/**
+ * 整理出tree数据 ---  layui tree
+ * @param $pInfo
+ * @param $spread
+ */
+function getTree($pInfo, $spread = true)
+{
+
+    $res = [];
+    $tree = [];
+    //整理数组
+    foreach($pInfo as $key=>$vo){
+
+        if($spread){
+            $vo['spread'] = true;  //默认展开
+        }
+        $res[$vo['id']] = $vo;
+        $res[$vo['id']]['children'] = [];
+    }
+    unset($pInfo);
+
+    //查找子孙
+    foreach($res as $key=>$vo){
+        if(0 != $vo['pid']){
+            $res[$vo['pid']]['children'][] = &$res[$key];
+        }
+    }
+
+    //过滤杂质
+    foreach( $res as $key=>$vo ){
+        if(0 == $vo['pid']){
+            $tree[] = $vo;
+        }
+    }
+    unset( $res );
+
+    return $tree;
+}
+
+/**
+ * 对象转换成数组
+ * @param $obj
+ */
+function objToArray($obj)
+{
+    return json_decode(json_encode($obj), true);
+}
+
+
+/**
+ * 权限检测
+ * @param $rule
+ */
+function authCheck($rule)
+{
+    $control = explode('/', $rule)['0'];
+    if(in_array($control, ['login', 'index'])){
+        return true;
+    }
+
+    if(in_array($rule, cache(session('role_id')))){
+        return true;
+    }
+
+    return false;
 }

+ 5 - 0
application/index/config.php

@@ -0,0 +1,5 @@
+<?php
+
+return [
+    'user_status'  => ['1' => '已启用' , '2' => '已停用']
+];

+ 47 - 0
application/index/controller/Base.php

@@ -0,0 +1,47 @@
+<?php
+namespace app\index\controller;
+
+use think\Controller;
+use app\index\model\RoleModel;
+
+class Base extends Controller{
+
+    public function _initialize(){
+        if(empty(session('username')) || empty(session('id'))){
+            //登录超时
+            return json(json_error_exception('1005'));
+        }
+        $this->cacheCheck();
+        // 检测权限
+        $control = lcfirst(request()->controller());
+        $action = lcfirst(request()->action());
+
+        if(empty(authCheck($control . '/' . $action))){
+
+            return json(json_error_exception('1000'));
+        }
+
+    }
+
+    private function cacheCheck()
+    {
+        $action = cache(session('role_id'));
+
+        if(is_null($action) || empty($action)){
+            // 获取该管理员的角色信息
+            $roleModel = new RoleModel();
+            $info = $roleModel->getRoleInfo(session('role_id'));
+            cache(session('role_id'), $info['action']);
+        }
+    }
+
+    protected function removRoleCache()
+    {
+        $roleModel = new RoleModel();
+        $roleList = $roleModel->getRole();
+
+        foreach ($roleList as $value) {
+            cache($value['id'], null);
+        }
+    }
+}

+ 4 - 22
application/index/controller/Btoc.php

@@ -1,36 +1,18 @@
 <?php
 namespace app\index\controller;
 
+use think\App;
 use think\Controller;
 
 class Btoc extends Controller
 {
     public function index()
     {
-        $post['name'] = 'ayy';
+        $post['id'] = 1;
         $data['url'] = 'http://hm.hemadj.com/dev/test';
         $data['method'] = 'post';
         $data['data'] =  $post;
-
-        _curl($data);
-        $result = $this->xtox('btoc');
-    }
-
-    public function xtox($listname){
-        $redis = new \Redis();
-        $redis->connect('39.97.239.116', 6379);
-        $redis->auth('huaxiashangmeng');
-        $redis->select(1);
-        while(true){
-            try{
-                $value = $redis->BRPOP($listname,0);
-                if(!$value){
-                    break;
-                }
-                return $value;
-            }catch(Exception $e){
-                return $e->getMessage();
-            }
-        }
+        $result = _curl($data);
+        pre($result);
     }
 }

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 8 - 6
application/index/controller/Index.php


+ 66 - 0
application/index/controller/Login.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace app\index\controller;
+
+use think\Controller;
+use app\index\model\UserModel;
+
+class Login extends Controller{
+    /**
+     * 管理员登录
+     * */
+    public function login(){
+        $username = input('post.username');
+        $password = input('post.password');
+
+        $UserModel = new UserModel();
+        $hasUser = $UserModel->checkUser($username,$password);
+        if(empty($hasUser)){
+            //管理员不存在
+            return json(json_error_exception('1001'));
+        }
+        if($hasUser['status'] != 1){
+            //管理员已禁用
+            return json(json_error_exception('1002'));
+        }
+        if($hasUser['password'] != md5($password)){
+            //密码错误
+            return json(json_error_exception('1003'));
+        }
+        // 更新管理员状态
+        $param = [
+            'last_login_ip' => request()->ip(),
+            'last_login_time' => date()
+        ];
+
+        $res = $UserModel->updateStatus($param, $hasUser['id']);
+        if(1 != $res['code']){
+            //更新失败
+            return json(json_error_exception('1004'));
+        }
+        session('username', $hasUser['user_name']);
+        session('id', $hasUser['id']);
+        session('role', $hasUser['role_name']);
+        session('role_id', $hasUser['role_id']);
+        session('rules', $hasUser['rules']);
+
+        json_return(200,[],'success');
+    }
+    /**
+     * 管理员退出
+     */
+    public function login_out(){
+        session('username', null);
+        session('id', null);
+        session('role', null);
+        session('role_id', null);
+        session('rule', null);
+        json_return(200,[],'success');
+    }
+
+    public function test(){
+        $UserModel = new UserModel();
+        $aa = $UserModel->ttt();
+        pre($aa);
+    }
+}

+ 48 - 0
application/index/controller/Node.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace app\index\controller;
+
+use app\index\controller\Base;
+use app\index\model\NodeModel;
+
+class Node extends Base{
+
+    // 节点列表
+    public function nodeList()
+    {
+        $node = new NodeModel();
+        $nodes = $node->getNodeList();
+
+        $nodes = getTree(objToArray($nodes), false);
+        json_return(200 , $nodes , 'success');
+    }
+
+    // 添加节点
+    public function nodeAdd()
+    {
+        $param = input('post.');
+
+        $node = new NodeModel();
+        $flag = $node->insertNode($param);
+        if($flag['code'] != 1){
+            return json(json_error_exception('1006',$flag['msg']));
+        }
+        $this->removRoleCache();
+        json_return(200,[],'success');
+    }
+
+    // 删除节点
+    public function nodeDel()
+    {
+        $id = input('param.id');
+
+        $role = new NodeModel();
+        $flag = $role->delNode($id);
+        if($flag['code'] != 1){
+            return json(json_error_exception('1006',$flag['msg']));
+        }
+        $this->removRoleCache();
+        json_return(200,[],'success');
+    }
+
+}

+ 58 - 0
application/index/controller/Role.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace app\index\controller;
+
+use app\index\controller\Base;
+use app\index\model\RoleModel;
+class Role extends Base{
+
+    // 角色列表
+    public function roleList()
+    {
+        $param = input('param.');
+
+        $limit = isset($param['pageSize']) ? $param['pageSize'] : 10;
+        $param['pageNumber'] = isset($param['pageNumber']) ? $param['pageNumber'] : 1;
+        $offset = ($param['pageNumber'] - 1) * $limit;
+
+        $where = [];
+        if (!empty($param['searchText'])) {
+            $where['role_name'] = ['like', '%' . $param['searchText'] . '%'];
+        }
+
+        $user = new RoleModel();
+        $selectResult = $user->getRoleByWhere($where, $offset, $limit);
+
+        $return['total'] = $user->getAllRole($where);  // 总数据
+        $return['rows'] = $selectResult;
+
+        json_return(200 , $return , 'success');
+    }
+
+    // 添加角色
+    public function roleAdd()
+    {
+        $param = input('post.');
+
+        $role = new RoleModel();
+        $flag = $role->insertRole($param);
+        if($flag['code'] != 1){
+            return json(json_error_exception('1006',$flag['msg']));
+        }
+        json_return(200,[],'success');
+    }
+
+    // 删除角色
+    public function roleDel()
+    {
+        $id = input('param.id');
+
+        $role = new RoleModel();
+        $flag = $role->delRole($id);
+        if($flag['code'] != 1){
+            return json(json_error_exception('1006',$flag['msg']));
+        }
+        $this->removRoleCache();
+        json_return(200,[],'success');
+    }
+}

+ 65 - 0
application/index/controller/User.php

@@ -0,0 +1,65 @@
+<?php
+
+namespace app\index\controller;
+
+use app\index\controller\Base;
+use app\index\model\UserModel;
+
+class User extends Base{
+
+    //用户列表
+    public function userList()
+    {
+        $param = input('param.');
+
+        $limit = isset($param['pageSize']) ? $param['pageSize'] : 10;
+        $param['pageNumber'] = isset($param['pageNumber']) ? $param['pageNumber'] : 1;
+        $offset = ($param['pageNumber'] - 1) * $limit;
+
+        $where = [];
+        if (!empty($param['searchText'])) {
+            $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
+        }
+        $user = new UserModel();
+        $selectResult = $user->getUsersByWhere($where, $offset, $limit);
+
+        $status = config('user_status');
+
+        // 拼装参数
+        foreach($selectResult as $key=>$vo){
+            $selectResult[$key]['status'] = $status[$vo['status']];
+        }
+
+        $return['total'] = $user->getAllUsers($where);  //总数据
+        $return['rows'] = $selectResult;
+        json_return(200 , $return , 'success');
+    }
+
+    // 添加用户
+    public function userAdd()
+    {
+        $param = input('post.');
+
+        $param['password'] = md5($param['password']);
+
+        $user = new UserModel();
+        $flag = $user->insertUser($param);
+        if($flag['code'] != 1){
+            return json(json_error_exception('1006',$flag['msg']));
+        }
+        json_return(200,[],'success');
+    }
+
+    // 删除用户
+    public function userDel()
+    {
+        $id = input('param.id');
+
+        $role = new UserModel();
+        $flag = $role->delUser($id);
+        if($flag['code'] != 1){
+            return json(json_error_exception('1006',$flag['msg']));
+        }
+        json_return(200,[],'success');
+    }
+}

+ 26 - 0
application/index/controller/daemon.php

@@ -0,0 +1,26 @@
+<?php
+
+class Daemon{
+
+    protected $handler = null;
+
+    public function init(){
+        $this->handler = new \Redis();
+        $this->handler->connect('39.97.239.116', 6379);
+        $this->handler->auth('huaxiashangmeng');
+        $this->handler->select(1);
+    }
+
+    public function btoc($listname){
+        $result = $this->handler->BRPOP($listname,0);
+        if($result){
+
+        }
+    }
+}
+
+$daemon = new Daemon();
+$daemon->init();
+while (true){
+
+}

+ 79 - 0
application/index/model/NodeModel.php

@@ -0,0 +1,79 @@
+<?php
+
+namespace app\index\model;
+
+use think\Model;
+
+class NodeModel extends Model{
+    // 确定链接表名
+    protected $name = 'node';
+
+    /**
+     * 根据条件获取访问权限节点数据
+     * @param $where
+     */
+    public function getActions($where)
+    {
+        return $this->field('control_name,action_name')->where($where)->select();
+    }
+
+    /**
+     * 根据节点数据获取对应的菜单
+     * @param $nodeStr
+     */
+    public function getMenu($nodeStr = '')
+    {
+        if(empty($nodeStr)){
+            return [];
+        }
+        // 超级管理员没有节点数组 * 号表示
+        $where = '*' == $nodeStr ? 'is_menu = 2' : 'is_menu = 2 and id in(' . $nodeStr . ')';
+
+        $result = $this->field('id,node_name,type_id,control_name,action_name,style')
+            ->where($where)->select();
+        $menu = prepareMenu($result);
+
+        return $menu;
+    }
+
+    /**
+     * 获取节点数据
+     * @return mixed
+     */
+    public function getNodeList()
+    {
+        return $this->field('id,node_name name,type_id pid,is_menu,style,control_name,action_name')->select();
+    }
+
+    /**
+     * 插入节点信息
+     * @param $param
+     */
+    public function insertNode($param)
+    {
+        try{
+
+            $this->save($param);
+            return msg(1, '', '添加节点成功');
+        }catch(PDOException $e){
+
+            return msg(-2, '', $e->getMessage());
+        }
+    }
+
+    /**
+     * 删除节点
+     * @param $id
+     */
+    public function delNode($id)
+    {
+        try{
+
+            $this->where('id', $id)->delete();
+            return msg(1, '', '删除节点成功');
+
+        }catch(PDOException $e){
+            return msg(-1, '', $e->getMessage());
+        }
+    }
+}

+ 107 - 0
application/index/model/RoleModel.php

@@ -0,0 +1,107 @@
+<?php
+
+namespace app\index\model;
+
+use think\Model;
+use app\index\model\NodeModel;
+
+class RoleModel extends Model{
+    // 确定链接表名
+    protected $name = 'role';
+
+    /**
+     * 获取角色信息
+     * @param $id
+     */
+    public function getRoleInfo($id)
+    {
+        $result = $this->where('id', $id)->find()->toArray();
+        // 超级管理员权限是 *
+        if(empty($result['rule'])){
+            $result['action'] = '';
+            return $result;
+        }else if('*' == $result['rule']){
+            $where = '';
+        }else{
+            $where = 'id in(' . $result['rule'] . ')';
+        }
+
+        // 查询权限节点
+        $nodeModel = new NodeModel();
+        $res = $nodeModel->getActions($where);
+
+        foreach($res as $key=>$vo){
+
+            if('#' != $vo['action_name']){
+                $result['action'][] = $vo['control_name'] . '/' . $vo['action_name'];
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * 根据搜索条件获取角色列表信息
+     * @param $where
+     * @param $offset
+     * @param $limit
+     */
+    public function getRoleByWhere($where, $offset, $limit)
+    {
+
+        return $this->where($where)->limit($offset, $limit)->order('id desc')->select();
+    }
+
+    /**
+     * 根据搜索条件获取所有的角色数量
+     * @param $where
+     */
+    public function getAllRole($where)
+    {
+        return $this->where($where)->count();
+    }
+
+    /**
+     * 插入角色信息
+     * @param $param
+     */
+    public function insertRole($param)
+    {
+        try{
+
+            $result =  $this->validate('RoleValidate')->save($param);
+            if(false === $result){
+                // 验证失败 输出错误信息
+                return msg(-1, '', $this->getError());
+            }else{
+
+                return msg(1, url('role/index'), '添加角色成功');
+            }
+        }catch(PDOException $e){
+
+            return msg(-2, '', $e->getMessage());
+        }
+    }
+
+    /**
+     * 删除角色
+     * @param $id
+     */
+    public function delRole($id)
+    {
+        try{
+
+            $this->where('id', $id)->delete();
+            return msg(1, '', '删除角色成功');
+
+        }catch(PDOException $e){
+            return msg(-1, '', $e->getMessage());
+        }
+    }
+
+    // 获取所有的角色信息
+    public function getRole()
+    {
+        return $this->select();
+    }
+}

+ 93 - 0
application/index/model/UserModel.php

@@ -0,0 +1,93 @@
+<?php
+
+namespace app\index\model;
+
+use think\Model;
+
+class UserModel extends Model{
+    // 确定链接表名
+    protected $name = 'user';
+
+    /**
+     * 根据用户名检测用户数据
+     * @param $userName
+     */
+    public function checkUser($userName,$password)
+    {
+        return $this->alias('u')
+            ->field('u.id,u.user_name,r.role_name,u.role_id,r.rules,u.password,u.status')
+            ->join('role r', 'u.role_id = r.id')
+            ->where('u.user_name', $userName)
+            ->find();
+    }
+
+    /**
+     * 根据搜索条件获取用户列表信息
+     * @param $where
+     * @param $offset
+     * @param $limit
+     */
+    public function getUsersByWhere($where, $offset, $limit)
+    {
+        return $this->alias('user')->field( 'user.*,role_name')
+            ->join('role rol', 'user.role_id = ' . 'rol.id')
+            ->where($where)->limit($offset, $limit)->order('id desc')->select();
+    }
+
+    /**
+     * 根据搜索条件获取所有的用户数量
+     * @param $where
+     */
+    public function getAllUsers($where)
+    {
+        return $this->where($where)->count();
+    }
+
+    /**
+     * 更新管理员状态
+     * @param array $param
+     */
+    public function updateStatus($param = [], $uid)
+    {
+        try{
+            $this->where('id', $uid)->update($param);
+            return msg(1, '', 'ok');
+        }catch (\Exception $e){
+            return msg(-1, '', $e->getMessage());
+        }
+    }
+
+    /**
+     * 插入管理员信息
+     * @param $param
+     */
+    public function insertUser($param)
+    {
+        try{
+            $result =  $this->validate('UserValidate')->save($param);
+            if(false === $result){
+                // 验证失败 输出错误信息
+                return msg(-1, '', $this->getError());
+            }else{
+                return msg(1, '', '添加用户成功');
+            }
+        }catch(PDOException $e){
+            return msg(-2, '', $e->getMessage());
+        }
+    }
+
+    /**
+     * 删除管理员
+     * @param $id
+     */
+    public function delUser($id)
+    {
+        try{
+            $this->where('id', $id)->delete();
+            return msg(1, '', '删除管理员成功');
+
+        }catch( PDOException $e){
+            return msg(-1, '', $e->getMessage());
+        }
+    }
+}

+ 21 - 0
application/index/validate/RoleValidate.php

@@ -0,0 +1,21 @@
+<?php
+// +----------------------------------------------------------------------
+// | snake
+// +----------------------------------------------------------------------
+// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: NickBai <1902822973@qq.com>
+// +----------------------------------------------------------------------
+namespace app\admin\validate;
+
+use think\Validate;
+
+class RoleValidate extends Validate
+{
+    protected $rule = [
+        ['role_name', 'unique:role', '角色已经存在']
+    ];
+
+}

+ 21 - 0
application/index/validate/UserValidate.php

@@ -0,0 +1,21 @@
+<?php
+// +----------------------------------------------------------------------
+// | snake
+// +----------------------------------------------------------------------
+// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: NickBai <1902822973@qq.com>
+// +----------------------------------------------------------------------
+namespace app\index\validate;
+
+use think\Validate;
+
+class UserValidate extends Validate
+{
+    protected $rule = [
+        ['user_name', 'unique:user', '管理员已经存在']
+    ];
+
+}

+ 1 - 1
config/database.php

@@ -29,7 +29,7 @@ return [
     // 数据库编码默认采用utf8
     'charset'         => 'utf8',
     // 数据库表前缀
-    'prefix'          => '',
+    'prefix'          => 'sc_',
     // 数据库调试模式
     'debug'           => true,
     // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)

+ 15 - 0
config/errorCode.php

@@ -0,0 +1,15 @@
+<?php
+
+/*
+ *自定义错误码返回信息
+ * */
+return [
+    '10000' =>  '内部错误',
+    '1000'  =>  '没有权限',
+    '1001'  =>  '管理员不存在',
+    '1002'  =>  '管理员已禁用',
+    '1003'  =>  '密码有误',
+    '1004'  =>  '登录信息同步错误',
+    '1005'  =>  '登录超时',
+    '1006'  =>  '操作失败',
+];

+ 1 - 1
public/index.php

@@ -18,4 +18,4 @@ require __DIR__ . '/../thinkphp/base.php';
 // 支持事先使用静态方法设置Request对象和Config对象
 
 // 执行应用并响应
-Container::get('app')->run()->send();
+Container::get('app')->run()->send();

+ 1 - 0
route/route.php

@@ -16,4 +16,5 @@ Route::get('think', function () {
 Route::get('hello/:name', 'index/hello');
 
 return [
+
 ];

+ 11 - 0
tests/LoginTest.php

@@ -0,0 +1,11 @@
+<?php
+
+namespace tests;
+
+use PHPUnit\Framework\TestCase;
+
+class LoginTest extends TestCase
+{
+
+
+}