Sfoglia il codice sorgente

商户用户管理、角色管理

aiden 4 mesi fa
parent
commit
7465639da8

+ 52 - 1
app/common.php

@@ -1,2 +1,53 @@
 <?php
-// 应用公共文件
+
+use Firebase\JWT\JWT;
+
+/// 加密密钥
+$GLOBALS['token_key_secret'] = "z.1i8L?Ld+ovuA4r%4YZrz?w1Y%-NYvlrJ=TqV$[W[5=B#C[=l2gHV8gJ,DhZc";
+/// COOKIE 有效期
+$GLOBALS['cookieExpire'] = 60 * 60 * 24 * 7;
+
+/**
+ * 响应成功json
+ */
+if(!function_exists('json_success')){
+    function json_success($data = [], $message = ""){
+        return json([
+            'state' => 1,
+            'data' => $data,
+            'message' => $message ?? ""
+        ]);
+    }
+}
+
+/**
+ * 响应失败json
+ */
+if(!function_exists('json_error')){
+    function json_error($data = [], $message = "", $code = 1){
+        return json([
+            'state' => 0,
+            'code' => $code,
+            'data' => $data,
+            'message' => $message ?? ""
+        ]);
+    }
+}
+
+/**
+ * 加密登录数据
+ *
+ * @param string $data 待加密数据
+ * @param string $key 加密密钥
+ * @return string
+ */
+if(!function_exists('generateToken')){
+    function generateToken($data = [], $expire = 0){
+        $payload = [
+            'exp' => time() + ($expire > 0 ? $expire : $GLOBALS['cookieExpire']), // 24小时有效期
+        ];
+        $payload = array_merge($payload, $data);
+        $token = JWT::encode($payload, $GLOBALS['token_key_secret'], 'HS256');
+        return $token;
+    }
+}

+ 418 - 0
app/controller/User.php

@@ -0,0 +1,418 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\controller;
+
+use app\BaseController;
+use think\facade\Cookie;
+use think\facade\Request;
+use think\facade\Config;
+use app\model\UserModel;
+use app\model\UserRoleModel;
+use app\validate\UserValidate;
+
+class User extends BaseController
+{
+    protected $message = [
+        'logout' => '退出成功',
+        'login' => '登录成功',
+        'error' => '账号或密码错误',
+        'param' => '参数错误',
+        'duplicate' => '用户账号已存在',
+        'create_suc' => '创建用户成功',
+        'empty' => '用户不存在',
+        'suc' => '操作成功',
+        'res' => '获取成功'
+    ];
+
+    /**
+     * 登录
+     */
+    public function login()
+    {
+        // 获取输入数据
+        $userName = trim(Request::post('user_name'));
+        $password = trim(Request::post('password'));
+
+        // 验证输入数据
+        $checkMessage = $this->validateInput([
+            'user_name' => $userName,
+            'password' => $password,
+        ], 'login');
+
+        if(!empty($checkMessage)) {
+            return json_error([], $checkMessage);
+        }
+
+        // 查询用户
+        $user = UserModel::where('user_name', $userName)->find();
+        if ($user && password_verify($password, $user->password)) {
+
+            $token = generateToken([
+                'user_id' => $user->user_id,
+                'merchant_id' => $user->merchant_id,
+                'user_role' => $user->user_role
+            ]);
+            Cookie::set('auth_token', $token, ['expire' => $GLOBALS['cookieExpire'], 'httponly' => true]);
+            // 更新登录时间
+            $user->login_time = time();
+            $user->save();
+
+            return json_success([
+                'user_name' => $user->user_name,
+                'nick_name' => $user->nick_name,
+                'user_role' => $user->user_role,
+                'login_time' => $user->login_time,
+                'token' => $token
+            ], $this->message['login']);
+        } else {
+            return json_error([], $this->message['error']);
+        }
+    }
+    
+    /**
+     * 用户注销
+     */
+    public function logout()
+    {
+        Cookie::delete('auth_token');
+        return json_success([], '退出成功');
+    }
+
+    /**
+     * 创建用户
+     */
+    public function createUser()
+    {
+        // 获取当前登录用户信息
+        $loginInfo = $this->checkUserLogin();
+        if (!$loginInfo) {
+            return json_error([], '请先登录');
+        }
+        
+        // 检查是否有创建用户权限
+        if (!$this->checkPermission($loginInfo, 'user', 'create')) {
+            return json_error([], '没有创建用户的权限');
+        }
+
+        // 获取输入数据
+        $data = Request::only([
+            'user_name', 'nick_name', 'password', 'phone', 
+            'user_role', 'white_list_ip'
+        ]);
+        $data['merchant_id'] = $loginInfo['merchant_id'];
+
+        try {
+            // 验证数据
+            $this->validate($data, UserValidate::class . '.create');
+        } catch (\think\exception\ValidateException $e) {
+            return json_error($e->getError());
+        }
+        
+        // 验证角色是否存在
+        if ($data['user_role'] > 0) {
+            $role = UserRoleModel::getRoleById($data['user_role'], $loginInfo['merchant_id']);
+            if (!$role) {
+                return json_error([], '选择的角色不存在');
+            }
+        }
+
+        // 检查用户名是否已存在
+        if (UserModel::where('user_name', $data['user_name'])->find()) {
+            return json_error($this->message['duplicate']);
+        }
+        
+        // 创建新用户
+        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
+        
+        try {
+            $user = UserModel::create($data);
+            return json_success(['user_id' => $user->user_id], $this->message['create_suc']);
+        } catch (\Exception $e) {
+            return json_error([], '创建用户失败:' . $e->getMessage());
+        }
+    }
+    
+    /**
+     * 获取用户列表
+     */
+    public function list()
+    {
+        $loginInfo = $this->checkUserLogin();
+        if (!$loginInfo) {
+            return json_error([], '请先登录');
+        }
+        
+        if (!$this->checkPermission($loginInfo, 'user', 'list')) {
+            return json_error([], '没有查看用户列表的权限');
+        }
+        
+        $page = Request::get('page', 1, 'intval');
+        $limit = Request::get('limit', 10, 'intval');
+        $userName = Request::get('user_name', '', 'trim');
+        $nickName = Request::get('nick_name', '', 'trim');
+        $userRole = Request::get('user_role', 0, 'intval');
+        
+        $where = [
+            ['merchant_id', '=', $loginInfo['merchant_id']]
+        ];
+        
+        if ($userName) {
+            $where[] = ['user_name', 'like', '%' . $userName . '%'];
+        }
+        
+        if ($nickName) {
+            $where[] = ['nick_name', 'like', '%' . $nickName . '%'];
+        }
+        
+        if ($userRole > 0) {
+            $where[] = ['user_role', '=', $userRole];
+        }
+        
+        $total = UserModel::where($where)->count();
+        $list = UserModel::where($where)
+            ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
+            ->order('user_id', 'desc')
+            ->page($page, $limit)
+            ->select();
+            
+        // 获取角色信息
+        $roleIds = array_unique(array_column($list->toArray(), 'user_role'));
+        $roles = [];
+        if ($roleIds) {
+            $roleList = UserRoleModel::whereIn('id', $roleIds)->select();
+            foreach ($roleList as $role) {
+                $roles[$role->id] = $role->role_name;
+            }
+        }
+        
+        // 添加角色名称
+        foreach ($list as $user) {
+            $user->role_name = $roles[$user->user_role] ?? '未分配角色';
+        }
+        
+        return json_success([
+            'list' => $list,
+            'total' => $total,
+            'page' => $page,
+            'limit' => $limit
+        ]);
+    }
+    
+    /**
+     * 获取用户详情
+     */
+    public function detail()
+    {
+        $loginInfo = $this->checkUserLogin();
+        if (!$loginInfo) {
+            return json_error([], '请先登录');
+        }
+        
+        if (!$this->checkPermission($loginInfo, 'user', 'detail')) {
+            return json_error([], '没有查看用户详情的权限');
+        }
+        
+        $userId = $this->request->param('user_id', 0, 'intval');
+        if (!$userId) {
+            return json_error([], '用户ID不能为空');
+        }
+        
+        $user = UserModel::where('user_id', $userId)
+            ->where('merchant_id', $loginInfo['merchant_id'])
+            ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
+            ->find();
+            
+        if (!$user) {
+            return json_error($this->message['empty']);
+        }
+        
+        // 获取角色信息
+        if ($user->user_role > 0) {
+            $role = UserRoleModel::getRoleById($user->user_role, $loginInfo['merchant_id']);
+            $user->role_name = $role ? $role->role_name : '未分配角色';
+            $user->role_privileges = $role ? $role->privileges : [];
+        } else {
+            $user->role_name = '未分配角色';
+            $user->role_privileges = [];
+        }
+        
+        return json_success($user);
+    }
+    
+    /**
+     * 更新用户
+     */
+    public function update()
+    {
+        $loginInfo = $this->checkUserLogin();
+        if (!$loginInfo) {
+            return json_error([], '请先登录');
+        }
+        
+        if (!$this->checkPermission($loginInfo, 'user', 'update')) {
+            return json_error([], '没有编辑用户的权限');
+        }
+        
+        $userId = $this->request->post('user_id', 0, 'intval');
+        if (!$userId) {
+            return json_error([], '用户ID不能为空');
+        }
+        
+        $user = UserModel::where('user_id', $userId)
+            ->where('merchant_id', $loginInfo['merchant_id'])
+            ->find();
+            
+        if (!$user) {
+            return json_error($this->message['empty']);
+        }
+        
+        // 获取更新数据
+        $data = $this->request->only([
+            'nick_name', 'phone', 'password', 'user_role', 'white_list_ip'
+        ]);
+        
+        // 过滤空值
+        $data = array_filter($data, function($value, $key) {
+            return $key !== 'password' || !empty($value);
+        }, ARRAY_FILTER_USE_BOTH);
+        
+        if (empty($data)) {
+            return json_error([], '没有要更新的数据');
+        }
+        
+        // 验证角色是否存在
+        if (isset($data['user_role']) && $data['user_role'] > 0) {
+            $role = UserRoleModel::getRoleById($data['user_role'], $loginInfo['merchant_id']);
+            if (!$role) {
+                return json_error([], '选择的角色不存在');
+            }
+        }
+        
+        // 密码加密
+        if (isset($data['password'])) {
+            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
+        }
+        
+        try {
+            $user->save($data);
+            return json_success([], $this->message['suc']);
+        } catch (\Exception $e) {
+            return json_error([], '更新失败:' . $e->getMessage());
+        }
+    }
+    
+    /**
+     * 删除用户
+     */
+    public function delete()
+    {
+        $loginInfo = $this->checkUserLogin();
+        if (!$loginInfo) {
+            return json_error([], '请先登录');
+        }
+        
+        if (!$this->checkPermission($loginInfo, 'user', 'delete')) {
+            return json_error([], '没有删除用户的权限');
+        }
+        
+        $userId = $this->request->post('user_id', 0, 'intval');
+        if (!$userId) {
+            return json_error([], '用户ID不能为空');
+        }
+        
+        if ($userId == $loginInfo['user_id']) {
+            return json_error([], '不能删除自己');
+        }
+        
+        $user = UserModel::where('user_id', $userId)
+            ->where('merchant_id', $loginInfo['merchant_id'])
+            ->find();
+            
+        if (!$user) {
+            return json_error($this->message['empty']);
+        }
+        
+        try {
+            $user->delete();
+            return json_success([], '删除成功');
+        } catch (\Exception $e) {
+            return json_error([], '删除失败:' . $e->getMessage());
+        }
+    }
+    
+    /**
+     * 获取当前登录用户信息
+     */
+    private function checkUserLogin()
+    {
+        $token = Cookie::get('auth_token');
+        if (!$token) {
+            return null;
+        }
+        
+        return $this->verifyToken($token);
+    }
+    
+    /**
+     * 验证Token
+     */
+    private function verifyToken($token)
+    {
+        try {
+            $parts = explode('.', $token);
+            if (count($parts) != 3) {
+                return null;
+            }
+            
+            $payload = json_decode(base64_decode($parts[1]), true);
+            
+            if ($payload['exp'] < time()) {
+                return null;
+            }
+            
+            return $payload;
+        } catch (\Exception $e) {
+            return null;
+        }
+    }
+    
+    /**
+     * 检查权限
+     */
+    private function checkPermission($user, $controller, $action)
+    {
+        // 超级管理员拥有所有权限
+        $superAdminRoleId = Config::get('permission.super_admin_role_id', 1);
+        if ($user['user_role'] == $superAdminRoleId) {
+            return true;
+        }
+        
+        // 获取用户角色权限
+        $role = UserRoleModel::getRoleById($user['user_role'], $user['merchant_id']);
+        if (!$role) {
+            return false;
+        }
+        
+        $privileges = $role->privileges;
+        
+        // 检查是否有对应权限
+        return isset($privileges[$controller]) && 
+               is_array($privileges[$controller]) && 
+               in_array($action, $privileges[$controller]);
+    }
+
+    /**
+     * 验证输入数据
+     */
+    protected function validateInput(array $data, $scene = '')
+    {
+        $validate = new UserValidate();
+
+        // 执行场景验证
+        if (!$validate->scene($scene)->check($data)) {
+            return $validate->getError();
+        }
+        return "";
+    }
+}

+ 204 - 0
app/controller/UserRole.php

@@ -0,0 +1,204 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\controller;
+
+use app\BaseController;
+use app\model\UserRoleModel;
+use app\model\UserModel;
+use think\facade\Config;
+use think\facade\Request;
+
+class UserRole extends BaseController
+{
+    /**
+     * 获取所有权限配置
+     */
+    public function getPermissions()
+    {
+        $permissions = Config::get('permission.permissions', []);
+        return json_success($permissions, '获取权限配置成功');
+    }
+    
+    /**
+     * 获取角色列表
+     */
+    public function list()
+    {
+        $merchantId = $this->getMerchantId();
+        $list = UserRoleModel::getRoleList($merchantId);
+        
+        return json_success([
+            'list' => $list,
+            'total' => count($list)
+        ]);
+    }
+    
+    /**
+     * 获取角色详情
+     */
+    public function detail()
+    {
+        $id = $this->request->param('id', 0, 'intval');
+        if (!$id) {
+            return json_error([], '角色ID不能为空');
+        }
+        
+        $merchantId = $this->getMerchantId();
+        
+        $role = UserRoleModel::getRoleById($id, $merchantId);
+        if (!$role) {
+            return json_error([], '角色不存在');
+        }
+        
+        return json_success($role);
+    }
+    
+    /**
+     * 创建角色
+     */
+    public function create()
+    {
+        $data = Request::only(['role_name', 'privileges']);
+        
+        if (empty($data['role_name'])) {
+            return json_error([], '角色名称不能为空');
+        }
+        
+        if (empty($data['privileges']) || !is_array($data['privileges'])) {
+            return json_error([], '权限配置不能为空');
+        }
+        
+        $merchantId = $this->getMerchantId();
+        
+        if (UserRoleModel::checkRoleExists($data['role_name'], $merchantId)) {
+            return json_error([], '角色名称已存在');
+        }
+        
+        $data['merchant_id'] = $merchantId;
+        
+        try {
+            $role = UserRoleModel::createRole($data);
+            return json_success(['id' => $role->id], '创建角色成功');
+        } catch (\Exception $e) {
+            return json_error([], '创建角色失败:' . $e->getMessage());
+        }
+    }
+    
+    /**
+     * 更新角色
+     */
+    public function update()
+    {
+        $id = Request::param('id', 0, 'intval');
+        if (!$id) {
+            return json_error([], '角色ID不能为空');
+        }
+        
+        $data = Request::only(['role_name', 'privileges']);
+        
+        if (empty($data['role_name'])) {
+            return json_error([], '角色名称不能为空');
+        }
+        
+        if (empty($data['privileges']) || !is_array($data['privileges'])) {
+            return json_error([], '权限配置不能为空');
+        }
+        
+        $merchantId = $this->getMerchantId();
+        
+        $role = UserRoleModel::getRoleById($id, $merchantId);
+        if (!$role) {
+            return json_error([], '角色不存在');
+        }
+        
+        if (UserRoleModel::checkRoleExists($data['role_name'], $merchantId, $id)) {
+            return json_error([], '角色名称已存在');
+        }
+        
+        try {
+            UserRoleModel::updateRole($id, $merchantId, $data);
+            return json_success([], '更新角色成功');
+        } catch (\Exception $e) {
+            return json_error([], '更新角色失败:' . $e->getMessage());
+        }
+    }
+    
+    /**
+     * 删除角色
+     */
+    public function delete()
+    {
+        $id = Request::param('id', 0, 'intval');
+        if (!$id) {
+            return json_error([], '角色ID不能为空');
+        }
+        
+        $merchantId = $this->getMerchantId();
+        
+        $role = UserRoleModel::getRoleById($id, $merchantId);
+        if (!$role) {
+            return json_error([], '角色不存在');
+        }
+        
+        $superAdminRoleId = Config::get('permission.super_admin_role_id', 1);
+        if ($id == $superAdminRoleId) {
+            return json_error([], '不能删除超级管理员角色');
+        }
+        
+        $userCount = UserModel::where('user_role', $id)
+            ->where('merchant_id', $merchantId)
+            ->count();
+        if ($userCount > 0) {
+            return json_error([], '该角色下还有用户,不能删除');
+        }
+        
+        try {
+            UserRoleModel::deleteRole($id, $merchantId);
+            return json_success([], '删除角色成功');
+        } catch (\Exception $e) {
+            return json_error([], '删除角色失败:' . $e->getMessage());
+        }
+    }
+    
+    /**
+     * 获取商户ID
+     */
+    private function getMerchantId()
+    {
+        $token = Request::cookie('auth_token');
+        if (!$token) {
+            throw new \Exception('未登录');
+        }
+        
+        $payload = $this->verifyToken($token);
+        if (!$payload) {
+            throw new \Exception('登录已过期');
+        }
+        
+        return $payload['merchant_id'] ?? 0;
+    }
+    
+    /**
+     * 验证Token
+     */
+    private function verifyToken($token)
+    {
+        try {
+            $parts = explode('.', $token);
+            if (count($parts) != 3) {
+                return false;
+            }
+            
+            $payload = json_decode(base64_decode($parts[1]), true);
+            
+            if ($payload['exp'] < time()) {
+                return false;
+            }
+            
+            return $payload;
+        } catch (\Exception $e) {
+            return false;
+        }
+    }
+}

+ 36 - 0
app/model/UserModel.php

@@ -0,0 +1,36 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\model;
+
+use think\Model;
+
+/**
+ * 用户模型
+ */
+class UserModel extends Model
+{
+    // 设置表名
+    protected $name = 'user';
+
+    // 设置主键
+    protected $pk = 'user_id';
+
+    // 设置自动时间戳
+    protected $autoWriteTimestamp = 'int';
+
+    // 设置字段类型
+    protected $type = [
+        'user_id' => 'int',
+        'user_name' => 'string',
+        'password' => 'string',
+        'user_role' => 'int',
+        'merchant_id' => 'int',
+        'phone' => 'string',
+        'nick_name' => 'string',
+        'white_list_ip' => 'string',
+        'create_time' => 'int',
+        'login_time' => 'int',
+        'update_time' => 'int',
+    ];
+}

+ 113 - 0
app/model/UserRoleModel.php

@@ -0,0 +1,113 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\model;
+
+use think\Model;
+
+/**
+ * 角色模型
+ */
+class UserRoleModel extends Model
+{
+    // 设置表名
+    protected $name = 'user_role';
+    
+    // 设置主键
+    protected $pk = 'id';
+    
+    // 开启自动时间戳
+    protected $autoWriteTimestamp = 'int';
+    
+    // 定义时间戳字段名
+    protected $createTime = 'create_time';
+    protected $updateTime = 'update_time';
+    
+    // 设置json类型字段
+    protected $json = ['privileges'];
+    
+    // 设置JSON数据返回数组
+    protected $jsonAssoc = true;
+    
+    /**
+     * 获取角色列表
+     * @param int $merchantId 商户ID
+     * @return \think\Collection
+     */
+    public static function getRoleList(int $merchantId)
+    {
+        return self::where('merchant_id', $merchantId)
+            ->field('id, role_name, privileges, create_time, update_time')
+            ->order('id', 'desc')
+            ->select();
+    }
+    
+    /**
+     * 获取角色详情
+     * @param int $id 角色ID
+     * @param int $merchantId 商户ID
+     * @return array|\think\Model|null
+     */
+    public static function getRoleById(int $id, int $merchantId)
+    {
+        return self::where('id', $id)
+            ->where('merchant_id', $merchantId)
+            ->find();
+    }
+    
+    /**
+     * 创建角色
+     * @param array $data 角色数据
+     * @return \think\Model
+     */
+    public static function createRole(array $data)
+    {
+        return self::create($data);
+    }
+    
+    /**
+     * 更新角色
+     * @param int $id 角色ID
+     * @param int $merchantId 商户ID
+     * @param array $data 更新数据
+     * @return 
+     */
+    public static function updateRole(int $id, int $merchantId, array $data)
+    {
+        return self::where('id', $id)
+            ->where('merchant_id', $merchantId)
+            ->update($data);
+    }
+    
+    /**
+     * 删除角色
+     * @param int $id 角色ID
+     * @param int $merchantId 商户ID
+     * @return bool
+     */
+    public static function deleteRole(int $id, int $merchantId)
+    {
+        return self::where('id', $id)
+            ->where('merchant_id', $merchantId)
+            ->delete();
+    }
+    
+    /**
+     * 检查角色是否存在
+     * @param string $roleName 角色名称
+     * @param int $merchantId 商户ID
+     * @param int|null $excludeId 排除的ID
+     * @return bool
+     */
+    public static function checkRoleExists(string $roleName, int $merchantId, ?int $excludeId = null): bool
+    {
+        $query = self::where('role_name', $roleName)
+            ->where('merchant_id', $merchantId);
+            
+        if ($excludeId) {
+            $query->where('id', '<>', $excludeId);
+        }
+        
+        return $query->count() > 0;
+    }
+}

+ 44 - 0
app/validate/UserRoleValidate.php

@@ -0,0 +1,44 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\validate;
+
+use think\Validate;
+
+/**
+ * 角色验证器
+ */
+class UserRoleValidate extends Validate
+{
+    /**
+     * 定义验证规则
+     */
+    protected $rule = [
+        'role_name'  => 'require|max:50',
+        'privileges' => 'require|array',
+        'id'         => 'require|integer|gt:0',
+    ];
+    
+    /**
+     * 定义错误信息
+     */
+    protected $message = [
+        'role_name.require'  => '角色名称不能为空',
+        'role_name.max'      => '角色名称最多50个字符',
+        'privileges.require' => '权限配置不能为空',
+        'privileges.array'   => '权限配置必须是数组',
+        'id.require'         => '角色ID不能为空',
+        'id.integer'         => '角色ID必须是整数',
+        'id.gt'              => '角色ID必须大于0',
+    ];
+    
+    /**
+     * 定义验证场景
+     */
+    protected $scene = [
+        'create' => ['role_name', 'privileges'],
+        'update' => ['id', 'role_name', 'privileges'],
+        'delete' => ['id'],
+        'detail' => ['id'],
+    ];
+}

+ 44 - 0
app/validate/UserValidate.php

@@ -0,0 +1,44 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\validate;
+
+use think\Validate;
+
+/**
+ * 用户验证器
+ */
+class UserValidate extends Validate
+{
+    // 定义验证规则
+    protected $rule = [
+        'username' => 'require|regex:/^[A-Za-z][A-Za-z0-9]{5,19}$/', // 必须|字母开头,且只包含字母数字,长度6-20
+        'nickname' => 'require|chsDash|length:2,20', // 汉字、字母、数字和下划线_及破折号-|长度6-20
+        'password' => 'require|regex:/^[A-Za-z0-9_+@%$]{6,20}$/', // 必须,以字母开头,长度6-20
+        'user_role'     => 'integer|egt:0',
+        'merchant_id'   => 'require|integer|gt:0',
+    ];
+
+    // 定义错误消息
+    protected $message = [
+        'user_name.require'  => '用户名不能为空',
+        'user_name.regex'    => '用户名只能包含字母或数字,以字母开头,长度在6到20个字符之间',
+        'user_name.unique'   => '用户名已存在',
+        'password.require'   => '密码不能为空',
+        'password.length'    => '密码只能包含字母、数字及特殊字符(_+@%), 长度在6-20个字符之间',
+        'nickname.require'   => '昵称不能为空',
+        'nickname.chsDash'   => '昵称只能包含汉字、字母及数字,长度在2-20个字符之间',
+        'user_role.integer'  => '角色ID必须是整数',
+        'user_role.egt'      => '角色ID必须大于等于0',
+        'merchant_id.require' => '商户ID不能为空',
+        'merchant_id.integer' => '商户ID必须是整数',
+        'merchant_id.gt'     => '商户ID必须大于0',
+    ];
+    
+    // 定义验证场景
+    protected $scene = [
+        'login'  => ['user_name', 'password'],
+        'create' => ['user_name', 'password', 'nick_name', 'user_role', 'merchant_id'],
+        'update' => ['nick_name', 'user_role'],
+    ];
+}

+ 6 - 6
config/database.php

@@ -24,13 +24,13 @@ return [
             // 数据库类型
             'type'            => env('DB_TYPE', 'mysql'),
             // 服务器地址
-            'hostname'        => env('DB_HOST', '127.0.0.1'),
+            'hostname'        => env('DB_HOST', 'rm-wz92e3umb949872jpmo.mysql.rds.aliyuncs.com'),
             // 数据库名
-            'database'        => env('DB_NAME', ''),
+            'database'        => env('DB_NAME', 'merchant_admin'),
             // 用户名
-            'username'        => env('DB_USER', 'root'),
+            'username'        => env('DB_USER', 'game'),
             // 密码
-            'password'        => env('DB_PASS', ''),
+            'password'        => env('DB_PASS', 'Leistar123+-*'),
             // 端口
             'hostport'        => env('DB_PORT', '3306'),
             // 数据库连接参数
@@ -38,7 +38,7 @@ return [
             // 数据库编码
             'charset'         => env('DB_CHARSET', 'utf8mb4'),
             // 数据库表前缀
-            'prefix'          => env('DB_PREFIX', ''),
+            'prefix'          => env('DB_PREFIX', 'merchant_'),
 
             // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
             'deploy'          => 0,
@@ -51,7 +51,7 @@ return [
             // 是否严格检查字段是否存在
             'fields_strict'   => true,
             // 是否需要断线重连
-            'break_reconnect' => false,
+            'break_reconnect' => true,
             // 监听SQL
             'trigger_sql'     => env('APP_DEBUG', true),
             // 开启字段缓存