Skip to main content

Overview

The Authentication API provides user registration, login, and session management for Poway Auto. All authenticated requests use cookie-based sessions with credentials: 'include'.

User Registration

curl -X POST https://autonomous.stu.nighthawkcodingsociety.com/api/user \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "uid": "johndoe",
    "password": "secure_password123"
  }'
Creates a new user account. Users must have their name and location verified by an administrator, or their account will be deleted.

Request Body

name
string
required
User’s full name (must match the name submitted in location verification)
uid
string
required
Unique username or GitHub ID
password
string
required
User’s password (will be securely hashed)

Response

message
string
Success confirmation message
id
number
Unique identifier for the new user

Success Response

{
  "message": "User created successfully",
  "id": 42
}

Error Responses

{
  "error": "Username already exists"
}
{
  "error": "Name must be verified before creating account"
}

Real Implementation

From navigation/authentication/login.md:85-118:
window.signup = function() {
  const signupButton = document.querySelector("#signupForm button");
  signupButton.disabled = true;
  signupButton.style.backgroundColor = '#d3d3d3';

  const signupOptions = {
    URL: `${pythonURI}/api/user`,
    method: "POST",
    cache: "no-cache",
    body: {
      name: document.getElementById("name").value,
      uid: document.getElementById("signupUid").value,
      password: document.getElementById("signupPassword").value,
    }
  };

  fetch(signupOptions.URL, {
    method: signupOptions.method,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(signupOptions.body)
  })
  .then(response => {
    if (!response.ok) throw new Error(`Signup failed: ${response.status}`);
    return response.json();
  })
  .then(() => {
    document.getElementById("signupMessage").textContent = "Signup successful!";
  })
  .catch(error => {
    document.getElementById("signupMessage").textContent = `Signup Error: ${error.message}`;
    signupButton.disabled = false;
    signupButton.style.backgroundColor = '';
  });
}
Accounts are subject to administrator verification. Create your account using the same name you submitted during location verification.

User Login

curl -X POST https://autonomous.stu.nighthawkcodingsociety.com/api/authenticate \
  -H "Content-Type: application/json" \
  --include-credentials \
  -d '{
    "uid": "johndoe",
    "password": "secure_password123"
  }'
Authenticates a user and creates a session cookie.

Request Body

uid
string
required
Username or GitHub ID
password
string
required
User’s password

Response

message
string
Authentication success message
user
object
Basic user information
auth_token
string
Session token (set as HTTP-only cookie)

Success Response

{
  "message": "Authentication successful",
  "user": {
    "id": 42,
    "uid": "johndoe",
    "name": "John Doe"
  }
}

Error Response

{
  "error": "Invalid credentials"
}

Real Implementation

From navigation/authentication/login.md:70-83 and assets/js/api/config.js:29-60:
window.pythonLogin = function() {
  const options = {
    URL: `${pythonURI}/api/authenticate`,
    callback: pythonDatabase,
    message: "message",
    method: "POST",
    cache: "no-cache",
    body: {
      uid: document.getElementById("uid").value,
      password: document.getElementById("password").value,
    }
  };
  login(options);
}

// Login function from config.js
export function login(options) {
  const requestOptions  = {
    ...fetchOptions,
    method: options.method,
    cache: options.cache,
    body: JSON.stringify(options.body)
  };

  document.getElementById(options.message).textContent = "";

  fetch(options.URL, requestOptions)
  .then(response => {
    if (!response.ok) {
      const errorMsg = 'Login error: ' + response.status;
      console.log(errorMsg);
      document.getElementById(options.message).textContent = errorMsg;
      return;
    }
    options.callback();
  })
  .catch(error => {
    console.log('Possible CORS or Service Down error: ' + error);
    document.getElementById(options.message).textContent = 'Possible CORS or service down error: ' + error;
  });
}

Get Current User

curl https://autonomous.stu.nighthawkcodingsociety.com/api/user \
  -H "Content-Type: application/json" \
  -H "X-Origin: client" \
  --include-credentials
Retrieves information about the currently authenticated user. This endpoint is used throughout the application to verify authentication status and filter user-specific data.

Response

id
number
Unique user identifier
uid
string
Username or GitHub ID
name
string
User’s full name
email
string
User’s email address (if available)
roles
array
User roles (e.g., [“User”, “Admin”])

Success Response

{
  "id": 42,
  "uid": "johndoe",
  "name": "John Doe",
  "email": "[email protected]",
  "roles": ["User"]
}

Error Response

{
  "error": "Not authenticated"
}

Real Implementation

From navigation/favoriteLocations/favoriteLocations.js:69-76:
async function filterForUsername(scores) {
  const currentUserResponse = await fetch(`${pythonURI}/api/user`, fetchOptions);
  if (!currentUserResponse.ok) throw new Error('Failed to fetch current user');
  const currentUser = await currentUserResponse.json();
  let userName = currentUser.name;

  return (scores.filter((entry) => String(entry.username) === String(userName)));
}
This endpoint is frequently called to filter user-specific data, such as saved locations and route preferences.

Session Management

All authenticated requests must include credentials:
const fetchOptions = {
  method: 'GET',
  mode: 'cors',
  cache: 'default',
  credentials: 'include', // Essential for session cookies
  headers: {
    'Content-Type': 'application/json',
    'X-Origin': 'client'
  }
};

Session Persistence

Sessions persist across page loads via HTTP-only cookies. The application checks authentication status on load:
window.onload = function() {
  const isAuthenticated = document.cookie.includes('auth_token');
  if (isAuthenticated) {
    pythonDatabase(); // Verify and fetch user data
  }
};

Authentication Flow

1

Registration

User submits location verification through /api/entries, then creates account via /api/user with matching name.
2

Administrator Verification

Admin reviews location verification and approves account creation.
3

Login

User authenticates via /api/authenticate, receiving a session cookie.
4

Authenticated Requests

All subsequent API requests include credentials: 'include' to send the session cookie.
5

Session Validation

Backend validates session cookie on each request, returning user data or authentication error.

Protected Features

The following features require authentication:

Saved Locations

Manage favorite locations with full CRUD operations

Daily Routine

Create and manage scheduled routes throughout the day

User Profile

View and update personal information and preferences

Route History

Access previously calculated routes and travel history

Error Handling

Common Error Codes

Status CodeErrorDescription
401Not authenticatedSession cookie missing or expired
403ForbiddenUser lacks required permissions
409ConflictUsername already exists during registration
422Validation errorInvalid input data (e.g., weak password, invalid email)

Frontend Error Display

.catch(error => {
  console.error('Authentication error:', error);
  document.getElementById("message").textContent = `Login Error: ${error.message}`;
});

Security Considerations

  • Passwords are securely hashed on the backend before storage
  • Session tokens are HTTP-only cookies to prevent XSS attacks
  • CORS is configured to allow requests only from trusted origins
  • Failed login attempts may be rate-limited to prevent brute force attacks
Never log or expose session tokens in client-side code. Always use credentials: 'include' for automatic cookie handling.

Integration with Config

Authentication configuration from assets/js/api/config.js:
export var pythonURI;
if (location.hostname === "localhost") {
  pythonURI = "http://localhost:8888";
} else if (location.hostname === "127.0.0.1") {
  pythonURI = "http://127.0.0.1:8888";
} else {
  pythonURI = "https://autonomous.stu.nighthawkcodingsociety.com";
}

export const fetchOptions = {
  method: 'GET',
  mode: 'cors',
  cache: 'default',
  credentials: 'include', // Critical for session management
  headers: {
    'Content-Type': 'application/json',
    'X-Origin': 'client'
  }
};

Next Steps

Saved Locations API

Learn how to manage user locations

API Overview

Understand base URLs and common patterns

Build docs developers (and LLMs) love