skillbox/server/registration/mutations_public.py

74 lines
2.6 KiB
Python

# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
#
# Created on 2019-10-08
# @author: chrigu <christian.cueni@iterativ.ch>
import graphene
from django.conf import settings
from graphene import relay
from registration.models import License
from registration.serializers import RegistrationSerializer
from users.models import User, Role, UserRole
from users.mutations import UpdateError, FieldError
class Registration(relay.ClientIDMutation):
class Input:
firstname_input = graphene.String()
lastname_input = graphene.String()
email_input = graphene.String()
license_key_input = graphene.String()
success = graphene.Boolean()
errors = graphene.List(UpdateError) # todo: change for consistency
@classmethod
def mutate_and_get_payload(cls, root, info, **kwargs):
first_name = kwargs.get('firstname_input')
last_name = kwargs.get('lastname_input')
email = kwargs.get('email_input')
license_key = kwargs.get('license_key_input')
registration_data = {
'first_name': first_name,
'last_name': last_name,
'email': email,
'license_key': license_key,
}
serializer = RegistrationSerializer(data=registration_data)
if serializer.is_valid():
user = User.objects.create_user_with_random_password(serializer.data['first_name'],
serializer.data['last_name'],
serializer.data['email'])
sb_license = License.objects.create(licensee=user, license_type=serializer.context['license_type'])
if sb_license.license_type.is_teacher_license():
teacher_role = Role.objects.get(key=Role.objects.TEACHER_KEY)
UserRole.objects.get_or_create(user=user, role=teacher_role)
# create class
else:
student_role = Role.objects.get(key=Role.objects.STUDENT_KEY)
UserRole.objects.get_or_create(user=user, role=student_role)
return cls(success=True)
errors = []
for key, value in serializer.errors.items():
error = UpdateError(field=key, errors=[])
for field_error in serializer.errors[key]:
error.errors.append(FieldError(code=field_error.code))
errors.append(error)
return cls(success=False, errors=errors)
class RegistrationMutations:
registration = Registration.Field()