Пример #1
0
    def get_clearbit_data(serializer):
        clearbit = ClearBit()

        if clearbit.is_available():
            # TODO move code to Celery queues
            data = {}
            clearbit_data = clearbit.get_person_enrichment(
                serializer.data.get('email'))

            # Checking clearbit data
            if clearbit_data is False or clearbit_data is None:
                return False

            # Merging data
            for i in serializer.data:
                data[i] = serializer.data[i]
            for i in clearbit_data:
                data[i] = clearbit_data[i]

            # Validate data
            serializer = CreateUserSerializer(data=data)
            serializer.is_valid(raise_exception=True)

            return serializer.data

        return False
Пример #2
0
def registration(request):
    CLIENT_ID = '9dGBsdHYqLICRZC4gKoNa57dkiHPIvh4PtxXZ0l5'
    CLIENT_SECRET = 'OU3LF7o9xGd1TuRvi5UBnrrUUQdd96uPBWqISAltkWArg4M8vANV0gSYplQ0uPtltcR71mjguqyS3axJKqPwMrFibr7SWVAQ4rC8QZzDMvcRNWnFuQJAvfd4fL3iyCyR'

    IP_token = 'http://193.61.36.93:8000/o/token/'
    IP_revoke_token = 'http://193.61.36.93:8000/o/revoke_token/'
    '''
    Registers user to the server. Input should be in the format:
    {"username": "******", "password": "******"}
    '''
    # Put the data from the request into the serializer
    serializer = CreateUserSerializer(data=request.data)
    # Validate the data
    if serializer.is_valid():
        # If it is valid, save the data (creates a user).
        serializer.save()
        # Then we get a token for the created user.
        # This could be done differentley
        r = requests.post(
            IP_token,
            data={
                'grant_type': 'password',
                'username': request.data['username'],
                'password': request.data['password'],
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET,
            },
        )
        #return Response(r.json())
        return index(request)
    return Response(serializer.errors)
Пример #3
0
 def post(self, request, *args, **kwargs):
     serializer = CreateUserSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         if user is not None:
             refresh = RefreshToken.for_user(user=user)
             response = serializer.data
             response['access'] = str(refresh.access_token)
             response['refresh'] = str(refresh)
         return Response(response, status.HTTP_201_CREATED)
     return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
Пример #4
0
    def create(self, request, *args, **kwargs):
        """Создание пользователя.

        Только для администраторов.
        """
        serializer = CreateUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        serializer = self.get_serializer(user)
        return Response(serializer.data, status=http.HTTPStatus.CREATED)
Пример #5
0
 def post(self, request, *args, **kwargs):
     serialized = CreateUserSerializer(data=request.data)
     if serialized.is_valid():
         serializer_data = serialized.validated_data
         User.objects.create_user(**serializer_data)
         serializer_data = serialized.data
         serializer_data.pop('password')
         return Response(serializer_data, status=status.HTTP_201_CREATED)
     else:
         return Response(serialized.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Пример #6
0
class ArticleSerializerForDetail(serializers.ModelSerializer):
    user = CreateUserSerializer(read_only=True)
    comments = CommentSerializerList(read_only=True, many=True)

    class Meta:
        model = Article
        fields = "__all__"
Пример #7
0
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': CreateUserSerializer(user, context={
            'request': request
        }).data
    }
Пример #8
0
class ArticleSerializerForList(serializers.ModelSerializer):
    user = CreateUserSerializer(read_only=True)
    collected = serializers.BooleanField(default=False)

    class Meta:
        model = Article
        fields = ("id", "title", "content", "createtime", "user",
                  "collected_users", "collected", "image", "visits")
Пример #9
0
def create_user(request):
    # ipdb.set_trace()
    user = CreateUserSerializer(data=request.data)
    if user.is_valid():
        profile_group = Group.objects.get(
            name=user.validated_data['profile']['group'])
        user_saved = user.save()
        profile_group.user_set.add(user_saved)
        user_auth = authenticate(username=user.validated_data['email'],
                                 password=user.validated_data['password'])
        token, _ = Token.objects.get_or_create(user=user_auth)
        return Response({
            'user': user.data,
            'token': token.key
        },
                        status=status.HTTP_201_CREATED)
    else:
        return Response(user._errors, status=status.HTTP_400_BAD_REQUEST)
Пример #10
0
    def create(self, request, *args, **kwargs):
        create_user_serializer = CreateUserSerializer(data=request.data)

        if not create_user_serializer.is_valid():
            return Response(
                {"detail": create_user_serializer.errors}, status.HTTP_400_BAD_REQUEST
            )

        cleaned_data = create_user_serializer.data
        user_exists = User.objects.filter(email=cleaned_data["email"]).first()
        if user_exists:
            return Response(
                {"detail": "A user with this email already exists"},
                status.HTTP_409_CONFLICT,
            )
        user = self.create_user(cleaned_data)
        self.set_default_user_role(user)

        return Response(self.serializer_class(user).data, status.HTTP_201_CREATED)
Пример #11
0
def create_user(request):
    serializer = CreateUserSerializer(data=request.data)
    if not serializer.is_valid():
        return ErrorResponse(serializer.errors_to_text,
                             status.HTTP_400_BAD_REQUEST)
    email = serializer.validated_data['email']
    password = serializer.validated_data['password']
    name = serializer.validated_data['name']
    token = to_base64(email, password)
    cash_account = AccountEmailCash.objects.filter(email=email).first()
    account = cash_account.account if cash_account is not None else None
    if User.objects.filter(email=email).first():
        return ErrorResponse(ALREADY_EXIST_USER, status.HTTP_400_BAD_REQUEST)
    else:
        user = User.objects.create(email=email,
                                   name=name,
                                   password=make_password(password),
                                   token=token,
                                   account=account)
        return SuccessResponse(
            UserSerializer(user).data, status.HTTP_201_CREATED)
Пример #12
0
    def post(self, request):
        user = request.data
        serializer = CreateUserSerializer(data=user)
        serializer.is_valid(raise_exception=True)

        # Verifying email by EmailHunter
        email_hunter = EmailHunter(serializer.data.get('email'))
        if email_hunter.is_available():
            if email_hunter.email_verifier() is False:
                return Response({"error": 'User email is invalid'},
                                status=status.HTTP_422_UNPROCESSABLE_ENTITY)

        # Getting additional information with ClearBit
        clearbit_data = self.get_clearbit_data(serializer)

        # Creating user
        serializer.create(
            clearbit_data) if clearbit_data else serializer.create(
                serializer.data)

        return Response('User Created!', status=status.HTTP_201_CREATED)
    def test_serializer_hashes_password(self):
        serializer = CreateUserSerializer(data=self.user_data)
        assert serializer.is_valid()

        user = serializer.save()
        assert check_password(self.user_data.get('password'), user.password)
 def test_serializer_with_valid_data(self):
     serializer = CreateUserSerializer(data=self.user_data)
     assert serializer.is_valid()
 def test_serializer_with_empty_data(self):
     serializer = CreateUserSerializer(data={})
     assert serializer.is_valid() is False