User.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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\validate\UserValidate;
  11. use app\service\IpWhiteListService;
  12. class User extends BaseController
  13. {
  14. protected $message = [
  15. 'logout' => '退出成功',
  16. 'login' => '登录成功',
  17. 'error' => '账号或密码错误',
  18. 'param' => '参数错误',
  19. 'duplicate' => '账号名已存在',
  20. 'create_suc' => '创建账号成功',
  21. 'empty' => '账号不存在',
  22. 'suc' => '操作成功',
  23. 'res' => '获取成功',
  24. 'ip_denied' => 'IP地址不在白名单中,禁止登录'
  25. ];
  26. /**
  27. * 登录
  28. */
  29. public function login()
  30. {
  31. // 获取输入数据
  32. $userName = trim(Request::post('user_name', ''));
  33. $password = trim(Request::post('password', ''));
  34. // 验证输入数据
  35. $checkMessage = $this->validateInput([
  36. 'user_name' => $userName,
  37. 'password' => $password,
  38. ], 'login');
  39. if(!empty($checkMessage)) {
  40. return json_error([], $checkMessage);
  41. }
  42. // 查询用户
  43. $user = UserModel::where('user_name', $userName)->find();
  44. if ($user && password_verify($password, $user->password)) {
  45. // 检查IP白名单
  46. $clientIp = getClientIp();
  47. if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
  48. return json_error([
  49. 'client_ip' => $clientIp,
  50. 'white_list_ip' => $user->white_list_ip
  51. ], $this->message['ip_denied']);
  52. }
  53. $token = generateToken([
  54. 'user_id' => $user->user_id,
  55. 'merchant_id' => $user->merchant_id,
  56. 'user_role' => $user->user_role
  57. ]);
  58. Cookie::set('auth_token', $token, ['expire' => $GLOBALS['cookieExpire'], 'httponly' => true]);
  59. // 更新登录时间
  60. $user->login_time = time();
  61. $user->save();
  62. return json_success([
  63. 'user_name' => $user->user_name,
  64. 'nick_name' => $user->nick_name,
  65. 'login_time' => $user->login_time,
  66. 'token' => $token,
  67. ], $this->message['login']);
  68. } else {
  69. return json_error([], $this->message['error']);
  70. }
  71. }
  72. /**
  73. * 用户注销
  74. */
  75. public function logout()
  76. {
  77. Cookie::delete('auth_token');
  78. return json_success([], '退出成功');
  79. }
  80. /**
  81. * 创建用户
  82. */
  83. public function createUser()
  84. {
  85. // 获取当前登录用户信息
  86. $userInfo = $this->request->userInfo;
  87. // 获取输入数据
  88. $data = Request::only([
  89. 'user_name', 'nick_name', 'password', 'phone',
  90. 'user_role/d', 'white_list_ip'
  91. ]);
  92. $data['merchant_id'] = $userInfo['merchant_id'];
  93. try {
  94. // 验证数据
  95. $this->validate($data, UserValidate::class . '.create');
  96. } catch (\think\exception\ValidateException $e) {
  97. return json_error($e->getError());
  98. }
  99. // 验证Ip白名单格式
  100. $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($data['white_list_ip']);
  101. if ($checkIpWhiteList[0] == false) {
  102. return json_error($checkIpWhiteList[1]);
  103. }
  104. // 验证角色是否存在
  105. if ($data['user_role'] > 0) {
  106. $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['merchant_id']);
  107. if (!$role) {
  108. return json_error([], '选择的角色不存在');
  109. }
  110. }
  111. // 检查账号名是否已存在
  112. if (UserModel::where('user_name', $data['user_name'])->find()) {
  113. return json_error($this->message['duplicate']);
  114. }
  115. // 创建新用户
  116. $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
  117. try {
  118. $user = UserModel::create($data);
  119. return json_success(['user_id' => $user->user_id], $this->message['create_suc']);
  120. } catch (\Exception $e) {
  121. return json_error([], '创建账号失败:' . $e->getMessage());
  122. }
  123. }
  124. /**
  125. * 获取账号列表
  126. */
  127. public function list()
  128. {
  129. $userInfo = $this->request->userInfo;
  130. $page = Request::get('page', 1, 'intval');
  131. $limit = Request::get('limit', 10, 'intval');
  132. $userName = Request::get('user_name', '', 'trim');
  133. $nickName = Request::get('nick_name', '', 'trim');
  134. $userRole = Request::get('user_role', 0, 'intval');
  135. $where = [
  136. ['merchant_id', '=', $userInfo['merchant_id']]
  137. ];
  138. if ($userName) {
  139. $where[] = ['user_name', 'like', '%' . $userName . '%'];
  140. }
  141. if ($nickName) {
  142. $where[] = ['nick_name', 'like', '%' . $nickName . '%'];
  143. }
  144. if ($userRole > 99) {
  145. $where[] = ['user_role', '=', $userRole];
  146. } else {
  147. $where[] = ['user_role', '>', 99];
  148. }
  149. $total = UserModel::where($where)->count();
  150. $list = UserModel::where($where)
  151. ->field('user_id, user_name, nick_name, phone, user_role, white_list_ip, create_time, login_time, update_time')
  152. ->order('user_id', 'desc')
  153. ->page($page, $limit)
  154. ->select();
  155. // 获取角色信息
  156. $roleIds = array_unique(array_column($list->toArray(), 'user_role'));
  157. $roles = [];
  158. if ($roleIds) {
  159. $roleList = UserRoleModel::whereIn('id', $roleIds)->select();
  160. foreach ($roleList as $role) {
  161. $roles[$role->id] = $role->role_name;
  162. }
  163. }
  164. // 添加角色名称
  165. foreach ($list as $user) {
  166. $user->role_name = $roles[$user->user_role] ?? '未分配';
  167. }
  168. return json_success([
  169. 'list' => $list,
  170. 'total' => $total,
  171. 'page' => $page,
  172. 'limit' => $limit
  173. ]);
  174. }
  175. /**
  176. * 获取用户详情
  177. */
  178. public function detail()
  179. {
  180. $userInfo = $this->request->userInfo;
  181. $userId = Request::param('user_id', 0, 'intval');
  182. if (!$userId) {
  183. return json_error([], '账号ID不能为空');
  184. }
  185. $user = UserModel::where('user_id', $userId)
  186. ->where('merchant_id', $userInfo['merchant_id'])
  187. ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
  188. ->find();
  189. if (!$user) {
  190. return json_error($this->message['empty']);
  191. }
  192. // 获取角色信息
  193. if ($user->user_role > 0) {
  194. if ($user->user_role > 99) {
  195. $role = UserRoleModel::getRoleById($user->user_role, $userInfo['merchant_id']);
  196. $user->role_name = $role ? $role->role_name : '未分配';
  197. $user->role_privileges = $role ? $role->privileges : [];
  198. } else {
  199. $user->role_name = '超级管理员';
  200. $user->role_privileges = [];
  201. }
  202. } else {
  203. $user->role_name = '未分配';
  204. $user->role_privileges = [];
  205. }
  206. return json_success($user);
  207. }
  208. /**
  209. * 更新用户
  210. */
  211. public function update()
  212. {
  213. $userInfo = $this->request->userInfo;
  214. $userId = Request::post('user_id', 0, 'intval');
  215. if (!$userId) {
  216. return json_error([], '账号ID不能为空');
  217. }
  218. $user = UserModel::where('user_id', $userId)
  219. ->where('merchant_id', $userInfo['merchant_id'])
  220. ->find();
  221. if (!$user) {
  222. return json_error($this->message['empty']);
  223. }
  224. // 获取请求中提供的所有可更新字段
  225. $requestData = Request::post();
  226. $allowedFields = ['nick_name', 'phone', 'password', 'user_role', 'white_list_ip'];
  227. $updateData = [];
  228. // 只处理请求中存在且允许更新的字段
  229. foreach ($allowedFields as $field) {
  230. if (array_key_exists($field, $requestData)) {
  231. // 对于密码字段,空值则跳过
  232. if ($field === 'password' && empty($requestData[$field])) {
  233. continue;
  234. }
  235. if ($field === 'user_role') {
  236. $requestData[$field] = intval($requestData[$field]);
  237. }
  238. $updateData[$field] = $requestData[$field];
  239. }
  240. }
  241. if (empty($updateData)) {
  242. return json_error([], '没有要更新的数据');
  243. }
  244. // 使用验证器进行字段验证
  245. $validate = new UserValidate();
  246. // 只验证传入的字段
  247. if (!$validate->only(array_keys($updateData))->check($updateData)) {
  248. return json_error([], $validate->getError());
  249. }
  250. // 额外的业务逻辑验证
  251. // 验证角色是否存在
  252. if (isset($updateData['user_role']) && $updateData['user_role'] > 99) {
  253. $role = UserRoleModel::getRoleById($updateData['user_role'], $userInfo['merchant_id']);
  254. if (!$role) {
  255. return json_error([], '选择的角色不存在');
  256. }
  257. }
  258. // 验证IP白名单格式
  259. if (isset($updateData['white_list_ip'])) {
  260. $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($updateData['white_list_ip']);
  261. if ($checkIpWhiteList[0] == false) {
  262. return json_error([], $checkIpWhiteList[1]);
  263. }
  264. }
  265. // 密码加密
  266. if (isset($updateData['password'])) {
  267. $updateData['password'] = password_hash($updateData['password'], PASSWORD_DEFAULT);
  268. }
  269. try {
  270. $user->save($updateData);
  271. return json_success([], $this->message['suc']);
  272. } catch (\Exception $e) {
  273. return json_error([], '更新失败:' . $e->getMessage());
  274. }
  275. }
  276. /**
  277. * 删除用户
  278. */
  279. public function delete()
  280. {
  281. $userInfo = $this->request->userInfo;
  282. $userId = Request::post('user_id', 0, 'intval');
  283. if (!$userId) {
  284. return json_error([], '账号ID不能为空');
  285. }
  286. if ($userId == $userInfo['user_id']) {
  287. return json_error([], '不能删除自己');
  288. }
  289. $user = UserModel::where('user_id', $userId)
  290. ->where('merchant_id', $userInfo['merchant_id'])
  291. ->find();
  292. if (!$user) {
  293. return json_error($this->message['empty']);
  294. }
  295. try {
  296. $user->delete();
  297. return json_success([], '删除成功');
  298. } catch (\Exception $e) {
  299. return json_error([], '删除失败:' . $e->getMessage());
  300. }
  301. }
  302. /**
  303. * 验证输入数据
  304. */
  305. protected function validateInput(array $data, $scene = '')
  306. {
  307. $validate = new UserValidate();
  308. // 执行场景验证
  309. if (!$validate->scene($scene)->check($data)) {
  310. return $validate->getError();
  311. }
  312. return "";
  313. }
  314. }