2026-03-06 16:57:46 +03:00
|
|
|
import logging
|
2026-03-05 21:33:41 +03:00
|
|
|
import httpx
|
|
|
|
|
|
2026-03-10 13:01:12 +03:00
|
|
|
from datetime import datetime
|
2026-03-09 17:18:25 +03:00
|
|
|
from fastapi import APIRouter, Request, Depends, HTTPException
|
|
|
|
|
from fastapi.responses import RedirectResponse, JSONResponse
|
2026-03-10 14:11:25 +03:00
|
|
|
from web.templates_env import templates
|
2026-03-09 17:18:25 +03:00
|
|
|
from pydantic import BaseModel
|
2026-03-05 21:33:41 +03:00
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
|
|
|
|
from web.auth import get_current_user
|
|
|
|
|
from web.config import settings
|
|
|
|
|
from web.database import get_db
|
|
|
|
|
from web.models import User, EvotorConnection
|
|
|
|
|
|
2026-03-09 17:18:25 +03:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-03-05 21:33:41 +03:00
|
|
|
router = APIRouter(prefix="/evotor")
|
|
|
|
|
|
2026-03-09 17:33:00 +03:00
|
|
|
EVOTOR_APP_URL = "https://market.evotor.ru/store/apps/{app_id}"
|
2026-03-05 21:33:41 +03:00
|
|
|
EVOTOR_STORES_URL = "https://api.evotor.ru/stores"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("")
|
|
|
|
|
def evotor_page(
|
|
|
|
|
request: Request,
|
|
|
|
|
db: Session = Depends(get_db),
|
|
|
|
|
user: User | None = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
if not user:
|
|
|
|
|
return RedirectResponse("/login", 303)
|
|
|
|
|
|
|
|
|
|
connection = db.query(EvotorConnection).filter(EvotorConnection.user_id == user.id).first()
|
|
|
|
|
error = request.query_params.get("error")
|
2026-03-10 13:01:12 +03:00
|
|
|
app_url = EVOTOR_APP_URL.format(app_id=settings.EVOTOR_APP_ID) if settings.EVOTOR_APP_ID else None
|
2026-03-05 21:33:41 +03:00
|
|
|
return templates.TemplateResponse("evotor.html", {
|
|
|
|
|
"request": request,
|
|
|
|
|
"user": user,
|
|
|
|
|
"connection": connection,
|
|
|
|
|
"error": error,
|
2026-03-10 13:01:12 +03:00
|
|
|
"app_url": app_url,
|
2026-03-05 21:33:41 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
2026-03-09 17:18:25 +03:00
|
|
|
class EvotorTokenPayload(BaseModel):
|
|
|
|
|
userId: str
|
|
|
|
|
token: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/callback")
|
2026-03-05 21:33:41 +03:00
|
|
|
async def evotor_callback(
|
|
|
|
|
request: Request,
|
2026-03-09 17:18:25 +03:00
|
|
|
payload: EvotorTokenPayload,
|
2026-03-05 21:33:41 +03:00
|
|
|
db: Session = Depends(get_db),
|
|
|
|
|
):
|
2026-03-09 17:18:25 +03:00
|
|
|
"""
|
|
|
|
|
Webhook endpoint: Evotor POSTs {"userId": "...", "token": "..."} here
|
|
|
|
|
after the user authorizes the app in their Evotor account.
|
|
|
|
|
"""
|
|
|
|
|
# Verify the Authorization header matches our configured webhook secret
|
|
|
|
|
if settings.EVOTOR_WEBHOOK_SECRET:
|
|
|
|
|
auth_header = request.headers.get("Authorization", "")
|
|
|
|
|
expected = f"Bearer {settings.EVOTOR_WEBHOOK_SECRET}"
|
|
|
|
|
if auth_header != expected:
|
|
|
|
|
logger.warning("Evotor webhook: invalid Authorization header")
|
|
|
|
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
2026-03-05 21:33:41 +03:00
|
|
|
|
2026-03-09 17:18:25 +03:00
|
|
|
now = datetime.utcnow()
|
2026-03-05 21:33:41 +03:00
|
|
|
|
2026-03-09 17:18:25 +03:00
|
|
|
# Fetch store info using the received token
|
2026-03-05 21:33:41 +03:00
|
|
|
store_id = None
|
|
|
|
|
store_name = None
|
|
|
|
|
try:
|
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
|
stores_response = await client.get(
|
|
|
|
|
EVOTOR_STORES_URL,
|
2026-03-09 17:18:25 +03:00
|
|
|
headers={"Authorization": f"Bearer {payload.token}"},
|
2026-03-05 21:33:41 +03:00
|
|
|
timeout=15,
|
|
|
|
|
)
|
|
|
|
|
if stores_response.status_code == 200:
|
|
|
|
|
stores = stores_response.json()
|
|
|
|
|
items = stores.get("items", stores) if isinstance(stores, dict) else stores
|
|
|
|
|
if items:
|
|
|
|
|
store_id = items[0].get("uuid") or items[0].get("id")
|
|
|
|
|
store_name = items[0].get("name")
|
|
|
|
|
except Exception:
|
2026-03-09 17:18:25 +03:00
|
|
|
pass # Store info is optional
|
2026-03-05 21:33:41 +03:00
|
|
|
|
2026-03-09 17:18:25 +03:00
|
|
|
# Upsert by evotor_user_id (user_id stays NULL until /evotor/link is called)
|
|
|
|
|
connection = db.query(EvotorConnection).filter(
|
|
|
|
|
EvotorConnection.evotor_user_id == payload.userId
|
|
|
|
|
).first()
|
2026-03-06 16:57:46 +03:00
|
|
|
|
2026-03-05 21:33:41 +03:00
|
|
|
if connection:
|
2026-03-09 17:18:25 +03:00
|
|
|
connection.access_token = payload.token
|
2026-03-05 21:33:41 +03:00
|
|
|
connection.store_id = store_id
|
|
|
|
|
connection.store_name = store_name
|
2026-03-06 15:26:49 +03:00
|
|
|
connection.is_online = True
|
2026-03-06 16:57:46 +03:00
|
|
|
connection.last_checked_at = now
|
2026-03-09 17:18:25 +03:00
|
|
|
connection.updated_at = now
|
2026-03-05 21:33:41 +03:00
|
|
|
else:
|
|
|
|
|
connection = EvotorConnection(
|
2026-03-09 17:18:25 +03:00
|
|
|
evotor_user_id=payload.userId,
|
|
|
|
|
access_token=payload.token,
|
2026-03-05 21:33:41 +03:00
|
|
|
store_id=store_id,
|
|
|
|
|
store_name=store_name,
|
2026-03-06 15:26:49 +03:00
|
|
|
is_online=True,
|
2026-03-06 16:57:46 +03:00
|
|
|
last_checked_at=now,
|
2026-03-05 21:33:41 +03:00
|
|
|
)
|
|
|
|
|
db.add(connection)
|
2026-03-09 17:18:25 +03:00
|
|
|
|
|
|
|
|
db.commit()
|
|
|
|
|
logger.info("Evotor webhook: saved token for evotor_user_id=%s", payload.userId)
|
|
|
|
|
|
|
|
|
|
return JSONResponse({"status": "ok"})
|
|
|
|
|
|
|
|
|
|
|
2026-03-09 17:35:17 +03:00
|
|
|
@router.post("/token")
|
|
|
|
|
async def evotor_token_manual(
|
|
|
|
|
request: Request,
|
|
|
|
|
db: Session = Depends(get_db),
|
|
|
|
|
user: User | None = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
"""Allow user to manually paste their Evotor token."""
|
|
|
|
|
if not user:
|
|
|
|
|
return RedirectResponse("/login", 303)
|
|
|
|
|
|
|
|
|
|
form = await request.form()
|
|
|
|
|
token = (form.get("token") or "").strip()
|
|
|
|
|
if not token:
|
|
|
|
|
return RedirectResponse("/evotor?error=empty_token", 303)
|
|
|
|
|
|
|
|
|
|
now = datetime.utcnow()
|
|
|
|
|
|
|
|
|
|
# Fetch store info
|
|
|
|
|
store_id = None
|
|
|
|
|
store_name = None
|
|
|
|
|
try:
|
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
|
stores_response = await client.get(
|
|
|
|
|
EVOTOR_STORES_URL,
|
|
|
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
|
|
|
timeout=15,
|
|
|
|
|
)
|
|
|
|
|
if stores_response.status_code == 200:
|
|
|
|
|
stores = stores_response.json()
|
|
|
|
|
items = stores.get("items", stores) if isinstance(stores, dict) else stores
|
|
|
|
|
if items:
|
|
|
|
|
store_id = items[0].get("uuid") or items[0].get("id")
|
|
|
|
|
store_name = items[0].get("name")
|
|
|
|
|
elif stores_response.status_code == 401:
|
|
|
|
|
return RedirectResponse("/evotor?error=invalid_token", 303)
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
connection = db.query(EvotorConnection).filter(EvotorConnection.user_id == user.id).first()
|
|
|
|
|
if connection:
|
|
|
|
|
connection.access_token = token
|
|
|
|
|
connection.store_id = store_id
|
|
|
|
|
connection.store_name = store_name
|
|
|
|
|
connection.is_online = True
|
|
|
|
|
connection.last_checked_at = now
|
|
|
|
|
connection.updated_at = now
|
|
|
|
|
else:
|
|
|
|
|
connection = EvotorConnection(
|
|
|
|
|
user_id=user.id,
|
|
|
|
|
access_token=token,
|
|
|
|
|
store_id=store_id,
|
|
|
|
|
store_name=store_name,
|
|
|
|
|
is_online=True,
|
|
|
|
|
last_checked_at=now,
|
|
|
|
|
)
|
|
|
|
|
db.add(connection)
|
|
|
|
|
db.commit()
|
|
|
|
|
|
|
|
|
|
return RedirectResponse("/connections", 303)
|
|
|
|
|
|
|
|
|
|
|
2026-03-05 21:33:41 +03:00
|
|
|
@router.post("/disconnect")
|
|
|
|
|
async def evotor_disconnect(
|
|
|
|
|
request: Request,
|
|
|
|
|
db: Session = Depends(get_db),
|
|
|
|
|
user: User | None = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
if not user:
|
|
|
|
|
return RedirectResponse("/login", 303)
|
|
|
|
|
|
|
|
|
|
connection = db.query(EvotorConnection).filter(EvotorConnection.user_id == user.id).first()
|
|
|
|
|
if connection:
|
|
|
|
|
db.delete(connection)
|
|
|
|
|
db.commit()
|
|
|
|
|
|
2026-03-06 15:26:49 +03:00
|
|
|
return RedirectResponse("/connections", 303)
|