Spaces:
Sleeping
Sleeping
'code'
Browse filesFiles changed (10)
- README.md+50-1
- alembic/__pycache__/env.cpython-312.pyc
- alembic/env.py+1
- alembic/versions/20251222_add_refresh_token_table.pyAdded+35
- alembic/versions/__pycache__/20251222_add_refresh_token_table.cpython-312.pycAdded
- alembic/versions/__pycache__/3b6c60669e48_add_project_model_and_relationship_to_.cpython-312.pyc
- alembic/versions/__pycache__/ec70eaafa7b6_initial_schema_with_users_and_tasks_.cpython-312.pyc
- src/models/__pycache__/refresh_token.cpython-312.pycAdded
- src/models/refresh_token.pyAdded+17
- src/routers/auth.py+130-37
18 unmodified lines1920212218 unmodified lines- Frontend fetch calls that rely on cookies must use `credentials: 'include'` (e.g. `fetch(url, { method, credentials: 'include' })`).- Backend CORS must have `allow_credentials=True` and the exact frontend origin (not `*`) in allowed origins. This project reads `FRONTEND_URL` for that purpose.If cookies are still not sent/received, open DevTools network tab and inspect the `Set-Cookie` response header and browser cookie/journal to see why it was blocked (e.g., SameSite/Secure/Domain issues).18 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707118 unmodified lines- Frontend fetch calls that rely on cookies must use `credentials: 'include'` (e.g. `fetch(url, { method, credentials: 'include' })`).- Backend CORS must have `allow_credentials=True` and the exact frontend origin (not `*`) in allowed origins. This project reads `FRONTEND_URL` for that purpose.### Refresh token flow (implemented)- On login the backend now returns a **short-lived access token** (in the response) and sets a **HttpOnly refresh cookie** (`/api/auth` path).- To get a new access token, call `POST /api/auth/refresh` with `credentials: 'include'`. The server validates and rotates the refresh token and returns a new access token in the response body.- On logout the server revokes the refresh token and clears the refresh cookie.Client example (login + using refresh) — Vercel frontend:1) Login (receives access token in response body and a HttpOnly refresh cookie):```jsconst res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/login`, {method: 'POST',headers: { 'Content-Type': 'application/json' },credentials: 'include',body: JSON.stringify({ email, password }),})const data = await res.json()const accessToken = data.access_token// Store accessToken in memory (React state)```2) Use access token for protected calls (in memory, sent in Authorization header):```jsawait fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/tasks`, {headers: { 'Authorization': `Bearer ${accessToken}` }})```3) Obtain a fresh access token when it expires:```jsconst res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/refresh`, {method: 'POST',credentials: 'include', // sends HttpOnly refresh cookie})const data = await res.json()const accessToken = data.access_token```If cookies are still not sent/received, open DevTools network tab and inspect the `Set-Cookie` response header and browser cookie/journal to see why it was blocked (e.g., SameSite/Secure/Domain issues).Database migration note:- After pulling these changes, run Alembic migrations to create the `refreshtoken` table:```bashalembic upgrade head```(If you deploy to Spaces, ensure your deployment runs the migration step or create the table manually.)
13 unmodified lines14151617181913 unmodified linesfrom src.models.user import User # Import your modelsfrom src.models.task import Task # Import your modelsfrom src.models.project import Project # Import your models# this is the Alembic Config object, which provides13 unmodified lines1415161718192013 unmodified linesfrom src.models.user import User # Import your modelsfrom src.models.task import Task # Import your modelsfrom src.models.project import Project # Import your modelsfrom src.models.refresh_token import RefreshToken # Add RefreshToken model for migrations# this is the Alembic Config object, which provides
1234567891011121314151617181920212223242526272829303132333435"""add refresh token table
Revision ID: 20251222_add_refresh_token_tableRevises: Create Date: 2025-12-22 00:00:00.000000"""from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision = '20251222_add_refresh_token_table'down_revision = '4ac448e3f100' # depends on last migration in the main chainbranch_labels = Nonedepends_on = None
def upgrade() -> None: op.create_table( 'refreshtoken', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True, nullable=False), sa.Column('token_hash', sa.String(length=128), nullable=False), sa.Column('user_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('user.id'), nullable=True), sa.Column('revoked', sa.Boolean(), nullable=False, server_default=sa.text('false')), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('expires_at', sa.DateTime(), nullable=True), ) # create index separately (SQLAlchemy/Alembic prefers explicit index creation) op.create_index('ix_refreshtoken_token_hash', 'refreshtoken', ['token_hash'])
def downgrade() -> None: # drop index then table op.drop_index('ix_refreshtoken_token_hash', table_name='refreshtoken') op.drop_table('refreshtoken')1234567891011121314151617from sqlmodel import SQLModel, Field, Relationshipfrom typing import Optionalimport uuidfrom datetime import datetimefrom sqlalchemy import Column, DateTime, Boolean, String, ForeignKey
class RefreshToken(SQLModel, table=True): id: Optional[uuid.UUID] = Field(default_factory=uuid.uuid4, primary_key=True) # Use a plain sa_column without `index=True` (SQLModel does not allow index=True when sa_column is provided) token_hash: str = Field(sa_column=Column(String(length=128))) user_id: Optional[uuid.UUID] = Field(foreign_key="user.id") revoked: bool = Field(default=False, sa_column=Column(Boolean, default=False)) created_at: datetime = Field(sa_column=Column(DateTime, default=datetime.utcnow)) expires_at: datetime = Field(sa_column=Column(DateTime))
# Relationship back to user is optional and not required for our use-case3 unmodified lines45678910113 unmodified lines1516171819203 unmodified lines2425262728293023 unmodified lines5455565758596061626364656667686970717273743 unmodified lines787980818283845 unmodified lines909192939495969798991001011021031041051061071081091101111121135 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461473 unmodified linesfrom datetime import datetime, timedeltafrom uuid import uuid4import secretsfrom ..models.user import User, UserCreate, UserReadfrom ..schemas.auth import RegisterRequest, RegisterResponse, LoginRequest, LoginResponse, ForgotPasswordRequest, ResetPasswordRequestfrom ..utils.security import hash_password, create_access_token, verify_passwordfrom ..utils.deps import get_current_user3 unmodified linesrouter = APIRouter(prefix="/api/auth", tags=["auth"])# NOTE: For cross-site cookie auth to work (backend on a different domain than the frontend):# - The frontend must call login/register endpoints with `fetch(..., credentials: 'include')`# - The backend must have CORS allow_credentials=True and the exact frontend origin in allow_origins3 unmodified lines@router.post("/register", response_model=RegisterResponse, status_code=status.HTTP_201_CREATED)def register(user_data: RegisterRequest, response: Response, session: Session = Depends(get_session_dep)):"""Register a new user with email and password."""# Check if user already existsexisting_user = session.exec(select(User).where(User.email == user_data.email)).first()23 unmodified linessession.commit()session.refresh(user)# Create access tokenaccess_token = create_access_token(data={"sub": str(user.id)})# Set the token as an httpOnly cookieresponse.set_cookie(key="access_token",value=access_token,httponly=True,secure=settings.JWT_COOKIE_SECURE, # True in production, False in developmentsamesite="none", # Allow cross-site cookies; browsers require Secure for SameSite=Nonemax_age=settings.ACCESS_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, # Convert days to secondspath="/")# Return responsereturn RegisterResponse(id=user.id,email=user.email,3 unmodified lines@router.post("/login", response_model=LoginResponse)def login(login_data: LoginRequest, response: Response, session: Session = Depends(get_session_dep)):"""Authenticate user with email and password, return JWT token."""# Find user by emailuser = session.exec(select(User).where(User.email == login_data.email)).first()5 unmodified linesheaders={"WWW-Authenticate": "Bearer"},)# Create access tokenaccess_token = create_access_token(data={"sub": str(user.id)})# Set the token as an httpOnly cookieresponse.set_cookie(key="access_token",value=access_token,httponly=True,secure=settings.JWT_COOKIE_SECURE, # True in production, False in developmentsamesite="none", # Allow cross-site cookies; browsers require Secure for SameSite=Nonemax_age=settings.ACCESS_TOKEN_EXPIRE_DAYS * 24 * 60 * 60, # Convert days to secondspath="/")# Debug: Print cookie attributes (do NOT log token value in production)print(f"Cookie set (httponly={True}, secure={settings.JWT_COOKIE_SECURE}, samesite=none, max_age={settings.ACCESS_TOKEN_EXPIRE_DAYS * 24 * 60 * 60})")# Return responsereturn LoginResponse(access_token=access_token,token_type="bearer",5 unmodified lines)@router.post("/logout")def logout(response: Response):"""Logout user by clearing the access token cookie."""# Clear the access_token cookieresponse.set_cookie(key="access_token",value="",httponly=True,secure=settings.JWT_COOKIE_SECURE,samesite="none", # Allow cross-site cookies; browsers require Secure for SameSite=Nonemax_age=0, # Expire immediatelypath="/")return {"message": "Logged out successfully"}@router.get("/me", response_model=RegisterResponse)def get_current_user_profile(request: Request, current_user: User = Depends(get_current_user)):"""Get the current authenticated user's profile."""# Debug: Print the cookies receivedprint(f"Received cookies: {request.cookies}")print(f"Access token cookie: {request.cookies.get('access_token')}")return RegisterResponse(id=current_user.id,3 unmodified lines456789101112133 unmodified lines171819202122232425263 unmodified lines3031323334353637383923 unmodified lines63646566676869707172737475767778798081828384858687888990913 unmodified lines95969798991001011021031041055 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411425 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392403 unmodified linesfrom datetime import datetime, timedeltafrom uuid import uuid4import secretsimport hashlibfrom ..models.user import User, UserCreate, UserReadfrom ..models.refresh_token import RefreshTokenfrom ..schemas.auth import RegisterRequest, RegisterResponse, LoginRequest, LoginResponse, ForgotPasswordRequest, ResetPasswordRequestfrom ..utils.security import hash_password, create_access_token, verify_passwordfrom ..utils.deps import get_current_user3 unmodified linesrouter = APIRouter(prefix="/api/auth", tags=["auth"])# Refresh token settingsREFRESH_TOKEN_EXPIRE_DAYS = 30REFRESH_TOKEN_COOKIE_NAME = "refresh_token"# NOTE: For cross-site cookie auth to work (backend on a different domain than the frontend):# - The frontend must call login/register endpoints with `fetch(..., credentials: 'include')`# - The backend must have CORS allow_credentials=True and the exact frontend origin in allow_origins3 unmodified lines@router.post("/register", response_model=RegisterResponse, status_code=status.HTTP_201_CREATED)def register(user_data: RegisterRequest, response: Response, session: Session = Depends(get_session_dep)):"""Register a new user with email and password.This returns a short-lived access token in the response and sets a HttpOnly refresh cookie."""# Check if user already existsexisting_user = session.exec(select(User).where(User.email == user_data.email)).first()23 unmodified linessession.commit()session.refresh(user)# Issue short-lived access token and refresh tokenaccess_token = create_access_token(data={"sub": str(user.id)}, expires_delta=timedelta(minutes=15))# Create refresh token, store hashed token in DBraw_refresh = secrets.token_urlsafe(64)token_hash = hashlib.sha256(raw_refresh.encode()).hexdigest()expires_at = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)refresh_record = RefreshToken(token_hash=token_hash, user_id=user.id, expires_at=expires_at)session.add(refresh_record)session.commit()# Set HttpOnly refresh cookieresponse.set_cookie(key=REFRESH_TOKEN_COOKIE_NAME,value=raw_refresh,httponly=True,secure=settings.JWT_COOKIE_SECURE,samesite="none",max_age=REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,path="/api/auth")return RegisterResponse(id=user.id,email=user.email,3 unmodified lines@router.post("/login", response_model=LoginResponse)def login(login_data: LoginRequest, response: Response, session: Session = Depends(get_session_dep)):"""Authenticate user with email and password.Returns a short-lived access token in the response body and sets a HttpOnly refresh cookie.Frontend should store access token in memory and call protected APIs with Authorization header, or let frontend call `/api/auth/refresh` (with `credentials: 'include'`) to obtain a new access token."""# Find user by emailuser = session.exec(select(User).where(User.email == login_data.email)).first()5 unmodified linesheaders={"WWW-Authenticate": "Bearer"},)# Create short-lived access token (e.g., 15 minutes)access_token = create_access_token(data={"sub": str(user.id)}, expires_delta=timedelta(minutes=15))# Create refresh token, store hashed token in DBraw_refresh = secrets.token_urlsafe(64)token_hash = hashlib.sha256(raw_refresh.encode()).hexdigest()expires_at = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)refresh_record = RefreshToken(token_hash=token_hash, user_id=user.id, expires_at=expires_at)session.add(refresh_record)session.commit()# Set HttpOnly refresh cookie (sent to frontend with credentials: 'include')response.set_cookie(key=REFRESH_TOKEN_COOKIE_NAME,value=raw_refresh,httponly=True,secure=settings.JWT_COOKIE_SECURE,samesite="none",max_age=REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,path="/api/auth")print(f"Refresh cookie set (httponly={True}, secure={settings.JWT_COOKIE_SECURE}, samesite=none, max_age={REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60})")# Return short-lived access token in response body for immediate usereturn LoginResponse(access_token=access_token,token_type="bearer",5 unmodified lines)@router.post("/refresh")def refresh_token(request: Request, response: Response, session: Session = Depends(get_session_dep)):"""Rotate refresh token and return a new short-lived access token.This endpoint reads the HttpOnly refresh cookie, validates it, rotates it (revokes old),and sets a new refresh cookie (cookie rotation) and returns a fresh access token.Frontend must call this with `credentials: 'include'`."""raw_refresh = request.cookies.get(REFRESH_TOKEN_COOKIE_NAME)if not raw_refresh:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="No refresh token provided")token_hash = hashlib.sha256(raw_refresh.encode()).hexdigest()token_record = session.exec(select(RefreshToken).where(RefreshToken.token_hash == token_hash)).first()if not token_record or token_record.revoked:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token")if token_record.expires_at < datetime.utcnow():raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Refresh token expired")# Get useruser = session.get(User, token_record.user_id)if not user:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")# Revoke old token and rotatetoken_record.revoked = Truesession.add(token_record)# Create new refresh tokennew_raw_refresh = secrets.token_urlsafe(64)new_token_hash = hashlib.sha256(new_raw_refresh.encode()).hexdigest()new_expires_at = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)new_refresh_record = RefreshToken(token_hash=new_token_hash, user_id=user.id, expires_at=new_expires_at)session.add(new_refresh_record)session.commit()# Set new refresh cookieresponse.set_cookie(key=REFRESH_TOKEN_COOKIE_NAME,value=new_raw_refresh,httponly=True,secure=settings.JWT_COOKIE_SECURE,samesite="none",max_age=REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,path="/api/auth")# Create new short-lived access token and return itaccess_token = create_access_token(data={"sub": str(user.id)}, expires_delta=timedelta(minutes=15))return {"access_token": access_token, "token_type": "bearer"}@router.post("/logout")def logout(request: Request, response: Response, session: Session = Depends(get_session_dep)):"""Logout user by revoking the refresh token cookie and clearing the cookie."""raw_refresh = request.cookies.get(REFRESH_TOKEN_COOKIE_NAME)if raw_refresh:token_hash = hashlib.sha256(raw_refresh.encode()).hexdigest()token_record = session.exec(select(RefreshToken).where(RefreshToken.token_hash == token_hash)).first()if token_record:token_record.revoked = Truesession.add(token_record)session.commit()# Clear the refresh cookieresponse.set_cookie(key=REFRESH_TOKEN_COOKIE_NAME,value="",httponly=True,secure=settings.JWT_COOKIE_SECURE,samesite="none",max_age=0, # Expire immediatelypath="/api/auth")return {"message": "Logged out successfully"}@router.get("/me", response_model=RegisterResponse)def get_current_user_profile(request: Request, current_user: User = Depends(get_current_user)):"""Get the current authenticated user's profile."""# Debug: Print the cookies received (do not print token values)print(f"Received cookies: { {k: '***' for k in request.cookies.keys()} }")return RegisterResponse(id=current_user.id,
README.md+50-1
alembic/__pycache__/env.cpython-312.pyc
alembic/env.py+1
alembic/versions/20251222_add_refresh_token_table.pyAdded+35
alembic/versions/__pycache__/20251222_add_refresh_token_table.cpython-312.pycAdded
alembic/versions/__pycache__/3b6c60669e48_add_project_model_and_relationship_to_.cpython-312.pyc
alembic/versions/__pycache__/ec70eaafa7b6_initial_schema_with_users_and_tasks_.cpython-312.pyc
src/models/__pycache__/refresh_token.cpython-312.pycAdded
src/models/refresh_token.pyAdded+17
src/routers/auth.py+130-37