Example #1
0
def update_user(data, user):
    user_serializer = UserProfileSerializer(data=data, instance=user)
    if user_serializer.is_valid():
        user_serializer.save()
        return user_serializer.data
    else:
        raise exceptions_utils.ValidationException(user_serializer.errors, status.HTTP_400_BAD_REQUEST)
Example #2
0
 def put(self, request):
     user = request.user
     serializer = UserProfileSerializer(user, data=request.DATA)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #3
0
 def put(self, request):
     user = request.user
     serializer = UserProfileSerializer(user, data=request.DATA)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #4
0
    def post(self, request, format=None):

        print(request.body)
        data = json.loads(request.body)

        # if data['facebook_token']:
        #     return Response("Good Job Josh!", status=status.HTTP_201_CREATED)
        # else:
        #     return Response({
        #         'status': 'Bad Request',
        #         'message': 'Wrong parameters'
        #     }, status=status.HTTP_400_BAD_REQUEST)

        graph = facebook.GraphAPI(access_token=data['facebook_token'])
        profile = graph.get_object("me")
        first_name, second_name = profile['name'].split()
        data['first_name'] = first_name
        data['second_name'] = second_name
        URL = "https://graph.facebook.com/{}/picture?type=small".format(profile['id'])


        print(data)
        print('validation')
        serializer = UserProfileSerializer(data=data)
        if serializer.is_valid():
            user = serializer.save()
            user.save()

            img_temp = NamedTemporaryFile(delete=True)
            img_temp.write(urllib2.urlopen(URL).read())
            img_temp.flush()

            user.avatar.save(profile['id']+'.png', File(img_temp))

            size = (128, 128)
            mask = Image.new('L', size, 0)
            draw = ImageDraw.Draw(mask)
            draw.ellipse((0, 0) + size, fill=255)
            from reach.settings import BASE_DIR, STATIC_ROOT
            print(user.avatar)
            print(os.path.join(BASE_DIR, str(user.avatar)))
            im = Image.open(os.path.join(STATIC_ROOT, str(user.avatar)))
            output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
            output.putalpha(mask)
            output.save(os.path.join(STATIC_ROOT, str(user.avatar)))

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            for error in serializer.errors:
                print error

        return Response({
            'status': 'Bad Request',
            'message': 'Wrong parameters'
        }, status=status.HTTP_400_BAD_REQUEST)
Example #5
0
	def post(self, request, format=None):
		user = UserSerializer(data=request.data)
		if user.is_valid():
			u = user.save()
		else:
			return Response(user.errors, status=status.HTTP_400_BAD_REQUEST)
		print u
		request.data['user'] = u.pk

		serializer = UserProfileSerializer(data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED, context={'request': request})
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #6
0
def authenticate_user(user, data):
    if user:
        token = fetch_token(user)
        user_serializer = UserProfileSerializer(user, data=data)
        if user_serializer.is_valid():
            keys = ['id', 'email']
            user_serializer_dict = {k: v for k, v in user_serializer.data.iteritems() if k in keys}
            user_serializer_dict['token'] = token
            user_serializer_dict.update(messages.LOGIN_SUCCESSFUL)
            return user_serializer_dict
        else:
            raise exceptions_utils.ValidationException(user_serializer.errors, status.HTTP_400_BAD_REQUEST)
    else:
        raise exceptions_utils.ValidationException(messages.INVALID_EMAIL_OR_PASSWORD, status.HTTP_401_UNAUTHORIZED)
Example #7
0
def delete_user(request, pk):
    if request.method == 'DELETE':
        try:
            user = validations_utils.user_validation(
                pk)  # Validates if user exists or not.
        except ValidationException as e:  # Generic exception
            return Response(e.errors, status=e.status)
        user.delete()
        fire_base = firebase.FirebaseApplication(
            'https://vogorentals.firebaseio.com/')
        result = fire_base.get('/users', None)
        res = result.keys()
        urlkey = ''
        for i in res:
            if result[str(i)]['id'] == int(pk):
                urlkey = i
        rem = fire_base.delete('/users/' + urlkey, None)

        return Response(messages.DELETED_USER,
                        status=status.HTTP_204_NO_CONTENT)
    elif request.method == 'GET':
        try:
            user = validations_utils.user_validation(
                pk)  # Validates if user exists or not.
        except ValidationException as e:  # Generic exception
            return Response(e.errors, status=e.status)
        user_profile_serializer = UserProfileSerializer(user)
        return Response(user_profile_serializer.data,
                        status=status.HTTP_200_OK)
Example #8
0
	def get(self, request, format=None):

		content = {
			'user': unicode(request.user),
			'auth': unicode(request.auth)
		}
		users = UserProfile.objects.all()
		serializer = UserProfileSerializer(users, many=True, context={'request': request})
		return Response(serializer.data)
Example #9
0
 def delete(self, request, format=None):
     try:
         user_obj = UserProfile.objects.get(user=request.user)
         user_obj.profile_picture = None
         user_obj.save()
         serializer = UserProfileSerializer(user_obj)
         return Response(serializer.data)
     except:
         return Response("No Picture object",
                         status=status.HTTP_400_BAD_REQUEST)
Example #10
0
def update_user(data, user):
    user_serializer = UserProfileSerializer(data=data, instance=user)
    if user_serializer.is_valid():
        fire_base = firebase.FirebaseApplication(
            'https://vogorentals.firebaseio.com/', None)
        user_serializer.save()
        result = fire_base.get('/users', None)
        res = result.keys()
        urlkey = ''
        for i in res:
            if result[str(i)]['id'] == int(
                    user.id
            ):  #replace 2 with id of the element you wish to update
                urlkey = str(i)
        rem = fire_base.patch('users/' + urlkey, user_serializer.data)
        return user_serializer.data
    else:
        raise exceptions_utils.ValidationException(user_serializer.errors,
                                                   status.HTTP_400_BAD_REQUEST)
Example #11
0
	def get(self, request, username):
		print request.user, request.auth
		content = {
			'user': unicode(request.user),
			'auth': unicode(request.auth)
		}
		user = self.get_user(username)
		serializer = UserProfileSerializer(user, context={'request': request})
		print serializer.data
		return Response(serializer.data)
Example #12
0
    def post(self, request, *args, **kwargs):
        serializer = UserProfileSerializer(data=request.data)
        if serializer.is_valid():
            cd = serializer.validated_data
            try:
                obj = UserProfile.objects.get(user=request.user)
                obj.company_name = cd.get('company_name')
                obj.profile_picture = cd.get('profile_picture')

            except UserProfile.DoesNotExist:
                obj = UserProfile(user=request.user,
                                  company_name=cd.get('company_name'),
                                  profile_picture=cd.get('profile_picture'))

            obj.save()
            serializer = UserProfileSerializer(obj)
            return Response(serializer.data)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Example #13
0
	def patch(self, request, username, format=None):
		user = self.get_user(username)
		main_user = self.get_main_user(username)

		# User Class update
		main_user_serializer = UserSerializer(main_user, data=request.data, partial=True)
		if main_user_serializer.is_valid():
			u = main_user_serializer.save()
		else:
			return Response(main_user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

		# UserProfile Class update
		user_serializer = UserProfileSerializer(user, data=request.data, partial=True, context={'request': request})
		if user_serializer.is_valid():
			
			user_serializer.save()

			return Response(user_serializer.data)
		
		return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #14
0
	def put(self, request, username, format=None):
		user = self.get_user(username)
		main_user = self.get_main_user(username)

		# User Class update
		main_user_serializer = UserSerializer(main_user, data=request.data)
		if main_user_serializer.is_valid():
			u = main_user_serializer.save()
		else:
			return Response(main_user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

		# UserProfile Class update
		# request.data['user'] = u.pk
		user_serializer = UserProfileSerializer(user, data=request.data)
		if main_user_serializer.is_valid():
			# request.data['user'] = u.pk
			user_serializer.save()

			return Response(user_serializer.data)
		
		return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #15
0
    def create(self, request, *args, **kwargs):
        """Register a new user by atomically creating a User and associated UserProfile.

        NB: This view is custom because we really don't want to be serializing the password
        back to the caller.
        """

        request_serializer = self.get_serializer(data=request.data)

        with transaction.atomic():
            if request_serializer.is_valid():
                user_profile = request_serializer.save()
                return Response(UserProfileSerializer(user_profile).data,
                                status=status.HTTP_201_CREATED)

            return Response(request_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Example #16
0
 def get(self, request):
     serializer = UserProfileSerializer(request.user)
     return Response(serializer.data)
Example #17
0
 def get(self, request):
     user = request.user
     serializer = UserProfileSerializer(user, many=False)
     return Response(serializer.data)
Example #18
0
def user_detail(request, pk):
    """

    **Get or change the user profile data- Ignore**

    > GET

    Returns the User Profile data.

    * Requires `user id` which is an integer and taken as primary key
    to identify user.

    * Possible HTTP status codes and JSON response:

        * `HTTP_200_OK` - Returns the User Profile data:

                {
                  "email": String,
                  "id": Integer,
                  "first_name": String,
                  "last_name": String,
                  "created": String,
                  "contact_no": Integer
                }

        * `HTTP_500_INTERNAL_SERVER_ERROR` - Internal server error



    > PUT

    ### Update User Profile Data

    * Requires data that needs to be changed. Any and all of the below fields
    could be modified in a single PUT request.

        1. `first_name`: String
        2. `last_name`: String
        3. `contact_no`: Integer
        4. `email` : String


    * Requires only the changed data of the user and `email` along the changed
    parameters.

    * Possible HTTP status codes and JSON response:

        * `HTTP_200_OK` - User profile data in JSON format:

                {
                  "email": String,
                  "id": Integer,
                  "first_name": String,
                  "last_name": String,
                  "created": String,
                  "contact_no": Integer
                }

        * `HTTP_500_INTERNAL_SERVER_ERROR`

        :param pk:
        :param request:
    """
    data = request.data
    try:
        user = validations_utils.user_validation(
            pk)  # Validates if user exists or not.
        # validations_utils.user_token_validation(request.auth.user_id, pk)  # Validates user's Token authentication.
    except ValidationException as e:  # Generic exception
        return Response(e.errors, status=e.status)
    if request.method == 'GET':
        fire_base = firebase.FirebaseApplication(
            'https://userfirebase-1e188.firebaseio.com/', None)
        result = fire_base.get('/users', None)

        user_profile_serializer = UserProfileSerializer(user)
        return Response(user_profile_serializer.data,
                        status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        try:
            data = validations_utils.email_validation(
                data
            )  # Validates email id, it returns lower-cased email in data.
            updated_data = utils.update_user(data, user)  # Updates user data.
            return Response(updated_data, status=status.HTTP_200_OK)
        except ValidationException as e:  # Generic exception
            return Response(e.errors, status=e.status)