✏️

- feature access/refresh tokens auth
This commit is contained in:
2026-06-11 15:59:29 +08:00
parent ea8e41e688
commit 3f386e5e38
5 changed files with 189 additions and 52 deletions
+6 -4
View File
@@ -27,19 +27,21 @@ uvicorn main:app --reload
**`main.py`** — FastAPI entry point. Creates the app, includes auth and properties routers, creates DB tables on startup, serves the homepage.
**`auth.py`** — Authentication router (`/auth` prefix). User registration, login (JWT in HttpOnly cookie), logout. `get_current_user()` checks cookie first, then bearer token, returns `None` for anonymous users.
**`auth.py`** — Authentication router (`/auth` prefix). Access-refresh token system: access token (15 min) + refresh token (7 days, stored in DB). `get_current_user()` checks access token cookie/bearer first, auto-refreshes via refresh token if expired. Web login sets both cookies; logout revokes refresh token in DB.
**`config.py`** — Shared config: `SECRET_KEY`, `templates`, `bcrypt_context`, `oauth2_bearer`. Jinja2 cache disabled for Python 3.14 compatibility.
**`config.py`** — Shared config: `SECRET_KEY`, `ALGORITHM`, `ACCESS_TOKEN_EXPIRE_MINUTES` (15), `REFRESH_TOKEN_EXPIRE_DAYS` (7), `templates`, `bcrypt_context`, `oauth2_bearer`. Jinja2 cache disabled for Python 3.14 compatibility.
**`database.py`** — SQLAlchemy setup with MySQL engine, `SessionLocal`, `Base`.
**`models.py`** — ORM models: `User` (with email/full_name/phone), `Property` (with contact_email/contact_phone), `PropertyImage`, `Favorite`.
**`models.py`** — ORM models: `User` (with email/full_name/phone), `Property` (with contact_email/contact_phone), `PropertyImage`, `Favorite`, `RefreshToken` (for token rotation/revocation).
**`properties.py`** — Property CRUD, search/filter, favorites, dashboard. Static paths (`/properties/new`) must be defined before parameterized paths (`/properties/{prop_id}`).
## Data Flow
Request → Router → dependency injection (`get_current_user`, `get_db`) → SQLAlchemy → Jinja2 template → HTML response.
Request → `RefreshTokenMiddleware` (sets new access cookie if refreshed) → Router → dependency injection (`get_current_user`, `get_db`) → SQLAlchemy → Jinja2 template → HTML response.
**Auth flow:** Login → issue access (15 min) + refresh (7 days) tokens → both set as HttpOnly cookies. Page load → `get_current_user()` decodes access token; if expired, uses refresh token cookie to get new access token via `try_refresh()`. Logout → revoke refresh token in DB, clear both cookies.
**TemplateResponse API:** `templates.TemplateResponse(request, "template.html", {"user": user, ...})` — request is first arg (Starlette 1.x).