-
Notifications
You must be signed in to change notification settings - Fork 0
Authentication
Understanding login, logout, and session management in strava-cz-python.
The simplest way to login is during client initialization:
from strava_cz import StravaCZ
strava = StravaCZ(
username="your.username",
password="YourPassword123",
canteen_number="3753" # Required!
)The client automatically logs in when all three parameters are provided.
You can also create a client without credentials and login later:
strava = StravaCZ() # Create client without login
# Login later
strava.login(
username="your.username",
password="YourPassword123",
canteen_number="3753"
)The canteen_number is a required parameter that identifies your specific school canteen. You can find it:
- From Strava.cz URL: When logged into Strava.cz, check the URL or login page
- From your school: Ask your canteen administrator
- Common format: Usually a 4-digit number (e.g., "3753")
After successful login, user information is available through the user object:
strava = StravaCZ(username="...", password="...", canteen_number="3753")
# Access user information
print(strava.user.username) # Login username
print(strava.user.full_name) # Full name (e.g., "Vojtěch Nerad")
print(strava.user.email) # Email address
print(strava.user.balance) # Account balance (float)
print(strava.user.currency) # Currency symbol (e.g., "Kč")
print(strava.user.canteen_name) # Full canteen name
print(strava.user.id) # User ID
print(strava.user.is_logged_in) # Login status (bool)The User object has a nice string representation:
print(strava.user)Output:
User information:
- Vojtěch Nerad (vojtech.nerad)
- Email: muj.email@gmail.com
- Balance: 0.00 Kč
- Canteen: Školní jídelna, Praha 5 - Smíchov, Štefánikova 11/235
Behind the scenes, the library manages session data:
strava.user.sid # Session ID - used for authentication
strava.user.s5url # Web service endpoint URLThese are automatically populated during login and used in subsequent API requests. You don't need to manage them manually.
if strava.user.is_logged_in:
print("User is logged in")
else:
print("User is not logged in")Sessions are not persisted between program runs. Each time you run your script, you need to login again.
# Session is not saved
strava = StravaCZ(username="...", password="...", canteen_number="3753")
# ... do work ...
strava.logout()
# Next run - need to login again
strava = StravaCZ(username="...", password="...", canteen_number="3753")strava.logout()This:
- Ends the server session
- Clears user data
- Resets the menu
- Returns
Trueon success
if strava.user.is_logged_in:
strava.logout()
print("Logged out successfully")
else:
print("Already logged out")Calling logout() when already logged out is safe and returns True immediately.
The AuthenticationError exception is raised for login-related issues:
from strava_cz import StravaCZ, AuthenticationError
try:
strava = StravaCZ(
username="wrong_user",
password="wrong_pass",
canteen_number="3753"
)
except AuthenticationError as e:
print(f"Login failed: {e}")Common authentication errors:
- Incorrect credentials: Wrong username or password
- Invalid canteen number: Canteen doesn't exist
- Already logged in: Trying to login when already authenticated
- Not logged in: Trying to access data without logging in first
try:
strava = StravaCZ(username="user") # Missing password
except ValueError as e:
print(f"Error: {e}") # "Username and password are required for login"
try:
strava = StravaCZ(username="user", password="pass") # Missing canteen_number
except ValueError as e:
print(f"Error: {e}") # "Canteen number is required for login"Most operations require authentication:
strava = StravaCZ() # Not logged in
try:
strava.menu.fetch()
except AuthenticationError as e:
print(f"Error: {e}") # "User not logged in"Don't hardcode credentials in your code:
import os
from dotenv import load_dotenv
from strava_cz import StravaCZ
load_dotenv()
strava = StravaCZ(
username=os.getenv("STRAVA_USERNAME"),
password=os.getenv("STRAVA_PASSWORD"),
canteen_number=os.getenv("STRAVA_CANTEEN_NUMBER")
)Use a try-finally block to ensure logout:
strava = None
try:
strava = StravaCZ(username="...", password="...", canteen_number="3753")
# Do work...
strava.menu.fetch()
strava.menu.print()
finally:
if strava and strava.user.is_logged_in:
strava.logout()Create a wrapper for automatic cleanup:
class StravaContext:
def __init__(self, username, password, canteen_number):
self.username = username
self.password = password
self.canteen_number = canteen_number
self.strava = None
def __enter__(self):
self.strava = StravaCZ(
username=self.username,
password=self.password,
canteen_number=self.canteen_number
)
return self.strava
def __exit__(self, exc_type, exc_val, exc_tb):
if self.strava and self.strava.user.is_logged_in:
self.strava.logout()
return False
# Usage
with StravaContext("user", "pass", "3753") as strava:
strava.menu.fetch()
strava.menu.print()
# Automatically logs outfrom strava_cz import StravaCZ, AuthenticationError
def safe_login(username, password, canteen_number, max_retries=3):
for attempt in range(max_retries):
try:
strava = StravaCZ(
username=username,
password=password,
canteen_number=canteen_number
)
return strava
except AuthenticationError as e:
if attempt < max_retries - 1:
print(f"Login attempt {attempt + 1} failed. Retrying...")
else:
print(f"Login failed after {max_retries} attempts: {e}")
raise
return NoneUnderstanding the authentication flow:
- Initialization: Client created with credentials
-
Login Request: POST to
/api/loginendpoint with credentials -
Session Creation: Server returns
sid(session ID) ands5url -
Authenticated Requests: All subsequent requests include
sidands5url -
Logout Request: POST to
/api/logOutendpoint - Session Termination: Server invalidates the session
- Never commit credentials to version control
- Use environment variables or secure credential storage
- Be cautious when sharing code or logs
- Sessions are temporary and expire after inactivity
- Always logout when done to invalidate the session
- Don't share your
sid- it provides full access to your account
- Learn about the Menu System
- Understand User Class in detail
- Explore Error Handling strategies