'退出成功', 'login' => '登录成功', 'error' => '账号或密码错误', 'param' => '参数错误', 'duplicate' => '账号名已存在', 'create_suc' => '创建账号成功', 'empty' => '账号不存在', 'suc' => '操作成功', 'res' => '获取成功', 'ip_denied' => 'IP地址不在白名单中,禁止登录' ]; /** * 登录 */ 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); } // 获取客户端信息 $clientIp = getClientIp(); $userAgent = Request::header('user-agent', ''); // 查询用户 $user = UserModel::where('user_name', $userName)->find(); // 准备登录日志数据 $loginLogData = [ 'merchant_id' => $user ? $user->merchant_id : 0, 'user_id' => $user ? $user->user_id : 0, 'login_device' => $userAgent, 'login_ip' => $clientIp, 'login_status' => UserLoginLogModel::STATUS_FAILED ]; if ($user && password_verify($password, $user->password)) { // 检查IP白名单 if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) { // 记录登录失败日志(IP白名单验证失败) UserLoginLogModel::recordLogin($loginLogData); return json_error([ 'client_ip' => $clientIp, 'white_list_ip' => $user->white_list_ip ], $this->message['ip_denied']); } $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(); // 记录登录成功日志 $loginLogData['login_status'] = UserLoginLogModel::STATUS_SUCCESS; UserLoginLogModel::recordLogin($loginLogData); return json_success([ 'user_name' => $user->user_name, 'nick_name' => $user->nick_name, 'login_time' => $user->login_time, 'token' => $token, ], $this->message['login']); } else { // 记录登录失败日志(密码错误或用户不存在) UserLoginLogModel::recordLogin($loginLogData); return json_error([], $this->message['error']); } } /** * 用户注销 */ public function logout() { Cookie::delete('auth_token'); return json_success([], '退出成功'); } /** * 创建用户 */ public function createUser() { // 获取当前登录用户信息 $userInfo = $this->request->userInfo; // 获取输入数据 $data = Request::only([ 'user_name', 'nick_name', 'password', 'phone', 'user_role/d', 'white_list_ip' ]); $data['merchant_id'] = $userInfo['merchant_id']; try { // 验证数据 $this->validate($data, UserValidate::class . '.create'); } catch (\think\exception\ValidateException $e) { return json_error($e->getError()); } // 验证Ip白名单格式 $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($data['white_list_ip']); if ($checkIpWhiteList[0] == false) { return json_error($checkIpWhiteList[1]); } // 验证角色是否存在 if ($data['user_role'] > 0) { $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['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() { $userInfo = $this->request->userInfo; $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', '=', $userInfo['merchant_id']] ]; if ($userName) { $where[] = ['user_name', 'like', '%' . $userName . '%']; } if ($nickName) { $where[] = ['nick_name', 'like', '%' . $nickName . '%']; } if ($userRole > 99) { $where[] = ['user_role', '=', $userRole]; } else { $where[] = ['user_role', '>', 99]; } $total = UserModel::where($where)->count(); $list = UserModel::where($where) ->field('user_id, user_name, nick_name, phone, user_role, 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() { $userInfo = $this->request->userInfo; $userId = Request::param('user_id', 0, 'intval'); if (!$userId) { return json_error([], '账号ID不能为空'); } $user = UserModel::where('user_id', $userId) ->where('merchant_id', $userInfo['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) { if ($user->user_role > 99) { $role = UserRoleModel::getRoleById($user->user_role, $userInfo['merchant_id']); $user->role_name = $role ? $role->role_name : '未分配'; $user->role_privileges = $role ? $role->privileges : []; } else { $user->role_name = '超级管理员'; $user->role_privileges = []; } } else { $user->role_name = '未分配'; $user->role_privileges = []; } return json_success($user); } /** * 更新用户 */ public function update() { $userInfo = $this->request->userInfo; $userId = Request::post('user_id', 0, 'intval'); if (!$userId) { return json_error([], '账号ID不能为空'); } $user = UserModel::where('user_id', $userId) ->where('merchant_id', $userInfo['merchant_id']) ->find(); if (!$user) { return json_error($this->message['empty']); } // 获取请求中提供的所有可更新字段 $requestData = Request::post(); $allowedFields = ['nick_name', 'phone', 'password', 'user_role', 'white_list_ip']; $updateData = []; // 只处理请求中存在且允许更新的字段 foreach ($allowedFields as $field) { if (array_key_exists($field, $requestData)) { // 对于密码字段,空值则跳过 if ($field === 'password' && empty($requestData[$field])) { continue; } if ($field === 'user_role') { $requestData[$field] = intval($requestData[$field]); } $updateData[$field] = $requestData[$field]; } } if (empty($updateData)) { return json_error([], '没有要更新的数据'); } // 使用验证器进行字段验证 $validate = new UserValidate(); // 只验证传入的字段 if (!$validate->only(array_keys($updateData))->check($updateData)) { return json_error([], $validate->getError()); } // 额外的业务逻辑验证 // 验证角色是否存在 if (isset($updateData['user_role']) && $updateData['user_role'] > 99) { $role = UserRoleModel::getRoleById($updateData['user_role'], $userInfo['merchant_id']); if (!$role) { return json_error([], '选择的角色不存在'); } } // 验证IP白名单格式 if (isset($updateData['white_list_ip'])) { $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($updateData['white_list_ip']); if ($checkIpWhiteList[0] == false) { return json_error([], $checkIpWhiteList[1]); } } // 密码加密 if (isset($updateData['password'])) { $updateData['password'] = password_hash($updateData['password'], PASSWORD_DEFAULT); } try { $user->save($updateData); return json_success([], $this->message['suc']); } catch (\Exception $e) { return json_error([], '更新失败:' . $e->getMessage()); } } /** * 删除用户 */ public function delete() { $userInfo = $this->request->userInfo; $userId = Request::post('user_id', 0, 'intval'); if (!$userId) { return json_error([], '账号ID不能为空'); } if ($userId == $userInfo['user_id']) { return json_error([], '不能删除自己'); } $user = UserModel::where('user_id', $userId) ->where('merchant_id', $userInfo['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()); } } /** * 获取登录日志列表 */ public function loginLogs() { $userInfo = $this->request->userInfo; // 获取查询参数 $page = Request::get('page', 1, 'intval'); $limit = Request::get('limit', 20, 'intval'); $userId = Request::get('user_id', 0, 'intval'); // 过滤条件 $filters = [ 'login_status' => Request::get('login_status', ''), 'login_ip' => Request::get('login_ip', '', 'trim'), 'start_time' => Request::get('start_time', '', 'trim'), 'end_time' => Request::get('end_time', '', 'trim'), ]; try { $result = UserLoginLogModel::getLoginLogs($userInfo['merchant_id'], $userId, $page, $limit, $filters); return json_success($result, '获取成功'); } catch (\Exception $e) { return json_error([], '获取登录日志失败:' . $e->getMessage()); } } /** * 获取登录统计信息 */ public function loginStatistics() { $userInfo = $this->request->userInfo; $userId = Request::get('user_id', 0, 'intval'); $startDate = Request::get('start_date', '', 'trim'); $endDate = Request::get('end_date', '', 'trim'); // 如果没有指定日期范围,默认获取最近30天 if (empty($startDate)) { $startDate = date('Y-m-d', strtotime('-30 days')); } if (empty($endDate)) { $endDate = date('Y-m-d'); } try { $statistics = UserLoginLogModel::getLoginStatistics($userInfo['merchant_id'], $userId, $startDate, $endDate); return json_success([ 'statistics' => $statistics, 'date_range' => [ 'start_date' => $startDate, 'end_date' => $endDate ] ], '获取成功'); } catch (\Exception $e) { return json_error([], '获取登录统计失败:' . $e->getMessage()); } } /** * 获取用户最近登录记录 */ public function recentLoginLogs() { $userInfo = $this->request->userInfo; $userId = Request::get('user_id', 0, 'intval'); $limit = Request::get('limit', 10, 'intval'); // 如果没有指定用户ID,则获取当前用户的登录记录 if ($userId == 0) { $userId = $userInfo['user_id']; } else { // 验证用户是否属于当前商户 $user = UserModel::where('user_id', $userId) ->where('merchant_id', $userInfo['merchant_id']) ->find(); if (!$user) { return json_error([], '用户不存在'); } } try { $logs = UserLoginLogModel::getRecentLogs($userId, $limit); // 格式化日志数据 foreach ($logs as &$log) { $log['status_text'] = $log['login_status'] == UserLoginLogModel::STATUS_SUCCESS ? '成功' : '失败'; $log['login_time_text'] = date('Y-m-d H:i:s', $log['login_time']); } return json_success([ 'logs' => $logs, 'user_id' => $userId ], '获取成功'); } catch (\Exception $e) { return json_error([], '获取最近登录记录失败:' . $e->getMessage()); } } /** * 验证输入数据 */ protected function validateInput(array $data, $scene = '') { $validate = new UserValidate(); // 执行场景验证 if (!$validate->scene($scene)->check($data)) { return $validate->getError(); } return ""; } }