Пример #1
0
    def save(cls, request_data, instance=None):
        try:
            file = request_data.pop('file', None)
            data = instance if instance else Data()

            for key in request_data:
                setattr(data, key, request_data[key])

            with transaction.atomic():

                #save info data
                data.save()
                ArangoDataService.save_post(data.__dict__)
                # save file to local
                if file:
                    extension = data.name[data.name.rfind('.'):]
                    file_name = str(data.id)+extension
                    local_file_path = join(settings.MEDIA_ROOT, file_name)
                    with open(local_file_path, 'wb') as dest:
                        for chunk in file.chunks():
                            dest.write(chunk)

                #update memory used
                from SocialNetwork_API.services import UserService
                user = UserService.get_user(data.user_id)
                user_data = {'memory_used': user.memory_used + data.capacity}
                UserService.save(instance=user, user_data=user_data)

            return data
        except Exception as exception:
            cls.log_exception(exception)
            raise exception
Пример #2
0
    def check_login(cls, data):
        try:
            password = data['password']
            if 'email' in data:
                email = data['email']
                user = UserService.authenticate(email=email,
                                                username=None,
                                                password=password)
            if 'username' in data:
                username = data['username']
                user = UserService.authenticate(username=username,
                                                email=None,
                                                password=password)
            user = ApiService.save(user)

            api_data = user['user'].__dict__
            if '_state' in api_data:
                del api_data['_state']
            api_data2 = user['token'].__dict__
            if '_state' in api_data2:
                del api_data2['_state']

            result = {'user': api_data, 'token': api_data2}
            return result
        except Exception as e:
            return None
Пример #3
0
    def reset_password(self, request, *args, **kwargs):
        try:
            user_id = request.data.get('user_id', None)
            user = User.objects.get(pk=user_id)
            if not user:
                raise exceptions.ValidationError('user_id is invalid')

            UserService.set_new_password(user, 'abc@123')
            return Response(status=status.HTTP_200_OK)
        except Exception as exception:
            raise exception
Пример #4
0
    def user_friend(cls, user, friend):
        try:
            user_friend = UserService.get_user_friend(user.id, friend.id)
            if user_friend is not None:
                error_message = '{0} was friend by you.'.format(
                    friend.username)
                raise exceptions.ValidationError(error_message)

            return UserService.user_friend(user, friend)
        except Exception as exception:
            raise exception
Пример #5
0
    def validate(self, attrs):
        username = attrs.pop('username', None)
        email = attrs.pop('email', None)
        password = attrs.pop('password', None)

        if email and password:
            user = UserService.authenticate(email=email,
                                            username=None,
                                            password=password,
                                            **attrs)
            if user:
                if not user.is_active:
                    msg = _('Your account is not activated.')
                    raise exceptions.ValidationError(msg)
                if user.is_disabled:
                    raise exceptions.ValidationError(
                        _('Your account have been disabled.'))
            else:
                msg = _('Unable to log in with provided credentials.')
                raise exceptions.ValidationError(msg)
        elif username and password:
            user = UserService.authenticate(username=username,
                                            email=None,
                                            password=password,
                                            **attrs)
            if user:
                if not user.is_active:
                    msg = _('Your account is not activated.')
                    raise exceptions.ValidationError(msg)
                if user.is_disabled:
                    raise exceptions.ValidationError(
                        _('Your account have been disabled.'))
            else:
                msg = _('Unable to log in with provided credentials.')
                raise exceptions.ValidationError(msg)
        else:
            msg = _('Must include username/email and password.')
            raise exceptions.ValidationError(msg)
        user_logged_in.send(sender=user.__class__, user=user)
        attrs['user'] = user
        attrs['is_social_login'] = False
        attrs['provider'] = ''
        return attrs
Пример #6
0
    def update(self, request, pk=None, *args, **kwargs):
        try:
            user = UserService.get_user(pk)
            serializer = self.serializer_class(instance=user,
                                               data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response(serializer.data)

        except Exception as exc:
            raise exc
Пример #7
0
    def validate(self, data):
        if data['data_status'] not in [
                StatusDataType.PUBLIC, StatusDataType.PRIVATE,
                StatusDataType.FRIEND
        ]:
            raise exceptions.APIException('status is invalid.')

        user = UserService.get_user(data['user_id'])
        if (user.memory_used + data['capacity'] > user.total_memory):
            raise exceptions.APIException('memory is not enough.')

        return data
Пример #8
0
    def test_add_friend(self, request, *args, **kwargs):
        try:
            data = {
                'user_id': request.data.get('user_id'),
                'friend_id': request.data.get('friend_id')
            }
            user = UserService.get_user(request.data.get('user_id'))
            serializer = FriendSerialiser(data=data)
            serializer.is_valid(raise_exception=True)
            serializer.user_friend(user, serializer.validated_data['friend'])

            return Response(status=status.HTTP_200_OK)
        except Exception as exception:
            raise ServiceException(exception)
Пример #9
0
    def change_password(self, request, *args, **kwargs):
        try:
            status_error = 0
            password = request.data.get('password', None)
            confirm_password = request.data.get('confirm_password', None)

            if not password and len(password.strip()) <= 6:
                status_error = 1
                raise exceptions.ValidationError(
                    'password must be at least 6 characters.')

            if password != confirm_password:
                status_error = 1
                raise exceptions.ValidationError(
                    'confirm_password is invalid.')

            UserService.set_new_password(request.user, password)

            return Response(status=status.HTTP_200_OK)
        except Exception as exception:
            if status_error == 1:
                raise exception
            else:
                raise ServiceException(exception)
Пример #10
0
    def update(self, request, pk=None, *args, **kwargs):
        try:
            user = UserService.get_user(pk)
            if user.id != request.user.id:
                raise exceptions.PermissionDenied()
            serializer = self.serializer_class(instance=user,
                                               data=request.data,
                                               partial=True)
            serializer.is_valid(raise_exception=True)
            serializer = UserSerializer(serializer.save())

            return Response(serializer.data)

        except Exception as exc:
            raise exc
Пример #11
0
    def validate(self, data):
        if 'friend_id' in data:
            friend_id = data['friend_id']
        if 'user_id' in data:
            user_id = data['user_id']

        if user_id == friend_id:
            raise exceptions.ValidationError(
                'friend_id must be different with user_id.')

        friend = UserService.get_user(friend_id)

        if not friend:
            error_message = ErrorMessage.DOES_NOT_EXIST.format('friend_id')
            raise exceptions.ValidationError(error_message)

        data['friend'] = friend
        return data
Пример #12
0
    def get_and_check(self, pk):
        post = UserService.get_user(pk)
        if not post:
            raise exceptions.NotFound()

        return post
Пример #13
0
 def create(self, validated_data):
     # for key in ['groups', 'user_permission']:
     #     if key in validated_data:
     #         del validated_data[key]
     user = UserService.save(validated_data)
     return user
Пример #14
0
 def update(self, instance, validated_data):
     return UserService.save(validated_data, instance)