-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_validators.py
More file actions
250 lines (185 loc) · 6.54 KB
/
Copy pathrequest_validators.py
File metadata and controls
250 lines (185 loc) · 6.54 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""
Input validation utilities for URL shortener
"""
import re
from typing import Optional, Dict, Any
from functools import wraps
from flask import request, jsonify
import validators as url_validators
from config import get_config
config = get_config()
class ValidationError(Exception):
"""Custom validation error"""
def __init__(self, message: str, field: str = None):
self.message = message
self.field = field
super().__init__(self.message)
def validate_url(url: str) -> bool:
"""
Validate URL format and length
Args:
url: URL string to validate
Returns:
True if valid
Raises:
ValidationError: If URL is invalid
"""
if not url:
raise ValidationError("URL is required", "url")
if len(url) > config.MAX_URL_LENGTH:
raise ValidationError(
f"URL too long. Maximum length is {config.MAX_URL_LENGTH} characters",
"url"
)
if not url_validators.url(url):
raise ValidationError("Invalid URL format", "url")
# Check for common malicious patterns
malicious_patterns = [
r'javascript:',
r'data:',
r'vbscript:',
r'file:',
]
for pattern in malicious_patterns:
if re.search(pattern, url, re.IGNORECASE):
raise ValidationError("URL contains potentially malicious content", "url")
return True
def validate_short_code(code: str) -> bool:
"""
Validate short code format
Args:
code: Short code to validate
Returns:
True if valid
Raises:
ValidationError: If code is invalid
"""
if not code:
return True # Optional field
if len(code) < 4 or len(code) > 20:
raise ValidationError("Short code must be between 4 and 20 characters", "code")
# Only allow alphanumeric, hyphens, and underscores
if not re.match(r'^[a-zA-Z0-9_-]+$', code):
raise ValidationError(
"Short code can only contain letters, numbers, hyphens, and underscores",
"code"
)
# Reserved codes
reserved = ['admin', 'api', 'health', 'metrics', 'stats', 'analytics', 'auth', 'login', 'signup', 'logout']
if code.lower() in reserved:
raise ValidationError("This short code is reserved", "code")
return True
def validate_username(username: str) -> bool:
"""
Validate username format
Args:
username: Username to validate
Returns:
True if valid
Raises:
ValidationError: If username is invalid
"""
if not username:
raise ValidationError("Username is required", "username")
if len(username) < 3 or len(username) > 50:
raise ValidationError("Username must be between 3 and 50 characters", "username")
if not re.match(r'^[a-zA-Z0-9_-]+$', username):
raise ValidationError(
"Username can only contain letters, numbers, hyphens, and underscores",
"username"
)
return True
def validate_password(password: str) -> bool:
"""
Validate password strength
Args:
password: Password to validate
Returns:
True if valid
Raises:
ValidationError: If password is invalid
"""
if not password:
raise ValidationError("Password is required", "password")
if len(password) < 8:
raise ValidationError("Password must be at least 8 characters long", "password")
if len(password) > 128:
raise ValidationError("Password is too long", "password")
# Check for at least one uppercase, one lowercase, and one number
if not re.search(r'[A-Z]', password):
raise ValidationError("Password must contain at least one uppercase letter", "password")
if not re.search(r'[a-z]', password):
raise ValidationError("Password must contain at least one lowercase letter", "password")
if not re.search(r'[0-9]', password):
raise ValidationError("Password must contain at least one number", "password")
return True
def validate_request_json(*required_fields):
"""
Decorator to validate JSON request body
Usage:
@validate_request_json('username', 'password')
def login():
...
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 400
data = request.get_json()
if not data:
return jsonify({"error": "Request body is required"}), 400
# Check required fields
missing_fields = []
for field in required_fields:
if field not in data or not data[field]:
missing_fields.append(field)
if missing_fields:
return jsonify({
"error": "Missing required fields",
"fields": missing_fields
}), 400
return f(*args, **kwargs)
return decorated_function
return decorator
def sanitize_input(text: str, max_length: int = 1000) -> str:
"""
Sanitize user input to prevent XSS
Args:
text: Input text to sanitize
max_length: Maximum allowed length
Returns:
Sanitized text
"""
if not text:
return ""
# Truncate to max length
text = text[:max_length]
# Remove null bytes
text = text.replace('\x00', '')
# Strip leading/trailing whitespace
text = text.strip()
return text
def validate_pagination_params(page: Optional[int] = None, per_page: Optional[int] = None) -> Dict[str, int]:
"""
Validate and normalize pagination parameters
Args:
page: Page number (1-indexed)
per_page: Items per page
Returns:
Dict with validated page and per_page
"""
# Default values
page = page or 1
per_page = per_page or 20
# Validate page
if page < 1:
raise ValidationError("Page must be >= 1", "page")
if page > 10000:
raise ValidationError("Page number too large", "page")
# Validate per_page
if per_page < 1:
raise ValidationError("per_page must be >= 1", "per_page")
if per_page > 100:
raise ValidationError("per_page cannot exceed 100", "per_page")
return {"page": page, "per_page": per_page}