BlackList.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\DataApiNew\Models;
  3. use Illuminate\Database\Eloquent\SoftDeletes;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Dcat\Admin\Traits\HasDateTimeFormatter;
  6. use Illuminate\Support\Facades\Cache;
  7. // 黑名单表
  8. class BlackList extends Model
  9. {
  10. use HasDateTimeFormatter;
  11. protected $table = 'black_list';
  12. protected $dateFormat = 'Y-m-d H:i:s';
  13. // 表字段
  14. protected $fillable = [
  15. 'id',
  16. 'type', // 类型 1拉黑
  17. 'phone', // 手机号
  18. 'user_id', // 用户id
  19. 'status', // 状态
  20. 'created_at', // 创建时间
  21. 'updated_at', // 更新时间
  22. 'deleted_at', // 删除时间
  23. 'remark', // 备注
  24. 'ip', // IP地址
  25. ];
  26. // 查询字段
  27. public static $selectFields = [
  28. 'id',
  29. 'type', // 类型 1拉黑
  30. 'phone', // 手机号
  31. 'user_id', // 用户id
  32. 'created_at', // 创建时间
  33. 'remark', // 备注
  34. 'ip', // IP地址
  35. ];
  36. // 类型
  37. const TYPE_USER = 1; // 用户黑名单
  38. const TYPE_IP = 2; // IP黑名单
  39. public $type = [
  40. self::TYPE_USER => '用户黑名单',
  41. self::TYPE_IP => 'IP黑名单',
  42. ];
  43. // 检查用户是否在黑名单
  44. public static function checkUser($user_id = null, $phone = null)
  45. {
  46. $blackList = self::query()->where('type',self::TYPE_USER);
  47. if ($user_id) {
  48. $blackList = $blackList->where('user_id', $user_id);
  49. }
  50. if ($phone) {
  51. if($user_id){
  52. $blackList = $blackList->orWhere('phone', $phone);
  53. }else{
  54. $blackList = $blackList->where('phone', $phone);
  55. }
  56. }
  57. return $blackList->exists();
  58. }
  59. // 检查IP是否在黑名单
  60. public static function checkIp($ip = null)
  61. {
  62. // 先从缓存中查找黑名单
  63. $blacklist = Cache::get('ip_blacklist');
  64. // 如果缓存不存在,则从数据库获取并更新缓存
  65. if (!$blacklist) {
  66. $blacklist = self::updateCache();
  67. }
  68. // 检查IP是否在黑名单中
  69. return in_array($ip, $blacklist);
  70. }
  71. // ip加入黑名单
  72. public static function addIp($ip = null)
  73. {
  74. if (!$ip) return false;
  75. // 更新数据库
  76. $info = self::query()->where('type', self::TYPE_IP)->where('ip', $ip)->first();
  77. if (!$info){
  78. self::create([
  79. 'type' => self::TYPE_IP,
  80. 'ip' => $ip,
  81. ]);
  82. }
  83. // 更新缓存
  84. self::updateCache();
  85. return true;
  86. }
  87. // 更新缓存
  88. public static function updateCache()
  89. {
  90. $blacklist = self::query()->where('type', self::TYPE_IP)->pluck('ip')->toArray();
  91. Cache::put('ip_blacklist', $blacklist, now()->addMinutes(60));
  92. return $blacklist;
  93. }
  94. }