Skip to content

Commit

Permalink
use masto api token for neodb api
Browse files Browse the repository at this point in the history
  • Loading branch information
Her Email committed Nov 13, 2023
1 parent 8a3a552 commit 814445a
Show file tree
Hide file tree
Showing 5 changed files with 162 additions and 23 deletions.
5 changes: 1 addition & 4 deletions boofilsic/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,10 +312,7 @@

SESSION_COOKIE_NAME = "neodbsid"

AUTHENTICATION_BACKENDS = [
"mastodon.auth.OAuth2Backend",
"oauth2_provider.backends.OAuth2Backend",
]
AUTHENTICATION_BACKENDS = ["mastodon.auth.OAuth2Backend"]

LOGGING = {
"version": 1,
Expand Down
27 changes: 8 additions & 19 deletions common/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
from typing import Any, Callable, List, Optional, Tuple, Type

from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.db.models import QuerySet
from ninja import NinjaAPI, Schema
from ninja.pagination import PageNumberPagination as NinjaPageNumberPagination
from ninja.security import HttpBearer
from oauth2_provider.oauth2_backends import OAuthLibCore
from oauth2_provider.oauth2_validators import OAuth2Validator
from oauthlib.oauth2 import Server

from takahe.utils import Takahe

_logger = logging.getLogger(__name__)

Expand All @@ -19,23 +19,12 @@

class OAuthAccessTokenAuth(HttpBearer):
def authenticate(self, request, token) -> bool:
if not token or not request.user.is_authenticated:
_logger.debug("API auth: no access token or user not authenticated")
return False
request_scopes = []
request_method = request.method
if request_method in PERMITTED_READ_METHODS:
request_scopes = ["read"]
elif request_method in PERMITTED_WRITE_METHODS:
request_scopes = ["write"]
if not token:
_logger.debug("API auth: no access token")
request.user = AnonymousUser()
else:
return False
validator = OAuth2Validator()
core = OAuthLibCore(Server(validator))
valid, oauthlib_req = core.verify_request(request, scopes=request_scopes)
if not valid:
_logger.debug(f"API auth: request scope {request_scopes} not verified")
return valid
request.user = Takahe.get_local_user_by_token(token) or AnonymousUser()
return request.user and request.user.is_authenticated


class EmptyResult(Schema):
Expand Down
76 changes: 76 additions & 0 deletions takahe/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,4 +647,80 @@ class Migration(migrations.Migration):
"db_table": "users_invite",
},
),
migrations.CreateModel(
name="Application",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("client_id", models.CharField(max_length=500)),
("client_secret", models.CharField(max_length=500)),
("redirect_uris", models.TextField()),
("scopes", models.TextField()),
("name", models.CharField(max_length=500)),
("website", models.CharField(blank=True, max_length=500, null=True)),
("created", models.DateTimeField(auto_now_add=True)),
("updated", models.DateTimeField(auto_now=True)),
],
options={
"db_table": "api_application",
},
),
migrations.CreateModel(
name="Token",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("token", models.CharField(max_length=500, unique=True)),
("scopes", models.JSONField()),
("created", models.DateTimeField(auto_now_add=True)),
("updated", models.DateTimeField(auto_now=True)),
("revoked", models.DateTimeField(blank=True, null=True)),
("push_subscription", models.JSONField(blank=True, null=True)),
(
"application",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="tokens",
to="takahe.application",
),
),
(
"identity",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="tokens",
to="takahe.identity",
),
),
(
"user",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="tokens",
to="takahe.user",
),
),
],
options={
"db_table": "api_token",
},
),
]
65 changes: 65 additions & 0 deletions takahe/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1653,3 +1653,68 @@ class Meta:
unique_together = [
("key", "user", "identity", "domain"),
]


class Application(models.Model):
"""
OAuth applications
"""

client_id = models.CharField(max_length=500)
client_secret = models.CharField(max_length=500)

redirect_uris = models.TextField()
scopes = models.TextField()

name = models.CharField(max_length=500)
website = models.CharField(max_length=500, blank=True, null=True)

created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

class Meta:
# managed = False
db_table = "api_application"


class Token(models.Model):
"""
An (access) token to call the API with.
Can be either tied to a user, or app-level only.
"""

application = models.ForeignKey(
"takahe.Application",
on_delete=models.CASCADE,
related_name="tokens",
)

user = models.ForeignKey(
"takahe.User",
blank=True,
null=True,
on_delete=models.CASCADE,
related_name="tokens",
)

identity = models.ForeignKey(
"takahe.Identity",
blank=True,
null=True,
on_delete=models.CASCADE,
related_name="tokens",
)

token = models.CharField(max_length=500, unique=True)
scopes = models.JSONField()

created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
revoked = models.DateTimeField(blank=True, null=True)

push_subscription = models.JSONField(blank=True, null=True)

class Meta:
# managed = False
db_table = "api_token"
12 changes: 12 additions & 0 deletions takahe/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,3 +603,15 @@ def verify_invite(token):
return False
invite = Invite.objects.filter(token=token).first()
return invite and invite.valid

@staticmethod
def get_local_user_by_token(token):
from users.models import APIdentity

if not token:
return None
t = Token.objects.filter(token=token, revoked__isnull=True).first()
if not t or not t.identity:
return None
identity = APIdentity.objects.filter(pk=t.identity.pk).first()
return identity.user if identity else None

0 comments on commit 814445a

Please sign in to comment.