123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace App\DataApiNew\Models;
- use Illuminate\Database\Eloquent\SoftDeletes;
- use Illuminate\Database\Eloquent\Model;
- use Dcat\Admin\Traits\HasDateTimeFormatter;
- use Illuminate\Support\Facades\Cache;
- // 黑名单表
- class BlackList extends Model
- {
- use HasDateTimeFormatter;
- protected $table = 'black_list';
- protected $dateFormat = 'Y-m-d H:i:s';
-
- // 表字段
- protected $fillable = [
- 'id',
- 'type', // 类型 1拉黑
- 'phone', // 手机号
- 'user_id', // 用户id
- 'status', // 状态
- 'created_at', // 创建时间
- 'updated_at', // 更新时间
- 'deleted_at', // 删除时间
- 'remark', // 备注
- 'ip', // IP地址
- ];
- // 查询字段
- public static $selectFields = [
- 'id',
- 'type', // 类型 1拉黑
- 'phone', // 手机号
- 'user_id', // 用户id
- 'created_at', // 创建时间
- 'remark', // 备注
- 'ip', // IP地址
- ];
- // 类型
- const TYPE_USER = 1; // 用户黑名单
- const TYPE_IP = 2; // IP黑名单
- public $type = [
- self::TYPE_USER => '用户黑名单',
- self::TYPE_IP => 'IP黑名单',
- ];
- // 检查用户是否在黑名单
- public static function checkUser($user_id = null, $phone = null)
- {
- $blackList = self::query()->where('type',self::TYPE_USER);
-
- if ($user_id) {
- $blackList = $blackList->where('user_id', $user_id);
- }
- if ($phone) {
- if($user_id){
- $blackList = $blackList->orWhere('phone', $phone);
- }else{
- $blackList = $blackList->where('phone', $phone);
- }
- }
- return $blackList->exists();
- }
- // 检查IP是否在黑名单
- public static function checkIp($ip = null)
- {
- // 先从缓存中查找黑名单
- $blacklist = Cache::get('ip_blacklist');
- // 如果缓存不存在,则从数据库获取并更新缓存
- if (!$blacklist) {
- $blacklist = self::updateCache();
- }
- // 检查IP是否在黑名单中
- return in_array($ip, $blacklist);
- }
- // ip加入黑名单
- public static function addIp($ip = null)
- {
- if (!$ip) return false;
- // 更新数据库
- $info = self::query()->where('type', self::TYPE_IP)->where('ip', $ip)->first();
- if (!$info){
- self::create([
- 'type' => self::TYPE_IP,
- 'ip' => $ip,
- ]);
- }
-
- // 更新缓存
- self::updateCache();
- return true;
- }
- // 更新缓存
- public static function updateCache()
- {
- $blacklist = self::query()->where('type', self::TYPE_IP)->pluck('ip')->toArray();
- Cache::put('ip_blacklist', $blacklist, now()->addMinutes(60));
- return $blacklist;
- }
- }
|