AutoBanUserJob.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Models\Config;
  5. use App\Http\Models\UserBanLog;
  6. use App\Http\Models\User;
  7. use App\Http\Models\UserTrafficHourly;
  8. use Log;
  9. class AutoBanUserJob extends Command
  10. {
  11. protected $signature = 'autoBanUserJob';
  12. protected $description = '自动封禁用户';
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. }
  17. public function handle()
  18. {
  19. $config = $this->systemConfig();
  20. // 封禁24小时内流量异常账号
  21. if ($config['is_traffic_ban']) {
  22. $userList = User::query()->where('status', '>=', 0)->where('enable', 1)->where('ban_time', '>=', 0)->get();
  23. if (!$userList->isEmpty()) {
  24. foreach ($userList as $user) {
  25. $time = date('Y-m-d H:i:s', time() - 24 * 60 * 60);
  26. $totalTraffic = UserTrafficHourly::query()->where('user_id', $user->id)->where('node_id', 0)->where('created_at', '>=', $time)->sum('total');
  27. if ($totalTraffic >= ($config['traffic_ban_value'] * 1024 * 1024 * 1024)) {
  28. $ban_time = strtotime(date('Y-m-d H:i:s', strtotime("+" . $config['traffic_ban_time'] . " minutes")));
  29. User::query()->where('id', $user->id)->update(['enable' => 0, 'ban_time' => $ban_time]);
  30. // 写入日志
  31. $this->log($user->id, $config['traffic_ban_time'], '【自动封禁】-24小时内流量异常');
  32. }
  33. }
  34. }
  35. }
  36. Log::info('定时任务:' . $this->description);
  37. }
  38. // 系统配置
  39. private function systemConfig()
  40. {
  41. $config = Config::query()->get();
  42. $data = [];
  43. foreach ($config as $vo) {
  44. $data[$vo->name] = $vo->value;
  45. }
  46. return $data;
  47. }
  48. private function log($user_id, $minutes, $desc)
  49. {
  50. $log = new UserBanLog();
  51. $log->user_id = $user_id;
  52. $log->minutes = $minutes;
  53. $log->desc = $desc;
  54. $log->save();
  55. }
  56. }