Return token and user on signup/login.

This commit is contained in:
Tom Hacohen 2020-05-14 17:19:18 +03:00
parent 93a0e41f03
commit e9e77945a6
2 changed files with 21 additions and 8 deletions

View File

@ -206,8 +206,14 @@ class UserSerializer(serializers.ModelSerializer):
fields = (User.USERNAME_FIELD, User.EMAIL_FIELD)
class UserQuerySerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (User.USERNAME_FIELD, User.EMAIL_FIELD)
class AuthenticationSignupSerializer(serializers.Serializer):
user = UserSerializer(many=False)
user = UserQuerySerializer(many=False)
salt = BinaryBase64Field()
pubkey = BinaryBase64Field()
@ -217,7 +223,7 @@ class AuthenticationSignupSerializer(serializers.Serializer):
pubkey = validated_data.pop('pubkey')
with transaction.atomic():
instance = UserSerializer.Meta.model.objects.create(**validated_data)
instance = User.objects.create(**validated_data)
instance.set_unusable_password()
models.UserInfo.objects.create(salt=salt, pubkey=pubkey, owner=instance)

View File

@ -44,7 +44,8 @@ from .serializers import (
CollectionSerializer,
CollectionItemSerializer,
CollectionItemRevisionSerializer,
CollectionItemChunkSerializer
CollectionItemChunkSerializer,
UserSerializer,
)
@ -313,6 +314,12 @@ class AuthenticationViewSet(viewsets.ViewSet):
def get_queryset(self):
return User.objects.all()
def login_response_data(self, user):
return {
'token': Token.objects.get_or_create(user=user)[0].key,
'user': UserSerializer(user).data,
}
def list(self, request):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
@ -320,9 +327,10 @@ class AuthenticationViewSet(viewsets.ViewSet):
def signup(self, request):
serializer = AuthenticationSignupSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
user = serializer.save()
return Response({}, status=status.HTTP_201_CREATED)
data = self.login_response_data(user)
return Response(data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@ -360,6 +368,7 @@ class AuthenticationViewSet(viewsets.ViewSet):
ret = {
"salt": b64encode(salt),
"challenge": b64encode(challenge),
"version": user.userinfo.version,
}
return Response(ret, status=status.HTTP_200_OK)
@ -401,9 +410,7 @@ class AuthenticationViewSet(viewsets.ViewSet):
verify_key = nacl.signing.VerifyKey(user.userinfo.pubkey, encoder=nacl.encoding.RawEncoder)
verify_key.verify(response_raw, signature)
data = {
'token': Token.objects.get_or_create(user=user)[0].key,
}
data = self.login_response_data(user)
return Response(data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)