-
Notifications
You must be signed in to change notification settings - Fork 113
Feat/swagger auth #1141
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
Open
Dawn0472
wants to merge
7
commits into
master
Choose a base branch
from
feat/swagger-auth
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/swagger auth #1141
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f3c0d39
feat(swagger): add drf-yasg to automatically generate swagger in dev env
josix 4ef0894
fix: indent
mattwang44 ec0984d
fix auth for swagger
Dawn0472 bd15fa3
fix code style error
Dawn0472 396da1f
fix code style error
Dawn0472 9a9c08d
fix test error
Dawn0472 287fc55
fix permission error
Dawn0472 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,48 @@ | ||
| from rest_framework.authentication import TokenAuthentication | ||
|
|
||
| from rest_framework import exceptions | ||
| from rest_framework import HTTP_HEADER_ENCODING, exceptions | ||
| from django.utils.translation import gettext_lazy as _ | ||
| from .models import Token | ||
|
|
||
|
|
||
| class TokenAuthentication(TokenAuthentication): | ||
| class BearerAuthentication(TokenAuthentication): | ||
| keyword = 'Bearer' | ||
| model = Token | ||
| def get_model(self): | ||
| if self.model is not None: | ||
| return self.model | ||
| from rest_framework.authtoken.models import Token | ||
| return Token | ||
|
|
||
| def get_authorization_header(self,request): | ||
| """ | ||
| Return request's 'Authorization:' header, as a bytestring. | ||
| Hide some test client ickyness where the header can be unicode. | ||
| """ | ||
| auth = request.META.get('HTTP_AUTHORIZATION', b'') | ||
| if isinstance(auth, str): | ||
| # Work around django test client oddness | ||
| auth = auth.encode(HTTP_HEADER_ENCODING) | ||
| return auth | ||
|
|
||
| def authenticate(self, request): | ||
| auth = self.get_authorization_header(request).split() | ||
|
|
||
| if not auth : | ||
| return None | ||
|
|
||
| token = auth[0].decode() | ||
|
|
||
| return self.authenticate_credentials(token) | ||
|
|
||
| def authenticate_credentials(self, key): | ||
| model = self.get_model() | ||
| try: | ||
| token = model.objects.select_related('user').get(key=key) | ||
| except model.DoesNotExist: | ||
| raise exceptions.AuthenticationFailed(_('Invalid token.')) | ||
|
|
||
| if not token.user.is_active: | ||
| raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) | ||
|
|
||
| return (token.user, token) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,11 +4,28 @@ | |
| from django.conf.urls.static import static | ||
| from django.contrib import admin | ||
| from django.views.i18n import set_language | ||
| from rest_framework import permissions | ||
| from drf_yasg.views import get_schema_view | ||
| from drf_yasg import openapi | ||
|
|
||
| from core.views import error_page, flat_page, index | ||
| from users.views import user_dashboard | ||
|
|
||
|
|
||
| schema_view = get_schema_view( | ||
| openapi.Info( | ||
| title="Snippets API", | ||
| default_version='v1', | ||
| description="Test description", | ||
| terms_of_service="https://www.google.com/policies/terms/", | ||
| contact=openapi.Contact(email="[email protected]"), | ||
| license=openapi.License(name="BSD License"), | ||
| ), | ||
| public=True, | ||
| permission_classes=(permissions.AllowAny,), | ||
| ) | ||
|
|
||
|
|
||
| urlpatterns = i18n_patterns( | ||
|
|
||
| # Add top-level URL patterns here. | ||
|
|
@@ -35,7 +52,8 @@ | |
| url(r'^api/events/', include('events.api.urls', namespace="events")), | ||
| url(r'^set-language/$', set_language, name='set_language'), | ||
| url(r'^admin/', admin.site.urls), | ||
| url(r'^api/attendee/', include('attendee.api.urls')) | ||
| url(r'^api/attendee/', include('attendee.api.urls')), | ||
| url(r'^api/users/', include('users.api.urls')), | ||
| ] | ||
|
|
||
| # User-uploaded files like profile pics need to be served in development. | ||
|
|
@@ -45,3 +63,8 @@ | |
| if settings.DEBUG: | ||
| import debug_toolbar | ||
| urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls))] | ||
| urlpatterns += [ | ||
| url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), | ||
| url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), | ||
| url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from django.urls import path | ||
| from users.api.views import CustomAuthToken | ||
|
|
||
|
|
||
| urlpatterns = [ | ||
| path("api-token-auth/", CustomAuthToken.as_view()), | ||
|
|
||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| from rest_framework.response import Response | ||
| from rest_framework.authtoken.views import ObtainAuthToken | ||
|
|
||
| from core.models import Token | ||
| from drf_yasg.utils import swagger_auto_schema | ||
| from drf_yasg import openapi | ||
| from rest_framework import exceptions | ||
| from django.contrib.auth import get_user_model | ||
| from users.models import User | ||
| from datetime import datetime, timedelta | ||
|
|
||
|
|
||
| class CustomAuthToken(ObtainAuthToken): | ||
| @swagger_auto_schema( | ||
| request_body=openapi.Schema( | ||
| type=openapi.TYPE_OBJECT, | ||
| required=['username','password'], | ||
| order=['username', 'password'], | ||
| properties={ | ||
| 'username':openapi.Schema(type=openapi.TYPE_STRING), | ||
| 'password':openapi.Schema(type=openapi.TYPE_STRING) | ||
| }, | ||
| ), | ||
| operation_description='Get account token' | ||
| ) | ||
|
|
||
| def post(self, request): | ||
| username = request.data['username'] | ||
| try: | ||
| user = get_user_model().objects.get(email=username) | ||
| except User.DoesNotExist: | ||
| raise exceptions.AuthenticationFailed(('User matching query does not exist')) | ||
|
|
||
| tokens = Token.objects.filter(user=user) | ||
| if len(tokens)== 0: | ||
| Token.objects.create(user=user) | ||
|
|
||
| token = Token.objects.get(user=user) | ||
| token = str(token) | ||
|
|
||
| token_create_time = Token.objects.get(key=token).created | ||
| pre_week_day = datetime.now(token_create_time.tzinfo) + timedelta(days=-7) | ||
| if token_create_time < pre_week_day: | ||
| Token.objects.get(key=token).delete() | ||
| Token.objects.create(user=user) | ||
|
|
||
| serializer = self.serializer_class(data=request.data, context={'request': request}) | ||
| serializer.is_valid(raise_exception=True) | ||
| user = serializer.validated_data['user'] | ||
|
|
||
| return Response({ | ||
| 'username': user.email, | ||
| 'token': token | ||
| }) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.