add_author_stat-fix+fmt

This commit is contained in:
2024-03-06 12:25:55 +03:00
parent 70589a35da
commit 9f881c0641
15 changed files with 241 additions and 138 deletions

View File

@@ -15,14 +15,18 @@ class WebhookEndpoint(HTTPEndpoint):
try:
data = await request.json()
if not data:
raise HTTPException(status_code=400, detail="Request body is empty")
raise HTTPException(status_code=400, detail='Request body is empty')
auth = request.headers.get('Authorization')
if not auth or auth != os.environ.get('WEBHOOK_SECRET'):
raise HTTPException(status_code=401, detail="Invalid Authorization header")
raise HTTPException(
status_code=401, detail='Invalid Authorization header'
)
# logger.debug(data)
user = data.get('user')
if not isinstance(user, dict):
raise HTTPException(status_code=400, detail="User data is not a dictionary")
raise HTTPException(
status_code=400, detail='User data is not a dictionary'
)
user_id: str = user.get('id')
name: str = user.get('given_name', user.get('slug'))
email: str = user.get('email', '')
@@ -32,20 +36,24 @@ class WebhookEndpoint(HTTPEndpoint):
author = session.query(Author).filter(Author.user == user_id).first()
if not author:
# If the author does not exist, create a new one
slug: str = email.split('@')[0].replace(".", "-").lower()
slug: str = email.split('@')[0].replace('.', '-').lower()
slug: str = re.sub('[^0-9a-z]+', '-', slug)
while True:
author = session.query(Author).filter(Author.slug == slug).first()
author = (
session.query(Author).filter(Author.slug == slug).first()
)
if not author:
break
slug = f"{slug}-{len(session.query(Author).filter(Author.email == email).all()) + 1}"
slug = f'{slug}-{len(session.query(Author).filter(Author.email == email).all()) + 1}'
author = Author(user=user_id, slug=slug, name=name, pic=pic)
session.add(author)
session.commit()
return JSONResponse({'status': 'success'})
except HTTPException as e:
return JSONResponse({'status': 'error', 'message': str(e.detail)}, status_code=e.status_code)
return JSONResponse(
{'status': 'error', 'message': str(e.detail)}, status_code=e.status_code
)
except Exception as e:
import traceback