Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unify api token for masto api and neodb api #375

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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