[mastodon] Return 422 error for invalid input when creating mastodon bot
This commit is contained in:
parent
3114faedb8
commit
3f68b65e17
|
@ -35,6 +35,7 @@ install_requires =
|
|||
requests
|
||||
scrypt
|
||||
Mastodon.py
|
||||
pydantic[email]
|
||||
|
||||
[options.packages.find]
|
||||
where = src
|
||||
|
|
|
@ -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,
|
||||
|
|
Loading…
Reference in a new issue