webhook-fix

This commit is contained in:
Untone 2024-03-03 16:59:15 +03:00
parent ab7d677a20
commit ad0dc98bc9
3 changed files with 45 additions and 25 deletions

View File

@ -219,10 +219,19 @@ async def get_author_follows_authors(_, _info, slug='', user=None, author_id=Non
def create_author(user_id: str, slug: str, name: str = ''): def create_author(user_id: str, slug: str, name: str = ''):
with local_session() as session: with local_session() as session:
try:
author = None
if user_id:
author = session.query(Author).filter(Author.user == user_id).first()
elif slug:
author = session.query(Author).filter(Author.slug == slug).first()
if not author:
new_author = Author(user=user_id, slug=slug, name=name) new_author = Author(user=user_id, slug=slug, name=name)
session.add(new_author) session.add(new_author)
session.commit() session.commit()
logger.info(f'author created by webhook {new_author.dict()}') logger.info(f'author created by webhook {new_author.dict()}')
except Exception as exc:
logger.debug(exc)
@query.field('get_author_followers') @query.field('get_author_followers')

View File

@ -30,6 +30,7 @@ fmt_config = {
'reset': True, 'reset': True,
} }
class MultilineColoredFormatter(colorlog.ColoredFormatter): class MultilineColoredFormatter(colorlog.ColoredFormatter):
def format(self, record): def format(self, record):
# Check if the message is multiline # Check if the message is multiline

View File

@ -4,9 +4,9 @@ import re
from starlette.endpoints import HTTPEndpoint from starlette.endpoints import HTTPEndpoint
from starlette.requests import Request from starlette.requests import Request
from starlette.responses import JSONResponse from starlette.responses import JSONResponse
from starlette.exceptions import HTTPException
from orm.author import Author from orm.author import Author
from resolvers.author import create_author
from services.db import local_session from services.db import local_session
from services.logger import root_logger as logger from services.logger import root_logger as logger
@ -15,28 +15,38 @@ class WebhookEndpoint(HTTPEndpoint):
async def post(self, request: Request) -> JSONResponse: async def post(self, request: Request) -> JSONResponse:
try: try:
data = await request.json() data = await request.json()
if data: if not data:
raise HTTPException(status_code=400, detail="Request body is empty")
auth = request.headers.get('Authorization') auth = request.headers.get('Authorization')
if auth: if not auth or auth != os.environ.get('WEBHOOK_SECRET'):
if auth == os.environ.get('WEBHOOK_SECRET'): raise HTTPException(status_code=401, detail="Invalid Authorization header")
logger.debug(data) logger.debug(data)
user = data.get('user') user = data.get('user')
if isinstance(user, dict): if not isinstance(user, dict):
raise HTTPException(status_code=400, detail="User data is not a dictionary")
user_id: str = user.get('id') user_id: str = user.get('id')
name: str = user.get('given_name', user.get('slug')) name: str = user.get('given_name', user.get('slug'))
slug: str = user.get('email', '').split('@')[0] email: str = user.get('email', '')
slug: str = re.sub('[^0-9a-z]+', '-', slug.lower()) pic: str = user.get('picture', '')
with local_session() as session: with local_session() as session:
author = ( author = session.query(Author).filter(Author.email == email).first()
session.query(Author) if not author:
.filter(Author.slug == slug) # If the author does not exist, create a new one
.first() slug: str = email.split('@')[0].replace(".", "-").lower()
) slug: str = re.sub('[^0-9a-z]+', '-', slug)
if author: while True:
slug = slug + '-' + user_id.split('-').pop() author = session.query(Author).filter(Author.slug == slug).first()
create_author(user_id, slug, name) if not author:
break
slug = f"{slug}-{len(session.query(Author).filter(Author.email == email).all()) + 1}"
author = Author(user_id=user_id, slug=slug, name=name, pic=pic)
session.add(author)
session.commit()
return JSONResponse({'status': 'success'}) return JSONResponse({'status': 'success'})
except HTTPException as e:
return JSONResponse({'status': 'error', 'message': str(e.detail)}, status_code=e.status_code)
except Exception as e: except Exception as e:
import traceback import traceback