auth.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import requests
  2. LOGIN_URL = "http://localhost:7777/user/login"
  3. EDIT_MILESTONE_URL = "http://localhost:7777/setyotontowi/experiments/milestones/1/edit"
  4. session = requests.Session()
  5. def login(username, password):
  6. """Log in and store session cookies."""
  7. print("Logging in...")
  8. payload = {
  9. "user_name": username,
  10. "password": password
  11. }
  12. response = session.post(LOGIN_URL, data=payload)
  13. if response.status_code == 200:
  14. print("Login successful.")
  15. return True
  16. else:
  17. print(f"Login failed: {response.status_code} - {response.text}")
  18. return False
  19. def get_csrf_token():
  20. """Fetch CSRF token from the edit milestone page."""
  21. print("Fetching CSRF token...")
  22. response = session.get(EDIT_MILESTONE_URL)
  23. if response.status_code == 200:
  24. token = extract_csrf_token(response.text)
  25. if token:
  26. print(f"CSRF token obtained: {token}")
  27. return token
  28. else:
  29. print("Failed to extract CSRF token.")
  30. return None
  31. elif response.status_code == 401: # Unauthorized → Need to re-login
  32. print("Session expired, re-logging in...")
  33. return None
  34. else:
  35. print(f"Failed to get CSRF token: {response.status_code} - {response.text}")
  36. return None
  37. def extract_csrf_token(html):
  38. """Extract CSRF token from HTML using regex."""
  39. import re
  40. match = re.search(r'name="_csrf" value="(.*?)"', html)
  41. if match:
  42. return match.group(1)
  43. return None