UserController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Components\Helpers;
  4. use App\Components\IP;
  5. use App\Http\Controllers\Controller;
  6. use App\Http\Requests\Admin\UserStoreRequest;
  7. use App\Http\Requests\Admin\UserUpdateRequest;
  8. use App\Models\Level;
  9. use App\Models\Node;
  10. use App\Models\Order;
  11. use App\Models\User;
  12. use App\Models\UserGroup;
  13. use App\Models\UserHourlyDataFlow;
  14. use Auth;
  15. use Exception;
  16. use Illuminate\Http\JsonResponse;
  17. use Illuminate\Http\Request;
  18. use Log;
  19. use Response;
  20. use Session;
  21. use Spatie\Permission\Models\Role;
  22. use Str;
  23. class UserController extends Controller
  24. {
  25. // 用户列表
  26. public function index(Request $request)
  27. {
  28. $id = $request->input('id');
  29. $email = $request->input('email');
  30. $wechat = $request->input('wechat');
  31. $qq = $request->input('qq');
  32. $port = $request->input('port');
  33. $group = $request->input('group');
  34. $level = $request->input('level');
  35. $status = $request->input('status');
  36. $enable = $request->input('enable');
  37. $online = $request->input('online');
  38. $flowAbnormal = $request->input('flowAbnormal');
  39. $expireWarning = $request->input('expireWarning');
  40. $largeTraffic = $request->input('largeTraffic');
  41. $query = User::with('subscribe');
  42. if (isset($id)) {
  43. $query->whereId($id);
  44. }
  45. if (isset($email)) {
  46. $query->where('email', 'like', '%'.$email.'%');
  47. }
  48. if (isset($wechat)) {
  49. $query->where('wechat', 'like', '%'.$wechat.'%');
  50. }
  51. if (isset($qq)) {
  52. $query->where('qq', 'like', '%'.$qq.'%');
  53. }
  54. if (isset($port)) {
  55. $query->wherePort($port);
  56. }
  57. if (isset($status)) {
  58. $query->whereStatus($status);
  59. }
  60. if (isset($enable)) {
  61. $query->whereEnable($enable);
  62. }
  63. if (isset($group)) {
  64. $query->whereGroupId($group);
  65. }
  66. if (isset($level)) {
  67. $query->whereLevel($level);
  68. }
  69. // 流量超过100G的
  70. if ($largeTraffic) {
  71. $query->whereIn('status', [0, 1])->whereRaw('(u + d)/transfer_enable >= 0.9');
  72. }
  73. // 临近过期提醒
  74. if ($expireWarning) {
  75. $query->whereBetween('expired_at', [date('Y-m-d'), date('Y-m-d', strtotime('+'.sysConfig('expire_days').' days'))]);
  76. }
  77. // 当前在线
  78. if ($online) {
  79. $query->where('t', '>=', strtotime('-10 minutes'));
  80. }
  81. // 不活跃用户
  82. if ($request->has('unActive')) {
  83. $query->whereBetween('t', [1, strtotime('-'.sysConfig('expire_days').' days')])->whereEnable(1);
  84. }
  85. // 不活跃用户
  86. if ($request->has('paying')) {
  87. $payingUser = Order::whereStatus(2)->where('goods_id', '<>', 0)->whereIsExpire(0)->where('amount', '>', 0)->pluck('user_id')->unique();
  88. $query->whereIn('id', $payingUser);
  89. }
  90. // 1小时内流量异常用户
  91. if ($flowAbnormal) {
  92. $query->whereIn('id', (new UserHourlyDataFlow)->trafficAbnormal());
  93. }
  94. return view('admin.user.index', [
  95. 'userList' => $query->orderByDesc('id')->paginate(15)->appends($request->except('page')),
  96. 'userGroups' => UserGroup::all()->pluck('name', 'id')->toArray(),
  97. 'levels' => Level::all()->pluck('name', 'level')->toArray(),
  98. ]);
  99. }
  100. // 添加账号页面
  101. public function create()
  102. {
  103. if (Auth::getUser()->hasRole('Super Admin')) {
  104. $roles = Role::all()->pluck('description', 'name');
  105. } elseif (Auth::getUser()->hasPermissionTo('give roles')) {
  106. $roles = Auth::getUser()->roles();
  107. }
  108. return view('admin.user.info', [
  109. 'levels' => Level::orderBy('level')->get(),
  110. 'userGroups' => UserGroup::orderBy('id')->get(),
  111. 'roles' => $roles ?? [],
  112. ]);
  113. }
  114. // 添加账号
  115. public function store(UserStoreRequest $request): JsonResponse
  116. {
  117. try {
  118. $data = $request->except('_token', 'uuid', 'roles');
  119. $data['password'] = $data['password'] ?? Str::random();
  120. $data['port'] = $data['port'] ?? Helpers::getPort();
  121. $data['passwd'] = $data['passwd'] ?? Str::random();
  122. $data['vmess_id'] = $request->input('uuid') ?? Str::uuid();
  123. $data['transfer_enable'] *= GB;
  124. $data['expired_at'] = $data['expired_at'] ?? date('Y-m-d', strtotime('+365 days'));
  125. $data['remark'] = str_replace(['atob', 'eval'], '', $data['remark']);
  126. $data['reg_ip'] = IP::getClientIp();
  127. $data['reset_time'] = $data['reset_time'] > date('Y-m-d') ? $data['reset_time'] : null;
  128. $user = User::create($data);
  129. $roles = $request->input('roles') ?? [];
  130. if ($roles && (Auth::getUser()->hasPermissionTo('give roles') || (in_array('Super Admin', $roles, true) && Auth::getUser()->hasRole('Super Admin'))
  131. || Auth::getUser()->hasRole('Super Admin'))) {
  132. $user->assignRole($roles);
  133. }
  134. if ($user) {
  135. // 写入用户流量变动记录
  136. Helpers::addUserTrafficModifyLog($user->id, null, 0, $data['transfer_enable'], '后台手动添加用户');
  137. return Response::json(['status' => 'success', 'message' => '添加成功']);
  138. }
  139. } catch (Exception $e) {
  140. Log::error('添加用户错误:'.$e->getMessage());
  141. return Response::json(['status' => 'fail', 'message' => $e->getMessage()]);
  142. }
  143. return Response::json(['status' => 'fail', 'message' => '添加失败']);
  144. }
  145. // 编辑账号页面
  146. public function edit(User $user)
  147. {
  148. if (Auth::getUser()->hasRole('Super Admin')) {
  149. $roles = Role::all()->pluck('description', 'name');
  150. } elseif (Auth::getUser()->hasPermissionTo('give roles')) {
  151. $roles = Auth::getUser()->roles();
  152. }
  153. return view('admin.user.info', [
  154. 'user' => $user->load('inviter:id,email'),
  155. 'levels' => Level::orderBy('level')->get(),
  156. 'userGroups' => UserGroup::orderBy('id')->get(),
  157. 'roles' => $roles ?? [],
  158. ]);
  159. }
  160. // 编辑账号
  161. public function update(UserUpdateRequest $request, User $user)
  162. {
  163. try {
  164. $data = $request->except('_token', 'password', 'uuid', 'password', 'roles');
  165. $data['passwd'] = $request->input('passwd') ?? Str::random();
  166. $data['vmess_id'] = $request->input('uuid') ?? Str::uuid();
  167. $data['transfer_enable'] *= GB;
  168. $data['enable'] = $data['status'] < 0 ? 0 : $data['enable'];
  169. $data['expired_at'] = $data['expired_at'] ?? date('Y-m-d', strtotime('+365 days'));
  170. $data['remark'] = str_replace(['atob', 'eval'], '', $data['remark']);
  171. // 只有超级管理员才能赋予超级管理员
  172. $roles = $request->input('roles') ?? [];
  173. if ($roles && (Auth::getUser()->hasPermissionTo('give roles') || (in_array('Super Admin', $roles, true) && Auth::getUser()->hasRole('Super Admin')) ||
  174. Auth::getUser()->hasRole('Super Admin'))) {
  175. $user->syncRoles($roles);
  176. }
  177. // Input checking for dummy
  178. if ($data['enable'] === '1') {
  179. if ($data['status'] === '-1' || $data['transfer_enable'] === 0 || $data['expired_at'] < date('Y-m-d')) {
  180. $data['enable'] = 0;
  181. }
  182. }
  183. // 非演示环境才可以修改管理员密码
  184. $password = $request->input('password');
  185. if (! empty($password) && ! (env('APP_DEMO') && $user->id === 1)) {
  186. $data['password'] = $password;
  187. }
  188. // 写入用户流量变动记录
  189. if ($user->transfer_enable !== $data['transfer_enable']) {
  190. Helpers::addUserTrafficModifyLog($user->id, null, $user->transfer_enable, $data['transfer_enable'], '后台手动编辑用户');
  191. }
  192. if ($user->update($data)) {
  193. return Response::json(['status' => 'success', 'message' => '编辑成功']);
  194. }
  195. } catch (Exception $e) {
  196. Log::error('编辑用户信息异常:'.$e->getMessage());
  197. return Response::json(['status' => 'fail', 'message' => '编辑用户信息错误:'.$e->getMessage()]);
  198. }
  199. return Response::json(['status' => 'fail', 'message' => '编辑失败']);
  200. }
  201. // 删除用户
  202. public function destroy(User $user)
  203. {
  204. if ($user->id === 1) {
  205. return Response::json(['status' => 'fail', 'message' => '系统管理员不可删除']);
  206. }
  207. try {
  208. if ($user->delete()) {
  209. return Response::json(['status' => 'success', 'message' => '删除成功']);
  210. }
  211. } catch (Exception $e) {
  212. Log::error('删除用户信息异常:'.$e->getMessage());
  213. return Response::json(['status' => 'fail', 'message' => '删除失败'.$e->getMessage()]);
  214. }
  215. return Response::json(['status' => 'fail', 'message' => '删除失败']);
  216. }
  217. // 批量生成账号
  218. public function batchAddUsers()
  219. {
  220. $preset = ['transfer_enable' => 1024 * GB, 'expired_at' => date('Y-m-d', strtotime('+365 days'))];
  221. try {
  222. for ($i = 0; $i < (int) request('amount', 1); $i++) {
  223. $user = Helpers::addUser(Str::random(8).'@auto.generate', Str::random(), 1024 * GB, 365);
  224. // 写入用户流量变动记录
  225. Helpers::addUserTrafficModifyLog($user->id, null, 0, 1024 * GB, '后台批量生成用户');
  226. }
  227. return Response::json(['status' => 'success', 'message' => '批量生成账号成功']);
  228. } catch (Exception $e) {
  229. return Response::json(['status' => 'fail', 'message' => '批量生成账号失败:'.$e->getMessage()]);
  230. }
  231. }
  232. // 转换成某个用户的身份
  233. public function switchToUser(User $user): JsonResponse
  234. {
  235. // 存储当前管理员ID,并将当前登录信息改成要切换的用户的身份信息
  236. Session::put('admin', Auth::id());
  237. Session::put('user', $user->id);
  238. return Response::json(['status' => 'success', 'message' => '身份切换成功']);
  239. }
  240. // 重置用户流量
  241. public function resetTraffic(User $user): JsonResponse
  242. {
  243. try {
  244. $user->update(['u' => 0, 'd' => 0]);
  245. } catch (Exception $e) {
  246. Log::error('流量重置失败:'.$e->getMessage());
  247. return Response::json(['status' => 'fail', 'message' => '流量重置失败']);
  248. }
  249. return Response::json(['status' => 'success', 'message' => '流量重置成功']);
  250. }
  251. // 操作用户余额
  252. public function handleUserCredit(Request $request, User $user): JsonResponse
  253. {
  254. $amount = (int) $request->input('amount');
  255. if (empty($amount)) {
  256. return Response::json(['status' => 'fail', 'message' => '充值异常']);
  257. }
  258. // 加减余额
  259. if ($user->updateCredit($amount)) {
  260. Helpers::addUserCreditLog($user->id, null, $user->credit, $user->credit + $amount, $amount, '后台手动充值'); // 写入余额变动日志
  261. return Response::json(['status' => 'success', 'message' => '充值成功']);
  262. }
  263. return Response::json(['status' => 'fail', 'message' => '充值失败']);
  264. }
  265. // 导出配置信息
  266. public function export(User $user)
  267. {
  268. return view('admin.user.export', [
  269. 'user' => $user,
  270. 'nodeList' => Node::whereStatus(1)->orderByDesc('sort')->orderBy('id')->paginate(15)->appends(\request('page')),
  271. ]);
  272. }
  273. public function exportProxyConfig(Request $request, User $user): JsonResponse
  274. {
  275. $node = Node::find($request->input('id'));
  276. if ($node->type === 1) {
  277. if ($node->compatible) {
  278. $proxyType = 'SS';
  279. } else {
  280. $proxyType = 'SSR';
  281. }
  282. } else {
  283. $proxyType = 'V2Ray';
  284. }
  285. $data = $this->getUserNodeInfo($user->id, $node->id, $request->input('type') !== 'text' ? 0 : 1);
  286. return Response::json(['status' => 'success', 'data' => $data, 'title' => $proxyType]);
  287. }
  288. }