auth.py 1.5 KB

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