Skip to main content

Overview

The SASCOP BME SubTec API uses session-based authentication with Django’s built-in authentication system. All API endpoints require authentication via the @login_required decorator.

Authentication Method

The API uses Django session authentication, which requires:
  1. User login through the web interface
  2. Session cookie maintained in subsequent requests
  3. CSRF token for POST/PUT/DELETE operations

Login Endpoint

curl -X POST https://api.sascop-bme-subtec.com/accounts/login/ \
  -H "Content-Type: application/json" \
  -d '{
    "username": "your_username",
    "password": "your_password"
  }' \
  -c cookies.txt

Session Configuration

From bme_subtec/settings.py:
SESSION_COOKIE_AGE = 7200  # 2 hours
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
Session duration in seconds (7200 = 2 hours)
SESSION_SAVE_EVERY_REQUEST
boolean
Extends session on each request

CSRF Protection

All POST, PUT, and DELETE requests require a valid CSRF token:
import requests

session = requests.Session()

# Get CSRF token from login page
login_page = session.get('https://api.sascop-bme-subtec.com/accounts/login/')
csrf_token = session.cookies['csrftoken']

# Include CSRF token in POST requests
headers = {'X-CSRFToken': csrf_token}
data = {'key': 'value'}

response = session.post(
    'https://api.sascop-bme-subtec.com/operaciones/api/ptes/',
    headers=headers,
    json=data
)

Trusted Origins

The API accepts requests from these origins:
settings.py
CSRF_TRUSTED_ORIGINS = [
    'http://localhost',
    'http://127.0.0.1',
    'http://0.0.0.0',
    'http://54.227.40.69',  # Production server
]

Authentication Check

All API endpoints use the @login_required decorator:
api.py
from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def api_estadisticas(request):
    """API para estadísticas del dashboard"""
    # Endpoint logic
    return JsonResponse(data)

Error Responses

{
  "error": "Authentication required",
  "redirect": "/accounts/login/"
}

Session Timeout

The API implements custom session timeout middleware:
middleware.py
class SessionTimeoutMiddleware:
    """
    Automatically logs out users after 2 hours of inactivity
    """
Sessions expire after 2 hours (7200 seconds) of the last request. Make sure to handle session expiration in your client application.

Security Best Practices

Use HTTPS

Always use HTTPS in production to protect credentials

Store Sessions Securely

Never expose session cookies in client-side JavaScript

Validate CSRF

Always include CSRF tokens in state-changing requests

Handle Expiration

Implement proper session expiration handling

Complete Authentication Example

import requests

class SascopAPIClient:
    def __init__(self, base_url):
        self.base_url = base_url
        self.session = requests.Session()
        
    def login(self, username, password):
        """Authenticate with the API"""
        login_url = f"{self.base_url}/accounts/login/"
        response = self.session.post(login_url, data={
            'username': username,
            'password': password
        })
        
        if response.status_code == 200:
            self.csrf_token = self.session.cookies.get('csrftoken')
            return True
        return False
    
    def get(self, endpoint):
        """Make authenticated GET request"""
        url = f"{self.base_url}{endpoint}"
        return self.session.get(url)
    
    def post(self, endpoint, data):
        """Make authenticated POST request with CSRF"""
        url = f"{self.base_url}{endpoint}"
        headers = {'X-CSRFToken': self.csrf_token}
        return self.session.post(url, json=data, headers=headers)

# Usage
client = SascopAPIClient('https://api.sascop-bme-subtec.com')
client.login('username', 'password')

response = client.get('/operaciones/api/estadisticas/')
print(response.json())

Build docs developers (and LLMs) love