Skip to content

Commit

Permalink
Release 1.11.2
Browse files Browse the repository at this point in the history
  • Loading branch information
albertoleoncio committed Dec 17, 2024
2 parents 2b855c7 + 8b95477 commit 6bf85a4
Show file tree
Hide file tree
Showing 8 changed files with 270 additions and 133 deletions.
7 changes: 5 additions & 2 deletions CapX/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"""
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.urls import path, include, re_path
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from rest_framework.routers import DefaultRouter
Expand All @@ -29,6 +29,7 @@
from orgs.views import OrganizationViewSet, OrganizationTypeViewSet
from events.views import EventViewSet, EventParticipantViewSet, EventOrganizationsViewSet
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from users.oauth import UserAuthView, AuthView, CheckView


router = DefaultRouter()
Expand All @@ -51,10 +52,12 @@
path('admin/', admin.site.urls),
path('api-auth/', include("rest_framework.urls", namespace="rest_framework")),
path('', include('social_django.urls')),
path('api/login/', include('rest_social_auth.urls_knox')),
path('tags/<str:tag_type>/<int:tag_id>/', UsersByTagViewSet.as_view({'get': 'list'}), name='tags'),
path("schema/", SpectacularAPIView.as_view(), name="schema"),
path("", SpectacularSwaggerView.as_view(url_name="schema"),name="swagger-ui",),
re_path(r'^api/login/social/knox_user/(?:(?P<provider>[a-zA-Z0-9_-]+)/?)?$', UserAuthView.as_view(), name='login_social_knox_user'),
re_path(r'^api/login/social/knox/(?:(?P<provider>[a-zA-Z0-9_-]+)/?)?$', AuthView.as_view(), name='login_social_knox'),
path('api/login/social/check/', CheckView.as_view(), name='login_social_check'),
path('', include(router.urls)),
]

Expand Down
3 changes: 0 additions & 3 deletions users/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,3 @@
class UserConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'

def ready(self):
import users.schema
22 changes: 22 additions & 0 deletions users/migrations/0012_authextrainfo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 4.2.11 on 2024-12-14 23:56

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('users', '0011_alter_language_language_autonym_and_more'),
]

operations = [
migrations.CreateModel(
name='AuthExtraInfo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.CharField(max_length=255, verbose_name='Oauth token')),
('extra', models.CharField(max_length=255, verbose_name='Extra info')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')),
],
),
]
109 changes: 109 additions & 0 deletions users/oauth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
from rest_social_auth.views import SocialKnoxUserAuthView, SocialKnoxOnlyAuthView
from rest_framework.response import Response
from datetime import timedelta
from django.utils.timezone import now
from drf_spectacular.utils import extend_schema
from .submodels import AuthExtraInfo


class AuthView(SocialKnoxOnlyAuthView):
request = {
'type': 'object',
'properties': {
'provider': {
'type': 'string',
'enum': ['mediawiki'],
'required': True,
'description': 'The provider of the OAuth token. This can be only "mediawiki".'
},
'extra': {'type': 'string', 'description': 'Extra information to store with the token'},
},
}

@extend_schema(
summary='Retrieve OAuth token',
description='This endpoint is used to retrieve the OAuth token for the user. The token is used to authenticate the user in the future.',
request={
('application/json'): request,
('application/x-www-form-urlencoded'): request,
('multipart/form-data'): request,
},
responses={(200, 'application/json'): {
'description': 'OAuth token retrieved successfully',
'type': 'object',
'properties': {
'oauth_token': {'type': 'string', 'description': 'The OAuth token'},
'oauth_token_secret': {'type': 'string', 'description': 'The OAuth token secret'},
'oauth_callback_confirmed': {'type': 'string', 'description': 'Whether the OAuth callback is confirmed or not'}
}
}}
)
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
AuthExtraInfo.objects.filter(created_at__lt=now() - timedelta(minutes=5)).delete()
if request.data.get('extra'):
AuthExtraInfo.objects.create(
token=response.data['oauth_token'],
extra=request.data['extra']
)
return response


class UserAuthView(SocialKnoxUserAuthView):
@extend_schema(
summary='Authenticate user using OAuth token',
description='This endpoint is used to authenticate the user using the OAuth token verifier. The OAuth token verifier is obtained from the OAuth provider.',
responses={(200, 'application/json'): {
'description': 'User authenticated successfully',
'type': 'object',
'properties': {
'id': {'type': 'integer', 'description': 'The user ID in the database'},
'token': {'type': 'string', 'description': 'The authorization token for use in the HTTP headers for future API requests'},
'username': {'type': 'string', 'description': 'The MediaWiki username'},
'email': {'type': 'string', 'description': 'The email address (should be empty for MediaWiki)'},
'user_groups': {'type': 'array', 'description': 'The user groups (should be null for MediaWiki)'},
'extra': {'type': 'string', 'description': 'Extra information stored with the token'}
}
}}
)
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
token = request.data['oauth_token']
if AuthExtraInfo.objects.filter(token=token).exists():
if isinstance(response.data, dict):
response.data['extra'] = AuthExtraInfo.objects.get(token=token).extra
return response

class CheckView(SocialKnoxOnlyAuthView):
request = {
'type': 'object',
'properties': {
'oauth_token': {
'type': 'string',
'required': True,
'description': 'The OAuth token to check'
}
},
}
@extend_schema(
summary='Check if the OAuth token exists and has extra information',
description='This endpoint is used to check if the OAuth token exists and has extra information stored with it.',
request={
('application/json'): request,
('application/x-www-form-urlencoded'): request,
('multipart/form-data'): request,
},
responses={(200, 'application/json'): {
'description': 'OAuth token checked successfully',
'type': 'object',
'properties': {
'exists': {'type': 'boolean', 'description': 'Whether the OAuth token exists or not'},
'extra': {'type': 'string', 'description': 'The extra information stored with the token'}
}
}}
)
def post(self, request, *args, **kwargs):
token = request.data['oauth_token']
exists = AuthExtraInfo.objects.filter(token=token).exists()
extra = AuthExtraInfo.objects.get(token=token).extra if exists else None
return Response({'exists': exists, 'extra': extra})
3 changes: 0 additions & 3 deletions users/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ def get_username(strategy, details, user=None, *args, **kwargs):
Returns:
- dict: A dictionary containing the username. If a user is provided, it returns {'username': user.username}.
Otherwise, it returns {'username': details['username']}.
"""
if user:
return {"username": user.username}
else:
return {"username": details['username']}
124 changes: 0 additions & 124 deletions users/schema.py

This file was deleted.

17 changes: 16 additions & 1 deletion users/submodels.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,19 @@ class WikimediaProject(models.Model):
)

def __str__(self):
return self.wikimedia_project_name
return self.wikimedia_project_name


class AuthExtraInfo(models.Model):
token = models.CharField(
verbose_name="Oauth token",
max_length=255,
)
extra = models.CharField(
verbose_name="Extra info",
max_length=255,
)
created_at = models.DateTimeField(
verbose_name="Created at",
auto_now_add=True
)
Loading

0 comments on commit 6bf85a4

Please sign in to comment.