Skip to content

bug: OAuth-authenticated users lose API access after every server restart #102

@piyushdotcomm

Description

@piyushdotcomm

Bug Description

When a user logs in via GitHub or Google OAuth for the first time, their generated API key is saved to the database and added to the in-memory settings.API_KEYS dictionary. This works correctly during that session.

However, after a server restart, settings.API_KEYS is only repopulated from the API_KEYS environment variable. It does NOT reload previously approved OAuth users from the database.

Since verify_api_key() validates all incoming API keys against settings.API_KEYS (in-memory only), every OAuth user gets a 401 Invalid API key response after any restart or redeployment.

Steps to Reproduce

  1. Log in via GitHub or Google OAuth — works correctly.
  2. Make an API request to /ask — returns a valid response.
  3. Restart the server.
  4. Make the same API request with the same key — returns 401 Invalid API key.

Root Cause

sync_env_keys_to_db() only syncs keys from the .env file into the database. It never reads all approved keys back from the database into memory. OAuth-created keys exist in the database but are invisible to the API key validator after a restart.

Suggested Fix

In main.py, after calling sync_env_keys_to_db(db):

approved_keys = db.query(APIKey).filter(
    APIKey.approved == True,
    APIKey.is_active == True
).all()
for key_obj in approved_keys:
    settings.API_KEYS[key_obj.key] = {
        "name": key_obj.name,
        "can_change_model": key_obj.can_change_model
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions