User.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. 'user_role' => $user->user_role,
  66. 'login_time' => $user->login_time,
  67. 'token' => $token,
  68. 'client_ip' => $clientIp
  69. ], $this->message['login']);
  70. } else {
  71. return json_error([], $this->message['error']);
  72. }
  73. }
  74. /**
  75. * 用户注销
  76. */
  77. public function logout()
  78. {
  79. Cookie::delete('auth_token');
  80. return json_success([], '退出成功');
  81. }
  82. /**
  83. * 创建用户
  84. */
  85. public function createUser()
  86. {
  87. // 获取当前登录用户信息
  88. $userInfo = $this->request->userInfo;
  89. // 获取输入数据
  90. $data = Request::only([
  91. 'user_name', 'nick_name', 'password', 'phone',
  92. 'user_role', 'white_list_ip'
  93. ]);
  94. $data['merchant_id'] = $userInfo['merchant_id'];
  95. try {
  96. // 验证数据
  97. $this->validate($data, UserValidate::class . '.create');
  98. } catch (\think\exception\ValidateException $e) {
  99. return json_error($e->getError());
  100. }
  101. // 验证角色是否存在
  102. if ($data['user_role'] > 0) {
  103. $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['merchant_id']);
  104. if (!$role) {
  105. return json_error([], '选择的角色不存在');
  106. }
  107. }
  108. // 检查用户名是否已存在
  109. if (UserModel::where('user_name', $data['user_name'])->find()) {
  110. return json_error($this->message['duplicate']);
  111. }
  112. // 创建新用户
  113. $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
  114. try {
  115. $user = UserModel::create($data);
  116. return json_success(['user_id' => $user->user_id], $this->message['create_suc']);
  117. } catch (\Exception $e) {
  118. return json_error([], '创建用户失败:' . $e->getMessage());
  119. }
  120. }
  121. /**
  122. * 获取用户列表
  123. */
  124. public function list()
  125. {
  126. $userInfo = $this->request->userInfo;
  127. $page = Request::get('page', 1, 'intval');
  128. $limit = Request::get('limit', 10, 'intval');
  129. $userName = Request::get('user_name', '', 'trim');
  130. $nickName = Request::get('nick_name', '', 'trim');
  131. $userRole = Request::get('user_role', 0, 'intval');
  132. $where = [
  133. ['merchant_id', '=', $userInfo['merchant_id']]
  134. ];
  135. if ($userName) {
  136. $where[] = ['user_name', 'like', '%' . $userName . '%'];
  137. }
  138. if ($nickName) {
  139. $where[] = ['nick_name', 'like', '%' . $nickName . '%'];
  140. }
  141. if ($userRole > 0) {
  142. $where[] = ['user_role', '=', $userRole];
  143. }
  144. $total = UserModel::where($where)->count();
  145. $list = UserModel::where($where)
  146. ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
  147. ->order('user_id', 'desc')
  148. ->page($page, $limit)
  149. ->select();
  150. // 获取角色信息
  151. $roleIds = array_unique(array_column($list->toArray(), 'user_role'));
  152. $roles = [];
  153. if ($roleIds) {
  154. $roleList = UserRoleModel::whereIn('id', $roleIds)->select();
  155. foreach ($roleList as $role) {
  156. $roles[$role->id] = $role->role_name;
  157. }
  158. }
  159. // 添加角色名称
  160. foreach ($list as $user) {
  161. $user->role_name = $roles[$user->user_role] ?? '未分配角色';
  162. }
  163. return json_success([
  164. 'list' => $list,
  165. 'total' => $total,
  166. 'page' => $page,
  167. 'limit' => $limit
  168. ]);
  169. }
  170. /**
  171. * 获取用户详情
  172. */
  173. public function detail()
  174. {
  175. $userInfo = $this->request->userInfo;
  176. $userId = Request::param('user_id', 0, 'intval');
  177. if (!$userId) {
  178. return json_error([], '用户ID不能为空');
  179. }
  180. $user = UserModel::where('user_id', $userId)
  181. ->where('merchant_id', $userInfo['merchant_id'])
  182. ->field('user_id, user_name, nick_name, phone, user_role, merchant_id, white_list_ip, create_time, login_time, update_time')
  183. ->find();
  184. if (!$user) {
  185. return json_error($this->message['empty']);
  186. }
  187. // 获取角色信息
  188. if ($user->user_role > 0) {
  189. $role = UserRoleModel::getRoleById($user->user_role, $userInfo['merchant_id']);
  190. $user->role_name = $role ? $role->role_name : '未分配角色';
  191. $user->role_privileges = $role ? $role->privileges : [];
  192. } else {
  193. $user->role_name = '未分配角色';
  194. $user->role_privileges = [];
  195. }
  196. return json_success($user);
  197. }
  198. /**
  199. * 更新用户
  200. */
  201. public function update()
  202. {
  203. $userInfo = $this->request->userInfo;
  204. $userId = Request::post('user_id', 0, 'intval');
  205. if (!$userId) {
  206. return json_error([], '用户ID不能为空');
  207. }
  208. $user = UserModel::where('user_id', $userId)
  209. ->where('merchant_id', $userInfo['merchant_id'])
  210. ->find();
  211. if (!$user) {
  212. return json_error($this->message['empty']);
  213. }
  214. // 获取更新数据
  215. $data = Request::only([
  216. 'nick_name', 'phone', 'password', 'user_role', 'white_list_ip'
  217. ]);
  218. // 过滤空值
  219. $data = array_filter($data, function($value, $key) {
  220. return $key !== 'password' || !empty($value);
  221. }, ARRAY_FILTER_USE_BOTH);
  222. if (empty($data)) {
  223. return json_error([], '没有要更新的数据');
  224. }
  225. // 验证角色是否存在
  226. if (isset($data['user_role']) && $data['user_role'] > 0) {
  227. $role = UserRoleModel::getRoleById($data['user_role'], $userInfo['merchant_id']);
  228. if (!$role) {
  229. return json_error([], '选择的角色不存在');
  230. }
  231. }
  232. // 密码加密
  233. if (isset($data['password'])) {
  234. $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
  235. }
  236. try {
  237. $user->save($data);
  238. return json_success([], $this->message['suc']);
  239. } catch (\Exception $e) {
  240. return json_error([], '更新失败:' . $e->getMessage());
  241. }
  242. }
  243. /**
  244. * 删除用户
  245. */
  246. public function delete()
  247. {
  248. $userInfo = $this->request->userInfo;
  249. $userId = Request::post('user_id', 0, 'intval');
  250. if (!$userId) {
  251. return json_error([], '用户ID不能为空');
  252. }
  253. if ($userId == $userInfo['user_id']) {
  254. return json_error([], '不能删除自己');
  255. }
  256. $user = UserModel::where('user_id', $userId)
  257. ->where('merchant_id', $userInfo['merchant_id'])
  258. ->find();
  259. if (!$user) {
  260. return json_error($this->message['empty']);
  261. }
  262. try {
  263. $user->delete();
  264. return json_success([], '删除成功');
  265. } catch (\Exception $e) {
  266. return json_error([], '删除失败:' . $e->getMessage());
  267. }
  268. }
  269. /**
  270. * 验证输入数据
  271. */
  272. protected function validateInput(array $data, $scene = '')
  273. {
  274. $validate = new UserValidate();
  275. // 执行场景验证
  276. if (!$validate->scene($scene)->check($data)) {
  277. return $validate->getError();
  278. }
  279. return "";
  280. }
  281. }