summaryrefslogtreecommitdiffstats
path: root/api
diff options
context:
space:
mode:
Diffstat (limited to 'api')
-rw-r--r--api/decorators.py19
-rw-r--r--api/middleware.py27
-rw-r--r--api/schemas/__init__.py108
-rw-r--r--api/views/__init__.py3
-rw-r--r--api/views/accounts.py9
-rw-r--r--api/views/apps.py14
-rw-r--r--api/views/instance.py1
-rw-r--r--api/views/oauth.py4
-rw-r--r--api/views/timelines.py23
9 files changed, 192 insertions, 16 deletions
diff --git a/api/decorators.py b/api/decorators.py
new file mode 100644
index 0000000..b60cc05
--- /dev/null
+++ b/api/decorators.py
@@ -0,0 +1,19 @@
+from functools import wraps
+
+from django.http import JsonResponse
+
+
+def identity_required(function):
+ """
+ API version of the identity_required decorator that just makes sure the
+ token is tied to one, not an app only.
+ """
+
+ @wraps(function)
+ def inner(request, *args, **kwargs):
+ # They need an identity
+ if not request.identity:
+ return JsonResponse({"error": "identity_token_required"}, status=400)
+ return function(request, *args, **kwargs)
+
+ return inner
diff --git a/api/middleware.py b/api/middleware.py
new file mode 100644
index 0000000..84eddca
--- /dev/null
+++ b/api/middleware.py
@@ -0,0 +1,27 @@
+from django.http import HttpResponse
+
+from api.models import Token
+
+
+class ApiTokenMiddleware:
+ """
+ Adds request.user and request.identity if an API token appears.
+ Also nukes request.session so it can't be used accidentally.
+ """
+
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ auth_header = request.headers.get("authorization", None)
+ if auth_header and auth_header.startswith("Bearer "):
+ token_value = auth_header[7:]
+ try:
+ token = Token.objects.get(token=token_value)
+ except Token.DoesNotExist:
+ return HttpResponse("Invalid Bearer token", status=400)
+ request.user = token.user
+ request.identity = token.identity
+ request.session = None
+ response = self.get_response(request)
+ return response
diff --git a/api/schemas/__init__.py b/api/schemas/__init__.py
new file mode 100644
index 0000000..cc0660c
--- /dev/null
+++ b/api/schemas/__init__.py
@@ -0,0 +1,108 @@
+from typing import Literal, Optional, Union
+
+from ninja import Field, Schema
+
+
+class Application(Schema):
+ id: str
+ name: str
+ website: str | None
+ client_id: str
+ client_secret: str
+ redirect_uri: str = Field(alias="redirect_uris")
+
+
+class CustomEmoji(Schema):
+ shortcode: str
+ url: str
+ static_url: str
+ visible_in_picker: bool
+ category: str
+
+
+class AccountField(Schema):
+ name: str
+ value: str
+ verified_at: str | None
+
+
+class Account(Schema):
+ id: str
+ username: str
+ acct: str
+ url: str
+ display_name: str
+ note: str
+ avatar: str
+ avatar_static: str
+ header: str
+ header_static: str
+ locked: bool
+ fields: list[AccountField]
+ emojis: list[CustomEmoji]
+ bot: bool
+ group: bool
+ discoverable: bool
+ moved: Union[None, bool, "Account"]
+ suspended: bool
+ limited: bool
+ created_at: str
+ last_status_at: str | None = Field(...)
+ statuses_count: int
+ followers_count: int
+ following_count: int
+
+
+class MediaAttachment(Schema):
+ id: str
+ type: Literal["unknown", "image", "gifv", "video", "audio"]
+ url: str
+ preview_url: str
+ remote_url: str | None
+ meta: dict
+ description: str | None
+ blurhash: str | None
+
+
+class StatusMention(Schema):
+ id: str
+ username: str
+ url: str
+ acct: str
+
+
+class StatusTag(Schema):
+ name: str
+ url: str
+
+
+class Status(Schema):
+ id: str
+ uri: str
+ created_at: str
+ account: Account
+ content: str
+ visibility: Literal["public", "unlisted", "private", "direct"]
+ sensitive: bool
+ spoiler_text: str
+ media_attachments: list[MediaAttachment]
+ mentions: list[StatusMention]
+ tags: list[StatusTag]
+ emojis: list[CustomEmoji]
+ reblogs_count: int
+ favourites_count: int
+ replies_count: int
+ url: str | None = Field(...)
+ in_reply_to_id: str | None = Field(...)
+ in_reply_to_account_id: str | None = Field(...)
+ reblog: Optional["Status"] = Field(...)
+ poll: None = Field(...)
+ card: None = Field(...)
+ language: None = Field(...)
+ text: str | None = Field(...)
+ edited_at: str | None
+ favourited: bool | None
+ reblogged: bool | None
+ muted: bool | None
+ bookmarked: bool | None
+ pinned: bool | None
diff --git a/api/views/__init__.py b/api/views/__init__.py
index d661e7c..93cf419 100644
--- a/api/views/__init__.py
+++ b/api/views/__init__.py
@@ -1,3 +1,6 @@
+from .accounts import * # noqa
from .apps import * # noqa
from .base import api # noqa
from .instance import * # noqa
+from .oauth import * # noqa
+from .timelines import * # noqa
diff --git a/api/views/accounts.py b/api/views/accounts.py
new file mode 100644
index 0000000..79906dc
--- /dev/null
+++ b/api/views/accounts.py
@@ -0,0 +1,9 @@
+from .. import schemas
+from ..decorators import identity_required
+from .base import api
+
+
+@api.get("/v1/accounts/verify_credentials", response=schemas.Account)
+@identity_required
+def verify_credentials(request):
+ return request.identity.to_mastodon_json()
diff --git a/api/views/apps.py b/api/views/apps.py
index 33ecf0f..1642ee9 100644
--- a/api/views/apps.py
+++ b/api/views/apps.py
@@ -1,7 +1,8 @@
import secrets
-from ninja import Field, Schema
+from ninja import Schema
+from .. import schemas
from ..models import Application
from .base import api
@@ -13,16 +14,7 @@ class CreateApplicationSchema(Schema):
website: None | str = None
-class ApplicationSchema(Schema):
- id: str
- name: str
- website: str | None
- client_id: str
- client_secret: str
- redirect_uri: str = Field(alias="redirect_uris")
-
-
-@api.post("/v1/apps", response=ApplicationSchema)
+@api.post("/v1/apps", response=schemas.Application)
def add_app(request, details: CreateApplicationSchema):
client_id = "tk-" + secrets.token_urlsafe(16)
client_secret = secrets.token_urlsafe(40)
diff --git a/api/views/instance.py b/api/views/instance.py
index 5923d30..eef258d 100644
--- a/api/views/instance.py
+++ b/api/views/instance.py
@@ -9,7 +9,6 @@ from .base import api
@api.get("/v1/instance")
-@api.get("/v1/instance/")
def instance_info(request):
return {
"uri": request.headers.get("host", settings.SETUP.MAIN_DOMAIN),
diff --git a/api/views/oauth.py b/api/views/oauth.py
index 6be2778..b97ce5a 100644
--- a/api/views/oauth.py
+++ b/api/views/oauth.py
@@ -66,7 +66,6 @@ class AuthorizationView(LoginRequiredMixin, TemplateView):
class TokenView(View):
def post(self, request):
grant_type = request.POST["grant_type"]
- scopes = set(self.request.POST.get("scope", "read").split())
try:
application = Application.objects.get(
client_id=self.request.POST["client_id"]
@@ -84,9 +83,6 @@ class TokenView(View):
token = Token.objects.get(code=code, application=application)
except Token.DoesNotExist:
return JsonResponse({"error": "invalid_code"}, status=400)
- # Verify the scopes match the token
- if scopes != set(token.scopes):
- return JsonResponse({"error": "invalid_scope"}, status=400)
# Update the token to remove its code
token.code = None
token.save()
diff --git a/api/views/timelines.py b/api/views/timelines.py
new file mode 100644
index 0000000..5de0e0f
--- /dev/null
+++ b/api/views/timelines.py
@@ -0,0 +1,23 @@
+from activities.models import TimelineEvent
+
+from .. import schemas
+from ..decorators import identity_required
+from .base import api
+
+
+@api.get("/v1/timelines/home", response=list[schemas.Status])
+@identity_required
+def home(request):
+ if request.GET.get("max_id"):
+ return []
+ limit = int(request.GET.get("limit", "20"))
+ events = (
+ TimelineEvent.objects.filter(
+ identity=request.identity,
+ type__in=[TimelineEvent.Types.post],
+ )
+ .select_related("subject_post", "subject_post__author")
+ .prefetch_related("subject_post__attachments")
+ .order_by("-created")[:limit]
+ )
+ return [event.subject_post.to_mastodon_json() for event in events]