Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 9 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
@@ -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)


Expand Down
24 changes: 24 additions & 0 deletions backend/tests/test_cors.py
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
12 changes: 5 additions & 7 deletions mobile/src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -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).
Expand All @@ -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);
};
Expand All @@ -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 {
Expand Down
15 changes: 15 additions & 0 deletions mobile/src/storage/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as SecureStore from 'expo-secure-store';

const TOKEN_KEY = 'authToken';

export function getToken(): Promise<string | null> {
return SecureStore.getItemAsync(TOKEN_KEY);
}

export function setToken(token: string): Promise<void> {
return SecureStore.setItemAsync(TOKEN_KEY, token);
}

export function deleteToken(): Promise<void> {
return SecureStore.deleteItemAsync(TOKEN_KEY);
}
15 changes: 15 additions & 0 deletions mobile/src/storage/token.web.ts
Original file line number Diff line number Diff line change
@@ -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<string | null> {
return localStorage.getItem(TOKEN_KEY);
}

export async function setToken(token: string): Promise<void> {
localStorage.setItem(TOKEN_KEY, token);
}

export async function deleteToken(): Promise<void> {
localStorage.removeItem(TOKEN_KEY);
}
Loading