Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Created September 10, 2019 21:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchtabian/285f8f51feed9c0beda8c7a12353f8f1 to your computer and use it in GitHub Desktop.
Save mitchtabian/285f8f51feed9c0beda8c7a12353f8f1 to your computer and use it in GitHub Desktop.
from rest_framework.views import APIView
from django.contrib.auth import authenticate
class ObtainAuthTokenView(APIView):
authentication_classes = []
permission_classes = []
def post(self, request):
context = {}
email = request.POST.get('username')
password = request.POST.get('password')
account = authenticate(email=email, password=password)
if account:
try:
token = Token.objects.get(user=account)
except Token.DoesNotExist:
token = Token.objects.create(user=account)
context['response'] = 'Successfully authenticated.'
context['pk'] = account.pk
context['email'] = email
context['token'] = token.key
else:
context['response'] = 'Error'
context['error_message'] = 'Invalid credentials'
return Response(context)
from django.urls import path
from account.api.views import(
registration_view,
account_properties_view,
update_account_view,
ObtainAuthTokenView,
)
app_name = 'account'
urlpatterns = [
path('properties', account_properties_view, name="properties"),
path('properties/update', update_account_view, name="update"),
path('login', ObtainAuthTokenView.as_view(), name="login"), # -> see accounts/api/views.py for response and url info
path('register', registration_view, name="register"),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment