def post(self, request, format='json'):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         if user:
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED)
def test_update_user(orig_share_amt, share_add_amt, share_del_amt,
                     update_name):
    if share_del_amt > orig_share_amt:
        return
    serializer = UserSerializer()
    user = random_users(1)[0]
    orig_shares = random_shares(orig_share_amt)
    orig_time = user.updated_at
    for share in orig_shares:
        share.users.add(user)

    validated_data = {'name': user.name + random_str(2)} if update_name else {}

    if share_add_amt + share_del_amt > 0:
        added = random_shares(share_add_amt)
        new_shares = orig_shares[:-share_del_amt] + added
        deleted = orig_shares[-share_del_amt:]
        validated_data['shares'] = new_shares
    else:
        deleted = []
        new_shares = list(orig_shares)

    serializer.update(user, validated_data)
    assert_update_time(orig_time, user)

    assert user.name == validated_data.get('name', user.name)
    user_shares = user.shares
    assert user_shares.count() == len(new_shares)
    assert set(user_shares) == set(new_shares)
    for deleted_share in deleted:
        assert deleted_share not in user_shares
Exemplo n.º 3
0
 def post(self, request):
     data = JSONParser().parse(request)
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return JSONResponse(serializer.data, status=201)
     return JSONResponse(serializer.errors, status=400)
Exemplo n.º 4
0
    def create(self, request):
        if all(value != None for value in request.data.values()):
            email = request.data.get("email")
            username = request.data.get("username")
            password = request.data.get("password") or request.data.get(
                "password1")
            logger.info(f"TRYING SERIALIZE NEW USER: {request.data}")

            serializer = UserSerializer(data={
                "username": username,
                "email": email,
                "password": password
            })
            if serializer.is_valid():
                serializer.save()
                logger.info(f"NEW USER CREATED: {serializer.data} ")
                new_user = User.objects.get(email=email, username=username)
                if UserProfile.objects.create(user=new_user,
                                              id=new_user.id,
                                              user_courses=[]):
                    logger.info(f"USER PROFILE WAS CREATED - {new_user.id}")
                    return Response(serializer.data,
                                    status=status.HTTP_201_CREATED)
            else:
                logger.error(
                    f"NEW USER WAS NOT CREATED {serializer.data} BECAUSE OF {serializer.errors}"
                )
                return Response(serializer.errors,
                                status=status.HTTP_412_PRECONDITION_FAILED)
        else:
            logger.error(
                f"NEW USER WAS NOT CREATED - SOME EMPTY INPUT FIELDS: {request.data}"
            )
            return Response(status=status.HTTP_412_PRECONDITION_FAILED)
Exemplo n.º 5
0
 def post(self, request):
     uid = request.data['id']
     status = request.data['status']
     data = {
         'id': uid,
         'status':status
     }
     try:
         user = User.objects.get(id=uid)
     except:
         response = {
             'code': 0,
             'message': '用户id不存在',
         }
         return Response(response)
     else:
         serializer = UserSerializer(data=data, instance=user)
         if serializer.is_valid():
             serializer.save()
             response = {
                 'code': 1,
                 'data': serializer.data,
             }
             return Response(response)
         else:
             return Response(serializer.errors)
Exemplo n.º 6
0
 def put(self, request, id, format=None):
     user = self.get_object(id)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 7
0
 def put(self, request, *args, **kwargs):
     user = request.data["pk"]
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return self.update(request, *args, **kwargs)
Exemplo n.º 8
0
 def put(self, request, uid, format=None):
     user = self._get_object(uid)
     serializer = UserSerializer(user, data=request.DATA)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
 def create(self, request, *args, **kwargs):
     """
     Override create method to hash the user's password
     :param request: POST request with user data
     :param args: none
     :param kwargs: none
     :return: If there is duplicate user, it returns 400. Otherwise, returns 201.
     """
     password = request.data['password']
     hashed_password = pl_hash.django_pbkdf2_sha256.hash(password)
     data = {
         'email': request.data['email'],
         'first_name': request.data['first_name'],
         'last_name': request.data['last_name'],
         'password_hash': hashed_password,
         'color_pref': request.data['color_pref'],
         'school': request.data['school'],
     }
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 10
0
def create_user(request):
    if not request.body:
        return HttpResponse(status=404)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        try:
            user = User()
            validate_email(data['email'])
        except ValidationError:
            return HttpResponse(status=400)
        users = User.objects.all()
        if not users:
            serializer = UserSerializer(user, data=data)
            if serializer.is_valid():
                serializer.save()
                return HttpResponse(status=202)  #First User
            return HttpResponse(status=400)
        else:
            for u in users:
                if data['email'] == u.get_email():
                    return HttpResponse(status=400)
            serializer = UserSerializer(user, data=data)
            if serializer.is_valid():
                serializer.save()
                return HttpResponse(status=202)
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=404)
Exemplo n.º 11
0
 def post(self, request, *args, **kwargs):
     # проверяем обязательные аргументы
     if {'first_name', 'last_name', 'email', 'password', 'company', 'position'}.issubset(request.data):
         # проверяем пароль на сложность
         try:
             validate_password(request.data['password'])
         except Exception as password_error:
             return Response({'status': False, 'error': {'password': password_error}},
                             status=status.HTTP_403_FORBIDDEN)
         else:
             # проверяем данные для уникальности имени пользователя
             request.data._mutable = True
             request.data.update({})
             user_serializer = UserSerializer(data=request.data)
             if user_serializer.is_valid():
                 user = user_serializer.save()
                 user.set_password(request.data['password'])
                 user.save()
                 token, _ = ConfirmEmailToken.objects.get_or_create(user_id=user.id)
                 # посылаем письмо с токеном для верификации (с помощью Celery)
                 send_verification_email.delay(user.id)
                 return Response({'status': True})
             else:
                 return Response({'status': False, 'error': user_serializer.errors},
                                 status=status.HTTP_403_FORBIDDEN)
     return Response({'status': False, 'error': 'Не указаны все необходимые аргументы'},
                     status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 12
0
	def post(self, request, format=None):
		data = request.data
		try:
			email = data['email']
			username = email[:email.find("@")]
			user = User.objects.create_user(username=username,email=email,password=data['password'])
			app_user = AppUser.objects.get(user=user)
			try:
				app_user.region = Region.objects.get(name='russia')
				app_user.save()
			except KeyError:
				print('No email', user)
			serializer = UserSerializer(app_user)
			return Response(serializer.data)
		except KeyError:
			try:
				telegram = data['telegram']
				password = User.objects.make_random_password()
				user = User.objects.create_user(username=telegram,password=password)
				app_user = AppUser.objects.get(user=user)
				AppUser.objects.filter(user=user).update(telegram=telegram)
				serializer = UserSerializer(app_user)
				return Response(serializer.data)
			except IntegrityError as e:
				if 'unique constraint' in e.args[0]:
					data = {'details': 'User already exists'}
					return Response(data)
		except IntegrityError as e:
			if 'unique constraint' in e.args[0]:
				data = {'details': 'User already exists'}
				return Response(data)
Exemplo n.º 13
0
    def post(self, request, format='json'):
        serializer = UserSerializer(data=request.data)
        """
        Verify that the token recieved at the client is valid
        """
        verify = requests.post(
            'https://www.google.com/recaptcha/api/siteverify',
            data={
                'secret': '6Ldv8ngUAAAAAF9fnkjTTf4OL6z3TLMDXjwDQL8w',
                'response': request.data['captcharesponse']
            },
            verify=True)

        print('reCaptcha verification')
        print(verify.json()['success'])

        if verify.json()['success'] == 'False':
            return Response(status=status.HTTP_400_BAD_REQUEST)

        if serializer.is_valid():
            user = serializer.save()
            if user:
                return Response(serializer.data,
                                status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 14
0
    def test_user_updates_email(self):
        """
        User updating email should not affect other fields.
        """

        email = self.user.email
        username = self.user.username
        password = self.user.password
        userid = self.user.id
        pk = self.user.pk
        profile = self.user.profile

        update = {
            'email': '*****@*****.**'
        }

        serializer = UserSerializer(self.user, data=update, partial=True,
                                    context={'request': None})
        # pdb.set_trace()
        self.assertTrue(serializer.is_valid())
        updated_user = serializer.save()

        self.assertTrue(updated_user)
        self.assertEqual(updated_user.email, update['email'])
        self.assertEqual(updated_user.username, username)
        self.assertEqual(userid, updated_user.id)
        self.assertEqual(pk, updated_user.pk)
        self.assertEqual(password, updated_user.password)
        self.assertEqual(profile, updated_user.profile)
        self.assertNotEqual(email, updated_user.email)
Exemplo n.º 15
0
def activate(request, pk):
    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        raise Http404

    serializer = UserSerializer(user, data=request.data, partial=True)
    if serializer.is_valid():
        if not request.data.get('activation_code') or not request.data.get(
                'password'):
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        if user.activation_code != request.data.get('activation_code'):
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        if len(user.password) != 0:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        serializer.save()
        user.set_password(request.data['password'])
        user.save()
        return Response(serializer.data)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 16
0
    def test_user_updates_email_and_password(self):
        """
        User updating any two fields should not affect the third field.
        """

        email = self.user.email
        username = self.user.username
        password = self.user.password
        userid = self.user.id
        pk = self.user.pk
        profile = self.user.profile

        update = {
            'password': '******',
            'email': '*****@*****.**'
        }

        serializer = UserSerializer(self.user, data=update, partial=True)
        self.assertTrue(serializer.is_valid())
        updated_user = serializer.save()

        self.assertTrue(updated_user)
        self.assertEqual(username, updated_user.username)
        self.assertEqual(userid, updated_user.id)
        self.assertEqual(pk, updated_user.pk)
        self.assertEqual(profile, updated_user.profile)

        self.assertNotEqual(updated_user.password, password)
        self.assertNotEqual(updated_user.email, email)
Exemplo n.º 17
0
 def put(self, request, pk, format=None):
     user = self.get_object(pk)
     serializer = UserSerializer(user, data=request.data, partial=True)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 18
0
 def put(self, request):
     uid = request.data['id']
     password = make_password(request.data['password'])
     new_password = make_password(request.data['new_password'])
     data = {
         'id': uid,
         'password': new_password
     }
     try:
         user = User.objects.get(id=uid, password=password)
     except:
         response = {
             'code': 0,
             'message': '原密码错误',
         }
         return Response(response)
     else:
         serializer = UserSerializer(data=data, instance=user)
         if serializer.is_valid():
             serializer.save()
             response = {
                 'code': 1,
                 'data': serializer.data,
             }
             return Response(response)
         else:
             return Response(serializer.errors)
Exemplo n.º 19
0
 def put(self, request, id):
     user = self.get_object(id)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 20
0
    def post(self, request):
        username = request.data['username']
        center_id = request.data['center_id']

        if User.objects.filter(username=username).count() == 0:
            password = make_password('123')
            data = {
                'username': username,
                'password': password,
                'center_id': center_id,
                'status': 1
            }
            serializer = UserSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                response = {
                    'code': 1,
                    'data': serializer.data,
                }
                return Response(response)
            else:
                return Response(serializer.errors)
        else:
            response = {
                'code': 0,
                'message': '用户名已存在'
            }
            return Response(response)
Exemplo n.º 21
0
def user_detail(request, pk):
    """
    get, update, or delete a specific user
    :param request: get,put,delete
    :param pk: user_id (primary key)
    :return: response
    """

    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = UserSerializer(user, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 22
0
    def _create_user(username, tenant, request):
        """Create a user for a tenant.

        Args:
            username (str): The username
            tenant (Tenant): The tenant the user is associated with
            request (object): The incoming request

        Returns:
            (User) The created user

        """
        new_user = None
        try:
            with transaction.atomic():
                user_data = {'username': username}
                context = {'request': request}
                serializer = UserSerializer(data=user_data, context=context)
                if serializer.is_valid(raise_exception=True):
                    new_user = serializer.save()

                logger.info('Created new user %s for tenant( %s).', username,
                            tenant.schema_name)
        except (IntegrityError, ValidationError):
            new_user = User.objects.get(username=username)
        return new_user
Exemplo n.º 23
0
    def post(self, request):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 24
0
 def post(self, request):
     data = json.loads(request.query_params.get('data', {}))
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save(password=data.get("user_password"))
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 25
0
    def post(self, request):
        data = json.loads(request.body)
        serializer = UserSerializer(data=data)
        if not serializer.is_valid():
            return JsonResponse({'errors': serializer.errors},
                                status=status_codes.HTTP_400_BAD_REQUEST)

        clean_data = serializer.validated_data

        try:
            User.objects.get(username=clean_data['username'])
            return JsonResponse({'errors': 'Username already taken!'},
                                status=status_codes.HTTP_403_FORBIDDEN)
        except User.DoesNotExist:
            pass

        model = User(username=clean_data['username'],
                     password=clean_data['password'],
                     name=clean_data['name'],
                     phone_number=clean_data['phone_number'],
                     latitude=clean_data['latitude'],
                     longitude=clean_data['longitude'],
                     bio=clean_data['bio'],
                     isBusiness=False)

        model.save()

        # Set auth cookie to request & get / generate auth token
        login(request, model)
        token, _ = Token.objects.get_or_create(user=model)
        return JsonResponse({
            'user': model.to_dict(),
            'token': token.key
        },
                            status=status_codes.HTTP_200_OK)
Exemplo n.º 26
0
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 27
0
class UserSerializerTest(SerializerTest):
    def setUp(self):
        self.serializer = UserSerializer()

    def test_user_creation(self):
        user = self.serializer.create(self.USER_DATA)
        auth_role = AuthRole.get_auth_role(user.pk)

        self.assertIsInstance(user, User)
        self.assertEqual(auth_role,
                         AuthRole.RoleTypes.USER,
                         msg='Auth role is user')
        self.assertEqual(user.first_name, self.USER_DATA.get('first_name'))
        self.assertEqual(user.last_name, self.USER_DATA.get('last_name'))
        self.assertEqual(user.email, self.USER_DATA.get('email'))
        self.assertEqual(user.username, self.USER_DATA.get('username'))
        self.assertEqual(user.check_password(self.USER_DATA.get('password')),
                         True)

    def test_user_update(self):
        manager = self.create_manager()
        manager = self.serializer.update(manager, self.TEST_DATA)  # type: User
        manager_role = AuthRole.get_auth_role(manager.pk)

        self.assertIsInstance(manager, User)
        self.assertEqual(manager_role,
                         AuthRole.RoleTypes.MANAGER,
                         msg='Auth role is manager')
        self.assertEqual(manager.first_name, self.TEST_DATA.get('first_name'))
        self.assertEqual(manager.last_name, self.TEST_DATA.get('last_name'))
        self.assertEqual(manager.email, self.TEST_DATA.get('email'))
        self.assertEqual(manager.username, self.TEST_DATA.get('username'))
        self.assertEqual(
            manager.check_password(self.TEST_DATA.get('password')), True)
Exemplo n.º 28
0
 def post(self, request, format=None):
     data = JSONParser().parse(request)
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 29
0
    def post(self, request, *args, **kwargs):

        # проверяем обязательные аргументы
        if {'first_name', 'last_name', 'email', 'password', 'company', 'position'}.issubset(request.data):
            errors = {}

            # проверяем пароль на сложность

            try:
                validate_password(request.data['password'])
            except Exception as password_error:
                error_array = []
                # noinspection PyTypeChecker
                for item in password_error:
                    error_array.append(item)
                return JsonResponse({'Status': False, 'Errors': {'password': error_array}})
            else:
                # проверяем данные для уникальности имени пользователя
                # request.data._mutable = True
                request.data.update({})
                user_serializer = UserSerializer(data=request.data)
                if user_serializer.is_valid():
                    # сохраняем пользователя
                    user = user_serializer.save()
                    user.set_password(request.data['password'])
                    user.save()
                    new_user_registered.send(sender=self.__class__, user_id=user.id)
                    return JsonResponse({'Status': True})
                else:
                    return JsonResponse({'Status': False, 'Errors': user_serializer.errors})

        return JsonResponse({'Status': False, 'Errors': 'Не указаны все необходимые аргументы'})
Exemplo n.º 30
0
    def test_user_updates_username(self):
        """
        User updating username should not affect other fields.
        """

        user = User.objects.get(username=self.user.username)
        email = user.email
        userid = user.id
        pk = user.pk
        profile = user.profile
        username = user.username

        update = {
            'username': '******',
        }

        serializer = UserSerializer(user, data=update, partial=True,
                                    context={'request': None})
        self.assertTrue(serializer.is_valid())
        updated_user = serializer.save()

        self.assertTrue(updated_user)
        self.assertEqual(updated_user.username, 'NewUserName')
        self.assertEqual(userid, updated_user.id)
        self.assertEqual(pk, updated_user.pk)
        self.assertEqual(email, updated_user.email)
        self.assertEqual(profile, updated_user.profile)

        self.assertNotEqual(username, updated_user.username)
Exemplo n.º 31
0
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return JsonResponse({'Status': False, 'Error': 'Log in required'}, status=403)
        # проверяем обязательные аргументы

        if 'password' in request.data:
            errors = {}
            # проверяем пароль на сложность
            try:
                validate_password(request.data['password'])
            except Exception as password_error:
                error_array = []
                # noinspection PyTypeChecker
                for item in password_error:
                    error_array.append(item)
                return JsonResponse({'Status': False, 'Errors': {'password': error_array}})
            else:
                request.user.set_password(request.data['password'])

        # проверяем остальные данные
        user_serializer = UserSerializer(request.user, data=request.data, partial=True)
        if user_serializer.is_valid():
            user_serializer.save()
            return JsonResponse({'Status': True})
        else:
            return JsonResponse({'Status': False, 'Errors': user_serializer.errors})
Exemplo n.º 32
0
    def test_user_updates_password(self):
        """
        User updating password should have password hashed before storage,
        and update should not affect other fields.
        """

        email = self.user.email
        username = self.user.username
        password = self.user.password
        userid = self.user.id
        pk = self.user.pk
        profile = self.user.profile

        update = {
            'password': '******'
        }

        serializer = UserSerializer(self.user, data=update, partial=True)
        self.assertTrue(serializer.is_valid())
        updated_user = serializer.save()

        self.assertTrue(updated_user)
        self.assertEqual(updated_user.email, email)
        self.assertEqual(updated_user.username, username)
        self.assertEqual(userid, updated_user.id)
        self.assertEqual(pk, updated_user.pk)
        self.assertEqual(profile, updated_user.profile)

        self.assertNotEqual(updated_user.password, update['password'])
        self.assertNotEqual(password, updated_user.password)
Exemplo n.º 33
0
def add_user(request):
	serializer = UserSerializer(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)
Exemplo n.º 34
0
def sign_up_user(request):
    if request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'Message': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 35
0
 def post(self, request, *args, **kwargs):
     serialized = UserSerializer(data=request.DATA)
     if serialized.is_valid():
         user = User.objects.create_user(
             serialized.init_data['username'],
             serialized.init_data['email'],
             serialized.init_data['password'],
             mobile=serialized.init_data['mobile']
         )
         token = Token.objects.get_or_create(user=user)[0]
         return Response({'token': token.key}, status=status.HTTP_201_CREATED)
     else:
         return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 36
0
def user_list(request):

    if request.method == 'GET':
        user = User.objects.all()
        serializer = UserSerializer(user, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Exemplo n.º 37
0
def register(req):
    phone = req.session.get("phone", "")
    password = req.session.get('password', "")
    if not phone:
        return SimpleResponse(False, "请先验证手机")
    else:
        del req.session['phone']
    req.data["phone_number"] = phone
    req.data['password'] = password
    ser = UserSerializer(data=req.data)
    if ser.is_valid():
        ser.save()
        return SimpleResponse(True)
    else:
        return SimpleResponse(False, ser.error_messages)
Exemplo n.º 38
0
Arquivo: views.py Projeto: leohahn/TIM
def user_list(request, format=None):
    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            if (0 == User.objects.filter(phoneNr= serializer.validated_data['phoneNr']).count()):
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        print (serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 39
0
    def post(self, request):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            credentials = {
                'email': serializer.validated_data['email'],
                'password': serializer.validated_data['password']
            }

            token = get_user_token(credentials)
            data = {'token': token}

            return Response(data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 40
0
def user_list(request):
    """
    List all users, or create a new one
    :param request:
    :return:
    """

    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = UserSerializer(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)
Exemplo n.º 41
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         User.objects.create_user(
             username=request.data['username'],
             password=request.data['password'],
             email=request.data['email']
         )
         auth_user = authenticate(
             username=request.data['username'],
             password=request.data['password']
         )
         login(request, auth_user)
         return Response(serializer.data)
     else:
         return Response(
             serializer.errors,
             status=status.HTTP_400_BAD_REQUEST
         )
Exemplo n.º 42
0
def user(request, email):
	try:
		user = User.objects.get(email=email)
	except User.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method == 'GET':
		serializer = UserSerializer(user)
		return Response(serializer.data)

	elif request.method == 'PUT':
		serializer = UserSerializer(user, data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

	elif request.method == 'DELETE':
		user.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 43
0
 def post(self, request):
     username = request.data['username']
     password = request.data['password']
     user = get_object_or_404(User, username=username)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         auth_user = authenticate(username=username, password=password)
         if auth_user is not None:
             if auth_user.is_active:
                 login(request, auth_user)
                 return Response(serializer.data)
         else:
             return Response(
                 serializer.errors,
                 status=status.HTTP_400_BAD_REQUEST
             )
     else:
         return Response(
             serializer.errors,
             status=status.HTTP_400_BAD_REQUEST
         )
Exemplo n.º 44
0
Arquivo: views.py Projeto: leohahn/TIM
def user_detail(request, name, format=None):
    try:
        user = User.objects.get(username=name)
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            print(serializer.data)
            return Response(serializer.data)
        print(serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 45
0
def user_detail(request, pk):

    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)
Exemplo n.º 46
0
def user_detail(request, id):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        user = User.objects.get(id=id)
    except User.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)
Exemplo n.º 47
0
 def post(self, request, format=None):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 48
0
contentReport = JSONRenderer().render(rs.data)
contentReport

contentImageReport = JSONRenderer().render(irs.data)
contentImageReport

contentComment = JSONRenderer().render(cs.data)
contentComment

#Deserialize User
from django.utils.six import BytesIO

stream = BytesIO(content)
data = JSONParser().parse(stream)

serializer = UserSerializer(data=data)

#Deserialize Report
stream = BytesIO(contentReport)
data = JSONParser().parse(stream)

serializer = ReportSerializer(data=data)

#Deserialize ImageReport
stream = BytesIO(contentImageReport)
data = JSONParser().parse(stream)

serializer = ImageReportSerializer(data=data)

#Deserialize Comment
stream = BytesIO(contentComment)