User.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. $data = Request::only([
  226. 'nick_name', 'phone', 'password', 'user_role/d', 'white_list_ip'
  227. ]);
  228. // 过滤空值
  229. $data = array_filter($data, function($value, $key) {
  230. return $key !== 'password' || !empty($value);
  231. }, ARRAY_FILTER_USE_BOTH);
  232. if (empty($data)) {
  233. return json_error([], '没有要更新的数据');
  234. }
  235. // 验证角色是否存在
  236. if (isset($data['user_role'])) {
  237. $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['merchant_id']);
  238. if (!$role) {
  239. return json_error([], '选择的角色不存在');
  240. }
  241. }
  242. if (isset($data['white_list_ip'])) {
  243. // 验证Ip白名单格式
  244. $checkIpWhiteList = IpWhiteListService::validateWhiteListFormat($data['white_list_ip']);
  245. if ($checkIpWhiteList[0] == false) {
  246. return json_error($checkIpWhiteList[1]);
  247. }
  248. }
  249. // 密码加密
  250. if (isset($data['password'])) {
  251. $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
  252. }
  253. try {
  254. $user->save($data);
  255. return json_success([], $this->message['suc']);
  256. } catch (\Exception $e) {
  257. return json_error([], '更新失败:' . $e->getMessage());
  258. }
  259. }
  260. /**
  261. * 删除用户
  262. */
  263. public function delete()
  264. {
  265. $userInfo = $this->request->userInfo;
  266. $userId = Request::post('user_id', 0, 'intval');
  267. if (!$userId) {
  268. return json_error([], '账号ID不能为空');
  269. }
  270. if ($userId == $userInfo['user_id']) {
  271. return json_error([], '不能删除自己');
  272. }
  273. $user = UserModel::where('user_id', $userId)
  274. ->where('merchant_id', $userInfo['merchant_id'])
  275. ->find();
  276. if (!$user) {
  277. return json_error($this->message['empty']);
  278. }
  279. try {
  280. $user->delete();
  281. return json_success([], '删除成功');
  282. } catch (\Exception $e) {
  283. return json_error([], '删除失败:' . $e->getMessage());
  284. }
  285. }
  286. /**
  287. * 验证输入数据
  288. */
  289. protected function validateInput(array $data, $scene = '')
  290. {
  291. $validate = new UserValidate();
  292. // 执行场景验证
  293. if (!$validate->scene($scene)->check($data)) {
  294. return $validate->getError();
  295. }
  296. return "";
  297. }
  298. }