namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class UserApiKey extends Model { use HasFactory; protected $table = 'user_api_keys'; protected $fillable = [ 'user_id', 'name', 'key', 'secret', 'permissions', 'ip_whitelist', 'last_used_at', 'expires_at', 'status', ]; protected $casts = [ 'permissions' => 'array', 'ip_whitelist' => 'array', 'last_used_at' => 'datetime', 'expires_at' => 'datetime', ]; protected $hidden = [ 'secret', ]; // Relationships public function user() { return $this->belongsTo(User::class); } public function logs() { return $this->hasMany(ApiLog::class, 'api_key_id'); } // Scopes public function scopeActive($query) { return $query->where('status', 'active'); } public function scopeExpired($query) { return $query->where('expires_at', '<', now()); } public function scopeValid($query) { return $query->where('status', 'active') ->where(function($q) { $q->whereNull('expires_at') ->orWhere('expires_at', '>', now()); }); } // Methods public function isActive() { return $this->status === 'active' && ($this->expires_at === null || $this->expires_at > now()); } public function updateLastUsed() { $this->update(['last_used_at' => now()]); } public function hasPermission($permission) { return in_array($permission, $this->permissions ?? []); } public function isIpAllowed($ip) { if (empty($this->ip_whitelist)) { return true; } return in_array($ip, $this->ip_whitelist); } public function generateKey() { $this->key = 'RGSMM-' . strtoupper(bin2hex(random_bytes(16))); return $this->key; } public function generateSecret() { $this->secret = bin2hex(random_bytes(32)); return $this->secret; } }