def test_user_create__firebase_user_exists(self, mock_create,
                                            mock_model_create):
     serializer = UserCreateSerializer(data=self.data)
     self.assertTrue(serializer.is_valid())
     self.assertRaises(ValidationError, serializer.save)
     mock_create.assert_called_once_with(email="*****@*****.**")
     mock_model_create.assert_not_called()
Beispiel #2
0
def create_user_view(request):
    serializer = UserCreateSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response({'message': 'ok'})
    else:
        return Response({'messgae': 'error'})
Beispiel #3
0
 def post(self, request):
     serializer = UserCreateSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
 def test_user_create__local_user_exists(self, mock_create, mock_delete,
                                         mock_model_create):
     serializer = UserCreateSerializer(data=self.data)
     self.assertTrue(serializer.is_valid())
     self.assertRaises(Exception, serializer.save)
     mock_create.assert_called_once()
     mock_delete.assert_called_once()
     mock_model_create.assert_called_once()
Beispiel #5
0
 def test_cannot_create_already_existing_user(self):
     # Test that an error is thrown if the mails are different
     existing_user = {
         'username': '******',
         'email': '*****@*****.**',
         'email2': '*****@*****.**',
         'password': '******',
     }
     user = UserCreateSerializer(data=existing_user)
     self.assertEqual(user.is_valid(), False)
Beispiel #6
0
 def test_validate_email2_with_right_data(self):
     # Test that an error is thrown if the mails are different
     good_user = {
         'username': '******',
         'email': '*****@*****.**',
         'email2': '*****@*****.**',
         'password': '******',
     }
     user = UserCreateSerializer(data=good_user)
     self.assertEqual(user.is_valid(), True)
 def test_user_create(self, mock_create, mock_model_create):
     uid = "test_uid"
     serializer = UserCreateSerializer(data=self.data)
     # anonymous object creation
     firebase_user = type("", (object, ), {"uid": uid})()
     model_user = type("", (object, ), {"firebase_uid": uid})()
     mock_create.return_value = firebase_user
     mock_model_create.return_value = model_user
     self.assertTrue(serializer.is_valid())
     user = serializer.save()
     self.assertEqual(user.firebase_uid, uid)
     mock_create.assert_called_once_with(email="*****@*****.**")
     mock_model_create.assert_called_once()
Beispiel #8
0
def registration(request):
    serializer = UserCreateSerializer(data=request.data)
    if not serializer.is_valid():
        return response.Response(serializer.errors,
                                 status.HTTP_400_BAD_REQUEST)
    user = serializer.save()
    refresh = RefreshToken.for_user(user)
    res = {
        "refresh": str(refresh),
        "access": str(refresh.access_token),
        "username": user.username
    }
    return response.Response(res, status.HTTP_201_CREATED)
Beispiel #9
0
    def post(self, request, *args, **kwargs):
        fields = {
            'email': request.data.get('email'),
            'password': request.data.get('password'),
            'last_name': request.data.get('last_name'),
            'first_name': request.data.get('first_name'),
        }

        serializer = UserCreateSerializer(data=fields)

        serializer.is_valid(raise_exception=True)

        user = serializer.create(serializer.validated_data)
        return Response(UserSerializer(user).data,
                        status=status.HTTP_201_CREATED)
Beispiel #10
0
def get_user_view(request: Request) -> Response:
    """[summary]

    Arguments:
        request {Request} -- [description]
    
    Schma:
        GET:
        
        POST:

    Raises:
        PermissionError: [description]
        ConnectionRefusedError: [description]
    
    Returns:
        Response -- [description]
    """
    serializer: Serializer
    if request.method == "GET":
        queryset = get_user_model().objects.all()
        serializer = UserDetailSerializer(queryset, many=True)
        raise PermissionError("error", "try Get or post")
        return Response(serializer.data)
    if request.method == "POST":
        serializer = UserCreateSerializer(data=request.data,
                                          status=status.HTTP_200_OK)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    raise ConnectionRefusedError()
class BasKetRetrieveSerializer(serializers.ModelSerializer):
    product = ProductRetrieveSerializer()
    customer = UserCreateSerializer()

    class Meta:
        model = BasKet
        fields = ['id', 'product', 'customer', 'count', 'created_at']
Beispiel #12
0
def users_requesting_access(request, pk):
    # Operates on users who request joining to a page.

    # User should be logged in.
    if request.user.is_anonymous:
        return JsonResponse({'message': "No access"},
                            status=status.HTTP_403_FORBIDDEN)

    # Get user specified by a primary key.
    try:
        page = ThematicPage.objects.get(pk=pk)
    except ThematicPage.DoesNotExist:
        return JsonResponse({'message': 'The Thematic Page does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    # GET request.
    if request.method == 'GET':
        # Check whether user is moderator of a specified page.
        if page in request.user.can_moderate.all():
            # Serialize an user.
            user_serializer = UserCreateSerializer(page.requested_by,
                                                   many=True)
            # Return serialized user.
            return JsonResponse(user_serializer.data, safe=False)
        else:
            # Notify that action is forbidden.
            return JsonResponse({'message': "User can't moderate this page"},
                                status=status.HTTP_403_FORBIDDEN)
Beispiel #13
0
def new_user(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=True)
            serialized_user = UserCreateSerializer(user).user_detail            
            return JsonResponse(data={'Success': 'You have created a new user!', 'user': serialized_user}, status=200)
Beispiel #14
0
def user_with_no_access_list(request, pk):
    # Operates on users who doesn't have an access to a thematic page.

    # User should be logged in.
    if request.user.is_anonymous:
        return JsonResponse({'message': "No access"},
                            status=status.HTTP_403_FORBIDDEN)

    # Get page specified by a primary key.
    try:
        page = ThematicPage.objects.get(pk=pk)
    except ThematicPage.DoesNotExist:
        return JsonResponse({'message': 'The Thematic Page does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    # GET request.
    if request.method == 'GET':
        if page in request.user.can_moderate.all():
            # Get all users.
            users = User.objects.all()
            # Exclude users that have access.
            for pk_ in page.users.values('pk'):
                pk_ = pk_['pk']
                users = users.exclude(pk=pk_)
            # Serialize an user.
            user_serializer = UserCreateSerializer(users, many=True)
            # Return serialized user.
            return JsonResponse(user_serializer.data, safe=False)
        else:
            # Notify that action is forbidden.
            return JsonResponse({'message': "User can't moderate this page"},
                                status=status.HTTP_403_FORBIDDEN)
Beispiel #15
0
def edit_user(request, user_id):
    user = User.objects.get(id=user_id)
    if request.method == 'POST':
        form = UserForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save(commit=True)
            serialized_user = UserCreateSerializer(user).user_detail            
            return JsonResponse(data={'Success': 'You have edited a user!', 'user': serialized_user}, status=200)
Beispiel #16
0
 def serializer_create_returns_the_validated_data(self):
     good_user = {
         'username': '******',
         'email': '*****@*****.**',
         'email2': '*****@*****.**',
         'password': '******',
     }
     user = UserCreateSerializer.create(validated_data=good_user)
     self.assertEqual(user, good_user)
class ProductRetrieveSerializer(serializers.ModelSerializer):
    owner = UserCreateSerializer()
    category = CategorySerializer()

    class Meta:
        model = Product
        fields = [
            'id', 'title', 'category', 'owner', 'description', 'price',
            'discount_price', 'amount_by_unit', 'unit', 'main_image',
            'created_at'
        ]
Beispiel #18
0
 def serializer_can_create_a_new_user(self):
     good_user = {
         'username': '******',
         'email': '*****@*****.**',
         'email2': '*****@*****.**',
         'password': '******',
     }
     user = UserCreateSerializer(data=good_user)
     user_qs = User.objects.filter(username='******')
     # The user was created
     self.assertEqual(len(user_qs), 1)
     # The right user was created
     self.assertEqual(user_qs[0].username, 'testuser')
class CommentSerializer(serializers.ModelSerializer):
    """
    Class that manages serialization and deserialization of Comment model from JSON.
    It inherits from rest_framework.serializers.ModelSerializer superclass
    which automatically populates a set of fields and default validators.
    """

    user = UserCreateSerializer(required=False)

    class Meta:
        # The model class for Serializer.
        model = Comment
        # A tuple of field names to be included in the serialization.
        fields = ['id', 'upload', 'user', 'content', 'date']
        extra_kwargs = {'user': {'required': False}}
Beispiel #20
0
def add_user(request, page_pk, user_pk):
    # Accept request for joining of a user.

    # User should be logged in.
    if request.user.is_anonymous:
        return JsonResponse({'message': "No access"},
                            status=status.HTTP_403_FORBIDDEN)

    # Get page specified by a primary key.
    try:
        page = ThematicPage.objects.get(pk=page_pk)
    except ThematicPage.DoesNotExist:
        return JsonResponse({'message': 'The Thematic Page does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    # Get user specified by a primary key.
    try:
        user = User.objects.get(pk=user_pk)
    except User.DoesNotExist:
        return JsonResponse({'message': 'The user does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    # POST request.
    if request.method == 'POST':
        # Check whether user is moderator of a specified page.
        if page in request.user.can_moderate.all():
            # Remove request.
            user.requested_pages.remove(page)
            # Add new follower.
            page.users.add(user)
            # Serialize an user.
            user_serializer = UserCreateSerializer(user)
            # Return serialized user.
            return JsonResponse(user_serializer.data)
        else:
            return JsonResponse({'message': "User can't moderate this page"},
                                status=status.HTTP_403_FORBIDDEN)
 def post(self, request):
     serializer = UserCreateSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.save()  # UserCreateSerializer.create 호출
     return Response(data=user.pk, status=HTTP_201_CREATED)
Beispiel #22
0
def user_detail(request, user_id):
    user = User.objects.get(id=user_id)
    serialized_user = UserCreateSerializer(user).user_detail
    return JsonResponse(data=serialized_user, status=200)
Beispiel #23
0
def friendship_home(request):
    users = User.objects.all()
    serialized_users = UserCreateSerializer(users).all_users
    return JsonResponse(data=serialized_users, status=200)
class UploadSerializer(serializers.ModelSerializer):
    """
    Class that manages serialization and deserialization of Upload model from JSON.
    It inherits from rest_framework.serializers.ModelSerializer superclass
    which automatically populates a set of fields and default validators.
    """

    user = UserCreateSerializer(required=False)

    # File serialization.
    file = serializers.FileField(max_length=None, use_url=True, required=False)
    # Multiple Tag serialization.
    tags = TagSerializer(many=True, required=False)

    class Meta:
        # The model class for Serializer.
        model = Upload
        # A tuple of field names to be included in the serialization.
        fields = (
            'id',
            'title',
            'user',
            'type',
            'date',
            'status',
            'innopoints',
            'tags',
            'link',
            'file',
            'thematic_page',
            'rating',
            'size',
            'name',
        )
        extra_kwargs = {'user': {'required': False}}

    def create(self, validated_data):
        # Describes the process of fields deserialization for object creation.

        # Retrieve tags parameters.
        try:
            tags_data = validated_data.pop('tags')
        except Exception:
            tags_data = []

        if validated_data['type'] != 3:
            validated_data['name'] = validated_data['file'].name
            validated_data['size'] = getsize(validated_data['file'].size)

        # Create a new instance of an upload.
        upload = Upload.objects.create(**validated_data)
        # Put tags in new upload.
        for tag_data in tags_data:
            upload.tags.add(tag_data)
        return upload

    def update(self, instance, validated_data):
        # Describes the process of fields deserialization for object update.

        # Retrieve tags parameters.
        try:
            tags_data = validated_data.pop('tags')
        except Exception:
            tags_data = []

        # Update title, type, innopoints, status field.
        instance.title = validated_data.get('title', instance.title)
        instance.type = validated_data.get('type', instance.type)
        instance.innopoints = validated_data.get('innopoints',
                                                 instance.innopoints)
        instance.status = validated_data.get('status', instance.status)
        instance.thematic_page = validated_data.get('thematic_page',
                                                    instance.thematic_page)
        # Clear tags field.
        instance.tags.clear()
        # Set new tags.
        for tag_data in tags_data:
            instance.tags.add(tag_data)
        instance.name = validated_data.get('name', instance.name)
        instance.size = validated_data.get('size', instance.name)
        # Save upload.
        instance.save()
        return instance