Files
fastapi/account_system.md
Beyhan Oğur 361dbef019 first commit
2026-04-26 22:25:19 +03:00

6.7 KiB
Raw Permalink Blame History

Aşağıdaki metni aynen VSCode Copilota (veya başka bir kod üreteci/AI asistana) ver — tek istekte tam bir FastAPI proje iskeleti oluşturacak şekilde ayrıntılı, ama gereksiz karmaşıklıktan kaçınan, dosyalar ayrı ayrı olacak ve SQLite (pip ile çalıştırılabilir) kullanacak bir hesap sistemi üretmesini istiyorum. Kod istemiyorum — sadece bu metni Copilot'a yapıştır ve proje oluşturmasını bekle. (Projede kullanılması zorunlu kütüphaneler listemdeki paketlerle uyumlu olsun.)

İstek (kopyala-yapıştır için):

"Generate a complete, minimal and well-structured FastAPI project that implements a user account system supporting:

  • email/password registration + login (with Argon2 password hashing),
  • social login via Google and GitHub OAuth2 (create handlers for oauth redirect and callback),
  • JWT access tokens (short-lived) and refresh tokens (long-lived) using PyJWT,
  • a simple user model and CRUD using SQLModel/SQLAlchemy, with SQLite as the default local database (so it works without MySQL installed) but structured so switching to MySQL later only needs DATABASE_URL change and Alembic config update,
  • use listed libraries where relevant: fastapi, sqlmodel, SQLAlchemy, alembic, pydantic (v2), python-dotenv, httpx, argon2-cffi, PyJWT, email-validator, uvicorn, and others from my environment list.
  • .venv benim virtual environment'im, requirements.txt içinde gerekli paketler olacak, .env dosyası tüm gerekli env değişkenlerini gösterecek. Requirements and constraints:
  • Keep it simple and explicit. Do not put everything in one file — split into clear modules (core/config, db, models, schemas, services, api/routers, utils).
  • Provide the following endpoints with expected behavior (implementations should be minimal but complete and runnable):
    • POST /auth/register — accept email + password, validate email, hash password, create user, return access + refresh tokens.
    • POST /auth/login — email + password, verify, return access + refresh tokens.
    • POST /auth/refresh — accept refresh token (in body) and return new access token (and optionally new refresh token).
    • GET /auth/oauth/{provider} — provider is "google" or "github", start OAuth flow (redirect to provider auth URL).
    • GET /auth/oauth/{provider}/callback — handle provider callback, exchange code for token via httpx, fetch email/profile, create or find local user, return JWT tokens (or redirect with tokens).
    • GET /users/me — protected endpoint, returns current user info.
    • POST /auth/logout — invalidate refresh token (store refresh tokens in DB).
  • Use dependency-injected DB session and FastAPI dependencies for current_user.
  • Data models:
    • User model (id, email unique, hashed_password nullable for OAuth-only accounts, is_active, created_at).
    • RefreshToken model (id, user_id, token (hashed or raw with storage choice), created_at, expires_at).
  • Security:
    • Hash passwords with argon2-cffi.
    • Sign JWTs with SECRET_KEY from environment (.env via python-dotenv / pydantic-settings).
    • Respect token expiry values from config (ACCESS_TOKEN_EXPIRE_MINUTES, REFRESH_TOKEN_EXPIRE_DAYS).
    • Validate incoming email with email-validator.
  • OAuth details:
    • Use env vars for GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, and OAUTH_REDIRECT_URL (or provider-specific callbacks).
    • Use httpx for server-side HTTP calls to exchange code and fetch user info.
    • When creating a user from OAuth, set hashed_password to None and mark provider source.
  • Database and migrations:
    • Default DB: SQLite file (e.g., sqlite:///./dev.db) so it runs with pip-installed packages only.
    • Include alembic config and a basic migration script that creates the user and refresh token tables. Make Alembic configured to read DATABASE_URL from env.
  • Project structure (must produce these files/modules — generate code for each):
    • app/
      • main.py (FastAPI app factory, include routers, startup events)
      • core/
        • config.py (pydantic settings using pydantic-settings, load .env)
        • security.py (hashing functions, token creation/verification)
        • oauth.py (provider configs and helper functions)
      • db/
        • session.py (engine, sessionmaker factory)
        • base.py (SQLModel metadata)
      • models/
        • models.py (SQLModel models: User, RefreshToken)
      • schemas/
        • schemas.py (pydantic models for requests/responses using pydantic v2 style)
      • services/
        • auth_service.py (register/login/refresh/oauth logic; create tokens; store refresh tokens)
        • user_service.py (basic user CRUD)
      • api/
        • deps.py (get_db, get_current_user)
        • routers/
          • auth.py (auth endpoints listed above)
          • users.py (users/me)
      • alembic/ (alembic env + migration scripts or instruction to autogenerate)
      • tests/
        • test_auth.py (basic tests covering register/login and protected endpoint — minimal)
    • .env.example (show all required env keys and example values)
    • requirements.txt (include the exact packages from my provided list that are necessary)
    • README.md (how to install, run migrations, run app, env variables, how to register OAuth apps for Google & GitHub and set callback URLs)

Developer notes for code generator (be explicit to the generator):

  • Do not implement email sending or complex account verification flows — keep the focus on login flows and JWT.
  • The code must be runnable: after pip install -r requirements.txt and creating a .env (from .env.example), a developer should be able to run alembic upgrade head (or a provided script to create tables) and start uvicorn app.main:app --reload and test the endpoints.
  • Use simple but clear error handling (HTTPException with appropriate status codes).
  • Use typing annotations everywhere and keep functions small and testable.
  • For refresh tokens storage you may store a UUID string in DB (no need to encrypt) but code should show where to change to hashed storage.
  • Keep OAuth handlers minimal but functional: build auth URL, redirect user, handle callback, fetch profile, extract primary email, create/find user, issue tokens. Use scopes ["openid","email","profile"] for Google and ["user:email"] for GitHub.
  • Provide comments in code explaining each module and the main steps of the auth flow.

Output expectation from Copilot:

  • Create all files listed above, with working code (no pseudocode). Keep implementations short and readable with comments.
  • Provide .env.example and README with run instructions.
  • Make sure the app uses SQLite by default and clearly documents how to switch to MySQL.

Language for generated code and docs: English (but variable names and comments can be clear and simple)."

Not: Bu metni VSCode Copilot'a yapıştırdığımda tam bir proje oluştursun; ben yalnızca prompt istedim — kod istemiyorum.