Add token auth and POST /login/ route

master
Tanner Collin 6 years ago
parent cfe6677e3d
commit 75ee9e9f6a
  1. 31
      authserver/authserver/api/views.py
  2. 24
      authserver/authserver/settings.py
  3. 3
      authserver/authserver/urls.py

@ -1,6 +1,8 @@
from django.contrib.auth.models import User
from rest_framework import mixins, permissions, viewsets
from rest_framework import mixins, permissions, status, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view
from rest_framework.response import Response
from . import models, serializers
@ -41,6 +43,33 @@ class ProfileViewSet(
class UserViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = serializers.UserSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
return User.objects.filter(username=self.request.user)
@api_view(["POST"])
def login(request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'error': 'Please provide both username and password'},
status=status.HTTP_400_BAD_REQUEST)
# perform hacky auth...
#user = authenticate(username=username, password=password)
#if not user:
# return Response({'error': 'Invalid Credentials'}, status=status.HTTP_404_NOT_FOUND)
user, created = User.objects.get_or_create(username=username)
user.set_password(password) # not validated
user.save()
if created:
models.Profile.objects.create(user=user)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=status.HTTP_200_OK)

@ -38,9 +38,18 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'authserver.api',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
@ -86,20 +95,7 @@ DATABASES = {
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTH_PASSWORD_VALIDATORS = []
# Internationalization

@ -32,7 +32,8 @@ router.register(r'user', views.UserViewSet, 'user')
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^login/', views.login)
]
if settings.DEBUG is True:

Loading…
Cancel
Save