[mastodon] Return 422 error for invalid input when creating mastodon bot

This commit is contained in:
missytake 2023-03-18 21:59:23 +01:00
parent cb88c24e2e
commit f533efee4f
2 changed files with 20 additions and 5 deletions

View file

@ -35,6 +35,7 @@ install_requires =
requests
scrypt
Mastodon.py
pydantic[email]
[options.packages.find]
where = src

View file

@ -5,14 +5,14 @@
from fastapi import APIRouter, Depends, HTTPException, Response, status
from ormantic.exceptions import NoMatch
from pydantic import BaseModel
from pydantic import BaseModel, validate_email, validator
from kibicara.config import config
from kibicara.platforms.mastodon.bot import spawner
from kibicara.platforms.mastodon.model import MastodonAccount, MastodonInstance
from kibicara.webapi.hoods import get_hood, get_hood_unauthorized
from mastodon import Mastodon, MastodonError
from mastodon import Mastodon, MastodonError, MastodonNetworkError
from logging import getLogger
@ -29,6 +29,14 @@ class BodyMastodonAccount(BaseModel):
instance_url: str
password: str
@validator("email")
def validate_email(cls, value):
return validate_email(value)
class HTTPError(BaseModel):
status_code: int
async def get_mastodon(mastodon_id, hood=Depends(get_hood)):
try:
@ -141,7 +149,10 @@ async def mastodon_stop(mastodon=Depends(get_mastodon)):
@router.post(
"/",
status_code=status.HTTP_201_CREATED,
# TODO response_model
responses={
201: {"model": MastodonAccount},
422: {"model": HTTPError, "description": "Invalid Input"},
},
operation_id="create_mastodon",
)
async def mastodon_create(values: BodyMastodonAccount, hood=Depends(get_hood)):
@ -153,7 +164,10 @@ async def mastodon_create(values: BodyMastodonAccount, hood=Depends(get_hood)):
:param: values: a BodyMastodonAccount object in json
:param: hood: the hood ORM object
"""
try:
instance = await get_mastodon_instance(values.instance_url)
except MastodonNetworkError:
raise HTTPException(422, "Invalid Mastodon Instance")
account = Mastodon(
instance.client_id, instance.client_secret, api_base_url=values.instance_url
)
@ -161,7 +175,7 @@ async def mastodon_create(values: BodyMastodonAccount, hood=Depends(get_hood)):
access_token = account.log_in(values.email, values.password)
except MastodonError:
logger.warning("Login to Mastodon failed.", exc_info=True)
return # show error to user
return HTTPException(422, "Login to Mastodon failed")
return await MastodonAccount.objects.create(
hood=hood,
instance=instance,