You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

75 lines
2.8 KiB

from datetime import timedelta
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from rest_framework import serializers
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.compat import authenticate
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from rest_framework import status
from apps.auth.models import TempToken
User = get_user_model()
class AuthTokenSerializer(serializers.Serializer):
user_id = serializers.IntegerField(required=False)
email = serializers.CharField(label=_("Email"), required=False)
password = serializers.CharField(
label=_("Password"),
style={'input_type': 'password'},
trim_whitespace=False,
required=False,
)
def validate(self, attrs):
user_id = attrs.get('user_id')
email = attrs.get('email')
password = attrs.get('password')
request = self.context.get('request')
if email and password:
user = authenticate(request=request, email=email, password=password)
# The authenticate call simply returns None for is_active=False
# users. (Assuming the default ModelBackend authentication
# backend.)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
elif user.role != User.ADMIN_ROLE:
msg = _('Only admin have permission to login admin page.')
raise serializers.ValidationError(msg, code='authorization')
elif user_id and request.user.is_authenticated and request.user.role == User.ADMIN_ROLE:
user = get_object_or_404(User, pk=user_id)
else:
msg = _('Must include "email" and "password".')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
class ObtainToken(ObtainAuthToken):
serializer_class = AuthTokenSerializer
class ObtainTempToken(APIView):
def get(self, request):
user_id = request.GET.get('user')
if user_id and request.user.is_authenticated and request.user.role == User.ADMIN_ROLE:
user = get_object_or_404(User, pk=user_id)
token, created = TempToken.objects.get_or_create(user=user)
if not created and now() - token.created > timedelta(hours=1):
token.delete()
token = TempToken.objects.create(user=user)
return Response({'temp_token': token.key})
return Response(status=status.HTTP_400_BAD_REQUEST)