Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Oct 10, 2025

Overview

This PR implements secure JWT-based authentication and user profile features for the Language Tutor API, enabling users to log in and access their profile information securely.

Changes

New API Endpoints

  1. POST /login - User authentication endpoint

    • Accepts username and password via OAuth2 password flow
    • Authenticates against the User table with secure password verification
    • Returns JWT access token with 30-minute expiration
    • Compatible with standard OAuth2 clients
  2. GET /me - User profile endpoint (protected)

    • Returns authenticated user's profile information
    • Requires valid JWT token in Authorization header
    • Returns: id, username, email, first_name, learning_style, date_joined
  3. POST /register - Enhanced user registration

    • Now uses bcrypt for secure password hashing
    • Maintains backward compatibility with existing users

Security Implementation

  • Password Hashing: Implemented bcrypt-based password hashing using passlib for all new user registrations, with automatic salt generation
  • JWT Tokens: Created JWT token generation and verification using python-jose with HS256 algorithm
  • OAuth2 Compatibility: Implemented OAuth2 password flow using FastAPI's OAuth2PasswordBearer and OAuth2PasswordRequestForm
  • Protected Routes: Added get_current_user() dependency that verifies JWT tokens and loads user data for protected endpoints
  • Legacy Support: Maintained backward compatibility with existing password hashes (fallback mechanism)

Technical Details

Dependencies Added:

  • passlib==1.7.4 - Industry-standard password hashing
  • python-jose[cryptography]==3.5.0 - JWT token handling
  • sqlmodel==0.0.27 - SQLModel ORM

Key Functions:

  • hash_password() - Securely hashes passwords using bcrypt
  • verify_password() - Verifies passwords with fallback for legacy hashes
  • create_access_token() - Generates JWT tokens with expiration
  • get_current_user() - FastAPI dependency for authentication

Configuration:

  • Uses existing SECRET_KEY from environment variables for JWT signing
  • Token expiration set to 30 minutes
  • Timezone-aware datetime handling

Documentation

Comprehensive documentation has been added to help developers get started:

  • QUICKSTART.md - Quick setup and testing guide (5 minutes to running)
  • AUTH_README.md - Complete authentication documentation with integration examples in Python, JavaScript, and curl
  • TESTING.md - Detailed testing instructions with examples for all endpoints
  • ARCHITECTURE.md - Visual flow diagrams showing authentication flows
  • IMPLEMENTATION_SUMMARY.md - Technical implementation details and security considerations

Testing

  • Added test_auth.py with comprehensive unit tests (4/4 passing)
  • Added examples.py demonstrating complete authentication flow
  • All tests verify password hashing, JWT creation, token expiration, and legacy password support

Backward Compatibility

Zero breaking changes - All existing endpoints continue to work:

  • Existing API key authentication unchanged
  • /languages and /docs-source endpoints work as before
  • Legacy users with old password hashes can still log in
  • No database migrations required

Example Usage

# Register a new user
POST /register
{
  "username": "john",
  "email": "john@example.com",
  "password": "securepass123",
  "first_name": "John"
}

# Login to get token
POST /login (form-data)
username=john&password=securepass123

# Response
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 1800
}

# Access protected profile
GET /me
Authorization: Bearer <token>

# Response
{
  "id": 1,
  "username": "john",
  "email": "john@example.com",
  "first_name": "John",
  "learning_style": null,
  "date_joined": "2025-10-10T16:30:00.123456"
}

Security Notes

The implementation follows security best practices:

  • Passwords are never stored in plain text
  • Bcrypt automatically handles salt generation
  • JWT tokens expire after 30 minutes
  • Proper HTTP status codes for authentication errors (401 for unauthorized, 400 for bad requests)
  • CORS middleware already configured

Production Recommendations:

  • Generate a strong SECRET_KEY (32+ bytes)
  • Use HTTPS/TLS for all traffic
  • Consider implementing refresh tokens for longer sessions
  • Add rate limiting for login attempts

Interactive Documentation

All endpoints are fully documented in the auto-generated Swagger UI at http://localhost:8000/docs, including:

  • Request/response examples
  • Authentication flow with "Authorize" button
  • Try-it-out functionality for testing

Testing Instructions

# Install dependencies
pip install -r requirements.txt

# Run unit tests
python test_auth.py

# Start server
uvicorn main:app --reload

# Visit interactive docs
open http://localhost:8000/docs

See TESTING.md for detailed manual testing instructions.


Closes: #[issue-number]

Note: As requested, no /logout endpoint has been implemented. JWT tokens naturally expire after 30 minutes, and clients can simply discard the token to log out.

Original prompt

Add authentication and profile features to the FastAPI app using SQLModel and SQLite. Implement the following:

  1. A /login endpoint that:
    • Accepts username and password, authenticates using the User table (with hashed_password).
    • Returns a JWT token (using a new SECRET_KEY, or the existing one if suitable).
  2. Dependency for protected endpoints (get_current_user) that reads and verifies JWT from the Authorization header.
  3. A /me endpoint that returns the current user's profile (id, username, email, first_name, learning_style, date_joined) using the JWT.
  4. Use secure password hashing (e.g., passlib's bcrypt) for new registrations and logins, but keep fallback for existing users with the old hash.
  5. Update /register to hash passwords securely (with bcrypt).

Notes:

  • Use FastAPI's security utilities (OAuth2PasswordBearer, etc.).
  • Add all necessary imports and error handling.
  • Document the endpoints and add examples to the Swagger UI.
  • Do not break existing endpoints.
  • No MongoDB or legacy code should remain.
  • Do NOT add a /logout endpoint.

This will enable secure user authentication and allow users to view their own profile after logging in.

This pull request was created as a result of the following prompt from Copilot chat.

Add authentication and profile features to the FastAPI app using SQLModel and SQLite. Implement the following:

  1. A /login endpoint that:
    • Accepts username and password, authenticates using the User table (with hashed_password).
    • Returns a JWT token (using a new SECRET_KEY, or the existing one if suitable).
  2. Dependency for protected endpoints (get_current_user) that reads and verifies JWT from the Authorization header.
  3. A /me endpoint that returns the current user's profile (id, username, email, first_name, learning_style, date_joined) using the JWT.
  4. Use secure password hashing (e.g., passlib's bcrypt) for new registrations and logins, but keep fallback for existing users with the old hash.
  5. Update /register to hash passwords securely (with bcrypt).

Notes:

  • Use FastAPI's security utilities (OAuth2PasswordBearer, etc.).
  • Add all necessary imports and error handling.
  • Document the endpoints and add examples to the Swagger UI.
  • Do not break existing endpoints.
  • No MongoDB or legacy code should remain.
  • Do NOT add a /logout endpoint.

This will enable secure user authentication and allow users to view their own profile after logging in.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@mycoding98 mycoding98 marked this pull request as ready for review October 10, 2025 16:18
Copilot AI and others added 6 commits October 10, 2025 16:18
Co-authored-by: mycoding98 <113207874+mycoding98@users.noreply.github.com>
Co-authored-by: mycoding98 <113207874+mycoding98@users.noreply.github.com>
Co-authored-by: mycoding98 <113207874+mycoding98@users.noreply.github.com>
Co-authored-by: mycoding98 <113207874+mycoding98@users.noreply.github.com>
Co-authored-by: mycoding98 <113207874+mycoding98@users.noreply.github.com>
Co-authored-by: mycoding98 <113207874+mycoding98@users.noreply.github.com>
Copilot AI changed the title [WIP] Add authentication and profile features to FastAPI app Add JWT authentication and user profile endpoints with bcrypt password hashing Oct 10, 2025
Copilot AI requested a review from mycoding98 October 10, 2025 16:31
Copilot finished work on behalf of mycoding98 October 10, 2025 16:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants