111 lines
4.0 KiB
Python
111 lines
4.0 KiB
Python
import os
|
|
import sys
|
|
import django
|
|
import json
|
|
|
|
# Set up Django environment
|
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
|
|
django.setup()
|
|
|
|
from django.test import Client
|
|
from django.contrib.auth import get_user_model
|
|
from django.urls import get_resolver, URLPattern, URLResolver
|
|
|
|
def get_all_urls(urlpatterns, prefix=''):
|
|
urls = []
|
|
for pattern in urlpatterns:
|
|
if isinstance(pattern, URLPattern):
|
|
# Try to build a valid URL by replacing common parameters
|
|
url = prefix + str(pattern.pattern)
|
|
url = url.replace('<int:pk>', '1')
|
|
url = url.replace('<int:candidate_pk>', '1')
|
|
url = url.replace('<int:po_pk>', '1')
|
|
url = url.replace('<str:action>', 'approve')
|
|
url = url.replace('^', '').replace('$', '')
|
|
urls.append(url)
|
|
elif isinstance(pattern, URLResolver):
|
|
urls.extend(get_all_urls(pattern.url_patterns, prefix + str(pattern.pattern)))
|
|
return urls
|
|
|
|
def run_analysis():
|
|
User = get_user_model()
|
|
# Try to get an existing admin or any user, or create a temporary one
|
|
user = User.objects.filter(is_superuser=True).first() or User.objects.first()
|
|
created_user = False
|
|
if not user:
|
|
user = User.objects.create_superuser('test_admin', 'admin@example.com', 'password123')
|
|
created_user = True
|
|
|
|
client = Client()
|
|
client.force_login(user)
|
|
|
|
resolver = get_resolver()
|
|
urls = get_all_urls(resolver.url_patterns)
|
|
|
|
# Filter out admin, media, and tax_api endpoints
|
|
urls = [u for u in urls if not u.startswith('admin/') and not u.startswith('media/') and 'tax_api' not in u]
|
|
|
|
# Prepend / to urls if needed
|
|
urls = ['/' + u if not u.startswith('/') else u for u in urls]
|
|
|
|
results = []
|
|
|
|
for url in urls:
|
|
# Ignore endpoints that aren't strictly GET or testable by simple GET
|
|
if url == '/logout/':
|
|
continue
|
|
|
|
try:
|
|
response = client.get(url)
|
|
status_code = response.status_code
|
|
content_type = response.headers.get('Content-Type', '')
|
|
|
|
snippet = ""
|
|
if 'application/json' in content_type:
|
|
try:
|
|
data = response.json()
|
|
snippet = json.dumps(data)[:150] + ("..." if len(json.dumps(data)) > 150 else "")
|
|
except Exception:
|
|
snippet = response.content.decode('utf-8', errors='ignore')[:150]
|
|
else:
|
|
snippet = response.content.decode('utf-8', errors='ignore')[:150].replace('\n', ' ').strip()
|
|
if len(response.content) > 150:
|
|
snippet += "..."
|
|
|
|
results.append({
|
|
'url': url,
|
|
'status_code': status_code,
|
|
'snippet': snippet,
|
|
'content_type': content_type
|
|
})
|
|
except Exception as e:
|
|
results.append({
|
|
'url': url,
|
|
'status_code': 'Error',
|
|
'snippet': str(e),
|
|
'content_type': 'N/A'
|
|
})
|
|
|
|
# Cleanup user if we created it
|
|
if created_user:
|
|
user.delete()
|
|
|
|
return results
|
|
|
|
if __name__ == '__main__':
|
|
print("Starting endpoints analysis...")
|
|
results = run_analysis()
|
|
|
|
artifact_path = "/home/cheerry/.gemini/antigravity/brain/5fe9c8b0-cf58-4038-b407-4851abf7278b/django_endpoints.md"
|
|
|
|
with open(artifact_path, "w", encoding="utf-8") as f:
|
|
f.write("# Django Endpoints Analysis\n\n")
|
|
f.write("| Endpoint | Status Code | Content Type | Snippet |\n")
|
|
f.write("|----------|-------------|--------------|---------|\n")
|
|
for res in results:
|
|
# Escape pipe symbols for markdown tables
|
|
snippet = res['snippet'].replace('|', '\\|').replace('\n', ' ')
|
|
f.write(f"| `{res['url']}` | {res['status_code']} | {res['content_type']} | `{snippet}` |\n")
|
|
|
|
print(f"Analysis successfully saved to {artifact_path}")
|