Skip to content

Authentication

jsem-nerad edited this page Nov 12, 2025 · 1 revision

Authentication

Understanding login, logout, and session management in strava-cz-python.

Login Process

Basic Login

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.

Manual Login

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"
)

Finding Your Canteen Number

The canteen_number is a required parameter that identifies your specific school canteen. You can find it:

  1. From Strava.cz URL: When logged into Strava.cz, check the URL or login page
  2. From your school: Ask your canteen administrator
  3. Common format: Usually a 4-digit number (e.g., "3753")

User Data

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)

User Object String Representation

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

Session Management

Session Identifiers

Behind the scenes, the library manages session data:

strava.user.sid      # Session ID - used for authentication
strava.user.s5url    # Web service endpoint URL

These are automatically populated during login and used in subsequent API requests. You don't need to manage them manually.

Checking Login Status

if strava.user.is_logged_in:
    print("User is logged in")
else:
    print("User is not logged in")

Session Persistence

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")

Logout

Basic Logout

strava.logout()

This:

  • Ends the server session
  • Clears user data
  • Resets the menu
  • Returns True on success

Checking If Already Logged Out

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.

Error Handling

Authentication Errors

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

Missing Credentials

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"

Checking Login Before Operations

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"

Best Practices

1. Use Environment Variables

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")
)

2. Always Logout

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()

3. Use Context Manager Pattern

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 out

4. Handle Authentication Errors

from 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 None

API Request Flow

Understanding the authentication flow:

  1. Initialization: Client created with credentials
  2. Login Request: POST to /api/login endpoint with credentials
  3. Session Creation: Server returns sid (session ID) and s5url
  4. Authenticated Requests: All subsequent requests include sid and s5url
  5. Logout Request: POST to /api/logOut endpoint
  6. Session Termination: Server invalidates the session

Security Considerations

Password Storage

⚠️ Important: Passwords are sent as plaintext to the Strava.cz API. This is a limitation of the Strava.cz service itself.

  • Never commit credentials to version control
  • Use environment variables or secure credential storage
  • Be cautious when sharing code or logs

Session Security

  • 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

Next Steps

Clone this wiki locally