core/services/webhook.py

41 lines
1.5 KiB
Python
Raw Normal View History

2023-12-16 15:24:30 +00:00
import os
import re
from starlette.endpoints import HTTPEndpoint
from starlette.requests import Request
from starlette.responses import JSONResponse
from orm.author import Author
from resolvers.author import create_author
from services.db import local_session
class WebhookEndpoint(HTTPEndpoint):
async def post(self, request: Request) -> JSONResponse:
try:
data = await request.json()
if data:
2024-02-21 07:27:16 +00:00
auth = request.headers.get("Authorization")
2023-12-16 15:24:30 +00:00
if auth:
2024-02-21 07:27:16 +00:00
if auth == os.environ.get("WEBHOOK_SECRET"):
user_id: str = data["user"]["id"]
name: str = data["user"]["given_name"]
slug: str = data["user"]["email"].split("@")[0]
slug: str = re.sub("[^0-9a-z]+", "-", slug.lower())
2023-12-16 15:24:30 +00:00
with local_session() as session:
2024-02-21 07:27:16 +00:00
author = (
session.query(Author)
.filter(Author.slug == slug)
.first()
)
2023-12-16 15:24:30 +00:00
if author:
2024-02-21 07:27:16 +00:00
slug = slug + "-" + user_id.split("-").pop()
2023-12-16 16:59:43 +00:00
await create_author(user_id, slug, name)
2023-12-16 15:24:30 +00:00
2024-02-21 07:27:16 +00:00
return JSONResponse({"status": "success"})
2023-12-16 15:24:30 +00:00
except Exception as e:
import traceback
traceback.print_exc()
2024-02-21 07:27:16 +00:00
return JSONResponse({"status": "error", "message": str(e)}, status_code=500)