-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_manager.py
More file actions
187 lines (152 loc) · 5.3 KB
/
ip_manager.py
File metadata and controls
187 lines (152 loc) · 5.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""IP whitelist and blacklist management."""
import json
import logging
from pathlib import Path
from typing import Set, Optional
logger = logging.getLogger(__name__)
class IPManager:
"""Manages IP whitelist and blacklist."""
def __init__(self, config_path: str = "ip_lists.json"):
"""
Initialize IP manager.
Args:
config_path: Path to JSON file storing whitelist/blacklist
"""
self.config_path = Path(config_path)
self.whitelist: Set[str] = set()
self.blacklist: Set[str] = set()
self._load_lists()
def _load_lists(self):
"""Load whitelist and blacklist from file."""
if self.config_path.exists():
try:
with open(self.config_path, 'r', encoding='utf-8') as f:
data = json.load(f)
self.whitelist = set(data.get('whitelist', []))
self.blacklist = set(data.get('blacklist', []))
logger.info(f"Loaded {len(self.whitelist)} whitelisted and {len(self.blacklist)} blacklisted IPs")
except (json.JSONDecodeError, IOError) as e:
logger.warning(f"Error loading IP lists: {e}. Starting with empty lists.")
self.whitelist = set()
self.blacklist = set()
else:
# Create empty file
self._save_lists()
def _save_lists(self):
"""Save whitelist and blacklist to file."""
try:
data = {
'whitelist': sorted(list(self.whitelist)),
'blacklist': sorted(list(self.blacklist))
}
with open(self.config_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
logger.debug(f"Saved IP lists to {self.config_path}")
except IOError as e:
logger.error(f"Error saving IP lists: {e}")
def add_whitelist(self, ip: str) -> bool:
"""
Add IP to whitelist.
Args:
ip: IP address to whitelist
Returns:
True if added, False if already exists
"""
if ip in self.whitelist:
return False
self.whitelist.add(ip)
# Remove from blacklist if present
self.blacklist.discard(ip)
self._save_lists()
logger.info(f"Added {ip} to whitelist")
return True
def add_blacklist(self, ip: str) -> bool:
"""
Add IP to blacklist.
Args:
ip: IP address to blacklist
Returns:
True if added, False if already exists
"""
if ip in self.blacklist:
return False
self.blacklist.add(ip)
# Remove from whitelist if present
self.whitelist.discard(ip)
self._save_lists()
logger.info(f"Added {ip} to blacklist")
return True
def remove_whitelist(self, ip: str) -> bool:
"""
Remove IP from whitelist.
Args:
ip: IP address to remove
Returns:
True if removed, False if not found
"""
if ip in self.whitelist:
self.whitelist.remove(ip)
self._save_lists()
logger.info(f"Removed {ip} from whitelist")
return True
return False
def remove_blacklist(self, ip: str) -> bool:
"""
Remove IP from blacklist.
Args:
ip: IP address to remove
Returns:
True if removed, False if not found
"""
if ip in self.blacklist:
self.blacklist.remove(ip)
self._save_lists()
logger.info(f"Removed {ip} from blacklist")
return True
return False
def is_whitelisted(self, ip: Optional[str]) -> bool:
"""
Check if IP is whitelisted.
Args:
ip: IP address to check
Returns:
True if whitelisted, False otherwise
"""
if not ip:
return False
return ip in self.whitelist
def is_blacklisted(self, ip: Optional[str]) -> bool:
"""
Check if IP is blacklisted.
Args:
ip: IP address to check
Returns:
True if blacklisted, False otherwise
"""
if not ip:
return False
return ip in self.blacklist
def should_ignore(self, ip: Optional[str]) -> bool:
"""
Check if IP should be ignored (whitelisted).
Args:
ip: IP address to check
Returns:
True if should be ignored, False otherwise
"""
return self.is_whitelisted(ip)
def should_block(self, ip: Optional[str]) -> bool:
"""
Check if IP should be blocked (blacklisted).
Args:
ip: IP address to check
Returns:
True if should be blocked, False otherwise
"""
return self.is_blacklisted(ip)
def get_whitelist(self) -> list:
"""Get list of whitelisted IPs."""
return sorted(list(self.whitelist))
def get_blacklist(self) -> list:
"""Get list of blacklisted IPs."""
return sorted(list(self.blacklist))