User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\controller;
  4. use app\BaseController;
  5. use think\facade\Cookie;
  6. use think\facade\Request;
  7. use think\facade\Config;
  8. use app\model\UserModel;
  9. use app\model\UserRoleModel;
  10. use app\model\UserLoginLogModel;
  11. use app\validate\UserValidate;
  12. use app\service\IpWhiteListService;
  13. class User extends BaseController
  14. {
  15. protected $message = [
  16. 'logout' => '退出成功',
  17. 'login' => '登录成功',
  18. 'error' => '账号或密码错误',
  19. 'param' => '参数错误',
  20. 'duplicate' => '账号名已存在',
  21. 'create_suc' => '创建账号成功',
  22. 'empty' => '账号不存在',
  23. 'suc' => '操作成功',
  24. 'res' => '获取成功',
  25. 'ip_denied' => 'IP地址不在白名单中,禁止登录'
  26. ];
  27. /**
  28. * 登录
  29. */
  30. public function login()
  31. {
  32. // 获取输入数据
  33. $userName = trim(Request::post('user_name', ''));
  34. $password = trim(Request::post('password', ''));
  35. // 验证输入数据
  36. $checkMessage = $this->validateInput([
  37. 'user_name' => $userName,
  38. 'password' => $password,
  39. ], 'login');
  40. if(!empty($checkMessage)) {
  41. return json_error([], $checkMessage);
  42. }
  43. // 获取客户端信息
  44. $clientIp = getClientIp();
  45. $userAgent = Request::header('user-agent', '');
  46. // 查询用户
  47. $user = UserModel::where('user_name', $userName)->find();
  48. // 准备登录日志数据
  49. $loginLogData = [
  50. 'merchant_id' => $user ? $user->merchant_id : 0,
  51. 'user_id' => $user ? $user->user_id : 0,
  52. 'login_device' => $userAgent,
  53. 'login_ip' => $clientIp,
  54. 'login_status' => UserLoginLogModel::STATUS_FAILED
  55. ];
  56. if ($user && password_verify($password, $user->password)) {
  57. // 检查IP白名单
  58. if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
  59. // 记录登录失败日志(IP白名单验证失败)
  60. UserLoginLogModel::recordLogin($loginLogData);
  61. return json_error([
  62. 'client_ip' => $clientIp,
  63. 'white_list_ip' => $user->white_list_ip
  64. ], $this->message['ip_denied']);
  65. }
  66. $token = generateToken([
  67. 'user_id' => $user->user_id,
  68. 'merchant_id' => $user->merchant_id,
  69. 'user_role' => $user->user_role
  70. ]);
  71. Cookie::set('auth_token', $token, ['expire' => $GLOBALS['cookieExpire'], 'httponly' => true]);
  72. // 更新登录时间
  73. $user->login_time = time();
  74. $user->save();
  75. // 记录登录成功日志
  76. $loginLogData['login_status'] = UserLoginLogModel::STATUS_SUCCESS;
  77. UserLoginLogModel::recordLogin($loginLogData);
  78. return json_success([
  79. 'user_name' => $user->user_name,
  80. 'nick_name' => $user->nick_name,
  81. 'login_time' => $user->login_time,
  82. 'token' => $token,
  83. ], $this->message['login']);
  84. } else {
  85. // 记录登录失败日志(密码错误或用户不存在)
  86. UserLoginLogModel::recordLogin($loginLogData);
  87. return json_error([], $this->message['error']);
  88. }
  89. }
  90. /**
  91. * 用户注销
  92. */
  93. public function logout()
  94. {
  95. Cookie::delete('auth_token');
  96. return json_success([], '退出成功');
  97. }
  98. /**
  99. * 创建用户
  100. */
  101. public function createUser()
  102. {
  103. // 获取当前登录用户信息
  104. $userInfo = $this->request->userInfo;
  105. // 获取输入数据
  106. $data = Request::only([
  107. 'user_name', 'nick_name', 'password', 'phone',
  108. 'user_role/d', 'white_list_ip'
  109. ]);
  110. $data['merchant_id'] = $userInfo['merchant_id'];
  111. try {
  112. // 验证数据
  113. $this->validate($data, UserValidate::class . '.create');
  114. } catch (\think\exception\ValidateException $e) {
  115. return json_error($e->getError());
  116. }
  117. // 验证Ip白名单格式
  118. $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($data['white_list_ip']);
  119. if ($checkIpWhiteList[0] == false) {
  120. return json_error($checkIpWhiteList[1]);
  121. }
  122. // 验证角色是否存在
  123. if ($data['user_role'] > 0) {
  124. $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['merchant_id']);
  125. if (!$role) {
  126. return json_error([], '选择的角色不存在');
  127. }
  128. }
  129. // 检查账号名是否已存在
  130. if (UserModel::where('user_name', $data['user_name'])->find()) {
  131. return json_error($this->message['duplicate']);
  132. }
  133. // 创建新用户
  134. $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
  135. try {
  136. $user = UserModel::create($data);
  137. return json_success(['user_id' => $user->user_id], $this->message['create_suc']);
  138. } catch (\Exception $e) {
  139. return json_error([], '创建账号失败:' . $e->getMessage());
  140. }
  141. }
  142. /**
  143. * 获取账号列表
  144. */
  145. public function list()
  146. {
  147. $userInfo = $this->request->userInfo;
  148. $page = Request::get('page', 1, 'intval');
  149. $limit = Request::get('limit', 10, 'intval');
  150. $userName = Request::get('user_name', '', 'trim');
  151. $nickName = Request::get('nick_name', '', 'trim');
  152. $userRole = Request::get('user_role', 0, 'intval');
  153. $where = [
  154. ['merchant_id', '=', $userInfo['merchant_id']]
  155. ];
  156. if ($userName) {
  157. $where[] = ['user_name', 'like', '%' . $userName . '%'];
  158. }
  159. if ($nickName) {
  160. $where[] = ['nick_name', 'like', '%' . $nickName . '%'];
  161. }
  162. if ($userRole > 99) {
  163. $where[] = ['user_role', '=', $userRole];
  164. } else {
  165. $where[] = ['user_role', '>', 99];
  166. }
  167. $total = UserModel::where($where)->count();
  168. $list = UserModel::where($where)
  169. ->field('user_id, user_name, nick_name, phone, user_role, white_list_ip, create_time, login_time, update_time')
  170. ->order('user_id', 'desc')
  171. ->page($page, $limit)
  172. ->select();
  173. // 获取角色信息
  174. $roleIds = array_unique(array_column($list->toArray(), 'user_role'));
  175. $roles = [];
  176. if ($roleIds) {
  177. $roleList = UserRoleModel::whereIn('id', $roleIds)->select();
  178. foreach ($roleList as $role) {
  179. $roles[$role->id] = $role->role_name;
  180. }
  181. }
  182. // 添加角色名称
  183. foreach ($list as $user) {
  184. $user->role_name = $roles[$user->user_role] ?? '未分配';
  185. }
  186. return json_success([
  187. 'list' => $list,
  188. 'total' => $total,
  189. 'page' => $page,
  190. 'limit' => $limit
  191. ]);
  192. }
  193. /**
  194. * 获取用户详情
  195. */
  196. public function detail()
  197. {
  198. $userInfo = $this->request->userInfo;
  199. $userId = Request::param('user_id', 0, 'intval');
  200. if (!$userId) {
  201. return json_error([], '账号ID不能为空');
  202. }
  203. $user = UserModel::where('user_id', $userId)
  204. ->where('merchant_id', $userInfo['merchant_id'])
  205. ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
  206. ->find();
  207. if (!$user) {
  208. return json_error($this->message['empty']);
  209. }
  210. // 获取角色信息
  211. if ($user->user_role > 0) {
  212. if ($user->user_role > 99) {
  213. $role = UserRoleModel::getRoleById($user->user_role, $userInfo['merchant_id']);
  214. $user->role_name = $role ? $role->role_name : '未分配';
  215. $user->role_privileges = $role ? $role->privileges : [];
  216. } else {
  217. $user->role_name = '超级管理员';
  218. $user->role_privileges = [];
  219. }
  220. } else {
  221. $user->role_name = '未分配';
  222. $user->role_privileges = [];
  223. }
  224. return json_success($user);
  225. }
  226. /**
  227. * 更新用户
  228. */
  229. public function update()
  230. {
  231. $userInfo = $this->request->userInfo;
  232. $userId = Request::post('user_id', 0, 'intval');
  233. if (!$userId) {
  234. return json_error([], '账号ID不能为空');
  235. }
  236. $user = UserModel::where('user_id', $userId)
  237. ->where('merchant_id', $userInfo['merchant_id'])
  238. ->find();
  239. if (!$user) {
  240. return json_error($this->message['empty']);
  241. }
  242. // 获取请求中提供的所有可更新字段
  243. $requestData = Request::post();
  244. $allowedFields = ['nick_name', 'phone', 'password', 'user_role', 'white_list_ip'];
  245. $updateData = [];
  246. // 只处理请求中存在且允许更新的字段
  247. foreach ($allowedFields as $field) {
  248. if (array_key_exists($field, $requestData)) {
  249. // 对于密码字段,空值则跳过
  250. if ($field === 'password' && empty($requestData[$field])) {
  251. continue;
  252. }
  253. if ($field === 'user_role') {
  254. $requestData[$field] = intval($requestData[$field]);
  255. }
  256. $updateData[$field] = $requestData[$field];
  257. }
  258. }
  259. if (empty($updateData)) {
  260. return json_error([], '没有要更新的数据');
  261. }
  262. // 使用验证器进行字段验证
  263. $validate = new UserValidate();
  264. // 只验证传入的字段
  265. if (!$validate->only(array_keys($updateData))->check($updateData)) {
  266. return json_error([], $validate->getError());
  267. }
  268. // 额外的业务逻辑验证
  269. // 验证角色是否存在
  270. if (isset($updateData['user_role']) && $updateData['user_role'] > 99) {
  271. $role = UserRoleModel::getRoleById($updateData['user_role'], $userInfo['merchant_id']);
  272. if (!$role) {
  273. return json_error([], '选择的角色不存在');
  274. }
  275. }
  276. // 验证IP白名单格式
  277. if (isset($updateData['white_list_ip'])) {
  278. $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($updateData['white_list_ip']);
  279. if ($checkIpWhiteList[0] == false) {
  280. return json_error([], $checkIpWhiteList[1]);
  281. }
  282. }
  283. // 密码加密
  284. if (isset($updateData['password'])) {
  285. $updateData['password'] = password_hash($updateData['password'], PASSWORD_DEFAULT);
  286. }
  287. try {
  288. $user->save($updateData);
  289. return json_success([], $this->message['suc']);
  290. } catch (\Exception $e) {
  291. return json_error([], '更新失败:' . $e->getMessage());
  292. }
  293. }
  294. /**
  295. * 删除用户
  296. */
  297. public function delete()
  298. {
  299. $userInfo = $this->request->userInfo;
  300. $userId = Request::post('user_id', 0, 'intval');
  301. if (!$userId) {
  302. return json_error([], '账号ID不能为空');
  303. }
  304. if ($userId == $userInfo['user_id']) {
  305. return json_error([], '不能删除自己');
  306. }
  307. $user = UserModel::where('user_id', $userId)
  308. ->where('merchant_id', $userInfo['merchant_id'])
  309. ->find();
  310. if (!$user) {
  311. return json_error($this->message['empty']);
  312. }
  313. try {
  314. $user->delete();
  315. return json_success([], '删除成功');
  316. } catch (\Exception $e) {
  317. return json_error([], '删除失败:' . $e->getMessage());
  318. }
  319. }
  320. /**
  321. * 获取登录日志列表
  322. */
  323. public function loginLogs()
  324. {
  325. $userInfo = $this->request->userInfo;
  326. // 获取查询参数
  327. $page = Request::get('page', 1, 'intval');
  328. $limit = Request::get('limit', 20, 'intval');
  329. $userId = Request::get('user_id', 0, 'intval');
  330. // 过滤条件
  331. $filters = [
  332. 'login_status' => Request::get('login_status', ''),
  333. 'login_ip' => Request::get('login_ip', '', 'trim'),
  334. 'start_time' => Request::get('start_time', '', 'trim'),
  335. 'end_time' => Request::get('end_time', '', 'trim'),
  336. ];
  337. try {
  338. $result = UserLoginLogModel::getLoginLogs($userInfo['merchant_id'], $userId, $page, $limit, $filters);
  339. return json_success($result, '获取成功');
  340. } catch (\Exception $e) {
  341. return json_error([], '获取登录日志失败:' . $e->getMessage());
  342. }
  343. }
  344. /**
  345. * 获取登录统计信息
  346. */
  347. public function loginStatistics()
  348. {
  349. $userInfo = $this->request->userInfo;
  350. $userId = Request::get('user_id', 0, 'intval');
  351. $startDate = Request::get('start_date', '', 'trim');
  352. $endDate = Request::get('end_date', '', 'trim');
  353. // 如果没有指定日期范围,默认获取最近30天
  354. if (empty($startDate)) {
  355. $startDate = date('Y-m-d', strtotime('-30 days'));
  356. }
  357. if (empty($endDate)) {
  358. $endDate = date('Y-m-d');
  359. }
  360. try {
  361. $statistics = UserLoginLogModel::getLoginStatistics($userInfo['merchant_id'], $userId, $startDate, $endDate);
  362. return json_success([
  363. 'statistics' => $statistics,
  364. 'date_range' => [
  365. 'start_date' => $startDate,
  366. 'end_date' => $endDate
  367. ]
  368. ], '获取成功');
  369. } catch (\Exception $e) {
  370. return json_error([], '获取登录统计失败:' . $e->getMessage());
  371. }
  372. }
  373. /**
  374. * 获取用户最近登录记录
  375. */
  376. public function recentLoginLogs()
  377. {
  378. $userInfo = $this->request->userInfo;
  379. $userId = Request::get('user_id', 0, 'intval');
  380. $limit = Request::get('limit', 10, 'intval');
  381. // 如果没有指定用户ID,则获取当前用户的登录记录
  382. if ($userId == 0) {
  383. $userId = $userInfo['user_id'];
  384. } else {
  385. // 验证用户是否属于当前商户
  386. $user = UserModel::where('user_id', $userId)
  387. ->where('merchant_id', $userInfo['merchant_id'])
  388. ->find();
  389. if (!$user) {
  390. return json_error([], '用户不存在');
  391. }
  392. }
  393. try {
  394. $logs = UserLoginLogModel::getRecentLogs($userId, $limit);
  395. // 格式化日志数据
  396. foreach ($logs as &$log) {
  397. $log['status_text'] = $log['login_status'] == UserLoginLogModel::STATUS_SUCCESS ? '成功' : '失败';
  398. $log['login_time_text'] = date('Y-m-d H:i:s', $log['login_time']);
  399. }
  400. return json_success([
  401. 'logs' => $logs,
  402. 'user_id' => $userId
  403. ], '获取成功');
  404. } catch (\Exception $e) {
  405. return json_error([], '获取最近登录记录失败:' . $e->getMessage());
  406. }
  407. }
  408. /**
  409. * 验证输入数据
  410. */
  411. protected function validateInput(array $data, $scene = '')
  412. {
  413. $validate = new UserValidate();
  414. // 执行场景验证
  415. if (!$validate->scene($scene)->check($data)) {
  416. return $validate->getError();
  417. }
  418. return "";
  419. }
  420. }