From 42403d26fd54f06cbc171351230de6ad5432e586 Mon Sep 17 00:00:00 2001 From: DarynaBb Date: Wed, 25 Nov 2026 12:27:11 +0100 Subject: [PATCH 1/2] fix(backend): allow CORS requests from Expo web Browsers blocked API calls from the Expo web dev server because the preflight OPTIONS request returned 405. Allowed origins are configurable via CORS_ORIGINS (default: http://localhost:8081). --- .env.example | 2 ++ backend/app/config.py | 8 ++++++++ backend/app/main.py | 10 +++++++++- backend/tests/test_cors.py | 24 ++++++++++++++++++++++++ docker-compose.yml | 1 + 5 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 backend/tests/test_cors.py diff --git a/.env.example b/.env.example index 55d43ff..72cdb36 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,8 @@ POSTGRES_DB=quitt # Backend APP_NAME=quitt API APP_ENV=development +# Comma-separated origins allowed to call the API from a browser (Expo web) +CORS_ORIGINS=http://localhost:8081 # JWT JWT_SECRET=replace-with-a-secure-random-secret diff --git a/backend/app/config.py b/backend/app/config.py index ce47e64..7c7d380 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -3,6 +3,14 @@ APP_NAME = os.getenv("APP_NAME", "quitt API") APP_ENV = os.getenv("APP_ENV", "development") +# Comma-separated list of origins allowed to call the API from a browser +# (e.g. the Expo web dev server). Native apps are not affected by CORS. +CORS_ORIGINS = [ + origin.strip() + for origin in os.getenv("CORS_ORIGINS", "http://localhost:8081").split(",") + if origin.strip() +] + JWT_SECRET = os.getenv("JWT_SECRET") if not JWT_SECRET or len(JWT_SECRET) < 32: diff --git a/backend/app/main.py b/backend/app/main.py index f3f4a00..6161d60 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,10 +1,18 @@ from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware -from app.config import APP_NAME +from app.config import APP_NAME, CORS_ORIGINS from app.routers.auth import router as auth_router app = FastAPI(title=APP_NAME) +app.add_middleware( + CORSMiddleware, + allow_origins=CORS_ORIGINS, + allow_methods=["*"], + allow_headers=["*"], +) + app.include_router(auth_router) diff --git a/backend/tests/test_cors.py b/backend/tests/test_cors.py new file mode 100644 index 0000000..e2a944d --- /dev/null +++ b/backend/tests/test_cors.py @@ -0,0 +1,24 @@ +def test_cors_preflight_allows_expo_web(client): + response = client.options( + "/login", + headers={ + "Origin": "http://localhost:8081", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + }, + ) + + assert response.status_code == 200 + assert response.headers["access-control-allow-origin"] == "http://localhost:8081" + + +def test_cors_rejects_unknown_origin(client): + response = client.options( + "/login", + headers={ + "Origin": "http://evil.example", + "Access-Control-Request-Method": "POST", + }, + ) + + assert "access-control-allow-origin" not in response.headers diff --git a/docker-compose.yml b/docker-compose.yml index 2df9338..3a3c18f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,6 +28,7 @@ services: DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-quitt}:${POSTGRES_PASSWORD:-quitt}@db:5432/${POSTGRES_DB:-quitt} APP_NAME: ${APP_NAME:-quitt API} APP_ENV: ${APP_ENV:-development} + CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:8081} JWT_SECRET: ${JWT_SECRET} JWT_ALGORITHM: ${JWT_ALGORITHM:-HS256} JWT_EXPIRE_MINUTES: ${JWT_EXPIRE_MINUTES:-30} From b2f99c0d25663d6bd3d20ca8f970b239f8fb3e59 Mon Sep 17 00:00:00 2001 From: DarynaBb Date: Wed, 25 Nov 2026 12:27:11 +0100 Subject: [PATCH 2/2] fix(app): store auth token in localStorage on web expo-secure-store has no web implementation, so restoring the session and signing in failed in the browser. Native builds keep using SecureStore. --- mobile/src/context/AuthContext.tsx | 12 +++++------- mobile/src/storage/token.ts | 15 +++++++++++++++ mobile/src/storage/token.web.ts | 15 +++++++++++++++ 3 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 mobile/src/storage/token.ts create mode 100644 mobile/src/storage/token.web.ts diff --git a/mobile/src/context/AuthContext.tsx b/mobile/src/context/AuthContext.tsx index e7d59b1..819ef11 100644 --- a/mobile/src/context/AuthContext.tsx +++ b/mobile/src/context/AuthContext.tsx @@ -1,10 +1,8 @@ -import * as SecureStore from 'expo-secure-store'; import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { getMe, login, register, type User } from '@/api/auth'; import { ApiError } from '@/api/client'; - -const TOKEN_KEY = 'authToken'; +import * as tokenStorage from '@/storage/token'; type AuthContextValue = { user: User | null; @@ -25,7 +23,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { useEffect(() => { async function restoreSession() { try { - const savedToken = await SecureStore.getItemAsync(TOKEN_KEY); + const savedToken = await tokenStorage.getToken(); if (!savedToken) { return; @@ -36,7 +34,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { setUser(currentUser); } catch (error) { if (error instanceof ApiError && error.status === 401) { - await SecureStore.deleteItemAsync(TOKEN_KEY).catch(() => {}); + await tokenStorage.deleteToken().catch(() => {}); } else { // Server not reachable: keep the token so the next app start can log in again. // The user sees the login screen for now (intended for the MVP). @@ -53,7 +51,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { const newToken = await login(email, password); const currentUser = await getMe(newToken); - await SecureStore.setItemAsync(TOKEN_KEY, newToken); + await tokenStorage.setToken(newToken); setToken(newToken); setUser(currentUser); }; @@ -65,7 +63,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { const signOut = async () => { try { - await SecureStore.deleteItemAsync(TOKEN_KEY); + await tokenStorage.deleteToken(); } catch (error) { console.warn('Failed to delete token', error); } finally { diff --git a/mobile/src/storage/token.ts b/mobile/src/storage/token.ts new file mode 100644 index 0000000..d6cbeee --- /dev/null +++ b/mobile/src/storage/token.ts @@ -0,0 +1,15 @@ +import * as SecureStore from 'expo-secure-store'; + +const TOKEN_KEY = 'authToken'; + +export function getToken(): Promise { + return SecureStore.getItemAsync(TOKEN_KEY); +} + +export function setToken(token: string): Promise { + return SecureStore.setItemAsync(TOKEN_KEY, token); +} + +export function deleteToken(): Promise { + return SecureStore.deleteItemAsync(TOKEN_KEY); +} diff --git a/mobile/src/storage/token.web.ts b/mobile/src/storage/token.web.ts new file mode 100644 index 0000000..64de239 --- /dev/null +++ b/mobile/src/storage/token.web.ts @@ -0,0 +1,15 @@ +// expo-secure-store has no web implementation, so the browser build falls back to +// localStorage. This is not secure storage and is only meant for local web development. +const TOKEN_KEY = 'authToken'; + +export async function getToken(): Promise { + return localStorage.getItem(TOKEN_KEY); +} + +export async function setToken(token: string): Promise { + localStorage.setItem(TOKEN_KEY, token); +} + +export async function deleteToken(): Promise { + localStorage.removeItem(TOKEN_KEY); +}