Esempio n. 1
0
 def post(self, request):
     try:
         serialized_data = self.serializer_class(data=request.data)
         if serialized_data.is_valid(raise_exception=True):
             username = serialized_data.data['username']
             password = serialized_data.data['password']
             try:
                 user = User.objects.get(username=username)
             except User.DoesNotExist as e:
                 raise util_exception.CustomException(
                     detail=ugettext('User credentials are incorrect.'),
                     code=404)
             if user.check_password(password):
                 payload = jwt_payload_handler(user)  # todo: Is deprecated
                 jwt_token = utils.jwt_response_payload_handler(
                     jwt_encode_handler(payload))
                 return responses.SuccessResponse(jwt_token).send()
             else:
                 raise util_exception.CustomException(
                     detail=ugettext('User credentials are incorrect.'),
                     code=404)
     except util_exception.CustomException as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
     except exceptions.ValidationError as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 2
0
 def post(self, request):
     try:
         serialized_data = self.serializer_class(data=request.data)
         if serialized_data.is_valid(raise_exception=True):
             username = serialized_data.data['username']
             password = serialized_data.data['password']
             try:
                 user = User.objects.get(username=username)
             except User.DoesNotExist as e:
                 user = None
             if user:
                 raise util_exception.CustomException(detail=ugettext(
                     'User with this credentials is registered before.'),
                                                      code=400)
             user = transactions.register_user(username, password)
             payload = jwt_payload_handler(user)  # todo: Is deprecated
             jwt_token = utils.jwt_response_payload_handler(
                 jwt_encode_handler(payload))
             return responses.SuccessResponse(jwt_token, status=201).send()
     except util_exception.CustomException as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
     except exceptions.ValidationError as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 3
0
 def post(self, request, *args, **kwargs):
     try:
         serialize_data = self.get_serializer(data=request.data)
         if serialize_data.is_valid(raise_exception=True):
             self.perform_create(serialize_data)
             return responses.SuccessResponse(serialize_data.data, status=201).send()
     except IntegrityError as e:
         return responses.ErrorResponse(message=ugettext('DB Integrity Error in creation.'),
                                        dev_error=str(e), status=409).send()
     except (CustomException, ValidationError) as e:
         return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
Esempio n. 4
0
    def put(self, request, id=None):
        try:
            instance = self.get_instance(request, id)

            serialized_data = self.get_serializer(instance, data=request.data)
            if serialized_data.is_valid(raise_exception=True):
                self.perform_update(serialized_data)
                return responses.SuccessResponse(serialized_data.data).send()
        except self.model.DoesNotExist as e:
            return responses.ErrorResponse(message=ugettext('Does not exist.'),
                                           status=400).send()
        except (exceptions.CustomException, ValidationError) as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 5
0
    def post(self):
        """
        Login user

            username  min 5, max 50

            password  min 5, max 50


        :return:
        """
        try:
            data = LoginRegisterParser.parse_args()
            user = User.query.get(username=data['username'])
            if user is None:
                raise CustomException(detail='User does not exist.')
            else:
                if user.check_password(data['password']):
                    data = {'token': user.encode_auth_token()}
                    return responses.SuccessResponse(data).send()
                else:
                    raise CustomException(
                        detail='username or password is incorrect.')
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 6
0
    def post(self):
        """
        Register user

            username  min 5, max 50

            password  min 5, max 50


        :return:
        """
        try:
            data = LoginRegisterParser.parse_args()
            user = User.query.get(username=data['username'])
            if user is None:
                user = User(username=data['username'])
                user.set_password(data['password'])
                user.create()
                data = {'token': user.encode_auth_token()}
                return responses.SuccessResponse(data, status=201).send()
            else:
                raise CustomException(detail='A user with this data exist.')
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 7
0
    def post(self):
        """
        Create Ad

            title  min 3, max 100

            body  min 3, max 100

            category  {'id': id of category}

            media  [{'path': 'path of media'}] max 5

        :return:
        """
        try:
            data = AdParser.parse_args()
            data['category'] = Category.query.get(data['category']['id'])
            if not data['category']:
                raise CustomException(detail='Category does not exist.')
            media = data.pop('media')
            data['user'] = g.user
            ad_item = Ad(**data).create()
            if media:
                for item in media:
                    ad_item.media_set.append(Media(path=item['path']))
            ad_item.save()
            return responses.SuccessResponse(marshal(ad_item, AdSchema),
                                             status=201).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 8
0
    def get(self):
        """
        List of Ads

            with pagination index default 0, size default 20

            use search param query on title and body

            use category id of category filter on that category

            /?search=title&category=1

        :return:
        """
        try:
            arg = dict(request.args)
            index, size = handle_pagination(arg)
            ads = Ad.query.filter_by(is_deleted=False)
            if arg.get('category'):
                ads = ads.filter_by(category_id=arg['category'])
            if arg.get('search'):
                ads = ads.filter((Ad.title.contains(arg['search'])) | (
                    Ad.body.contains(arg['search']))).distinct()
            ads = ads.all()
            total = len(ads)
            return responses.SuccessResponse(marshal_list(
                ads[index:size], AdListSchema),
                                             index=index,
                                             total=total).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 9
0
    def post(self, request):
        try:
            serialized_data = self.serializer_class(data=request.data)
            if serialized_data.is_valid(raise_exception=True):
                email = serialized_data.data['email']
                password = serialized_data.data['password']
                user_list = User.objects.filter(email=email,
                                                email_confirmed=True)
                if user_list:
                    raise authnz_exceptions.CustomException(
                        detail=ugettext('You registered before.'))

                permissions.check_send_email_permission(email)

                try:  # check for previous used email
                    user = User.objects.get(email=email, email_confirmed=False)
                except User.DoesNotExist as e:
                    user = None

                if user:  # registered before but not confirmed
                    user = user.update_password(password)
                else:
                    user = User.register_user(email, password)
                user.send_email_confirm(request)
                return responses.SuccessResponse({}, status=201).send()
        except (authnz_exceptions.CustomException,
                exceptions.ValidationError) as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 10
0
    def put(self, id):
        """
        Update ad details by id

            title  min 3, max 100

            body  min 3, max 100

            category  {'id': id of category}

            media  [{'path': 'path of media', 'id': 'id of gallery'}] max 5  id is optional for checking previous created

        :param id:
        :return:
        """
        try:
            data = AdParser.parse_args()
            ad_item = Ad.query.get(id)
            if ad_item is None or ad_item.is_deleted:
                raise CustomException(detail='Ad does not exist.')

            ad_item.has_permission()
            ad_item.update(data)
            return responses.SuccessResponse(marshal(ad_item, AdSchema)).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 11
0
 def delete(self, request, id):
     try:
         feed = self.model.objects.get(id=id, is_deleted=False)
         feed.favorites.remove(request.user)
         return responses.SuccessResponse(status=204).send()
     except (exceptions.CustomException, self.model.DoesNotExist) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 12
0
 def delete(self, request, id):
     try:
         rss = self.model.objects.get(id=id, is_active=True)
         rss.followers.remove(request.user)
         return responses.SuccessResponse(status=204).send()
     except (exceptions.CustomException, self.model.DoesNotExist) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 13
0
 def decorated_function(*args, **kwargs):
     try:
         user = handle_jwt_decode(request)
     except exceptions.CustomException as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
     g.user = user
     return f(*args, **kwargs)
Esempio n. 14
0
    def get(self, request):
        try:
            if request.user.is_active:
                jwt_token = utils.jwt_response_payload_handler(
                    request.user.generate_token())
                return responses.SuccessResponse(jwt_token).send()
            else:
                raise authnz_exceptions.CustomException(
                    detail=ugettext('This user is inactive, contact us.'))

        except authnz_exceptions.CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 15
0
    def get(self, request, uidb64, token):
        try:
            try:
                uid = urlsafe_base64_decode(uidb64).decode()
                user = User.objects.get(pk=uid)
            except (TypeError, ValueError, OverflowError, User.DoesNotExist):
                user = None

            if user is not None and email_activation_token.check_token(
                    user, token):
                user.confirm_email()
                return render(request, 'authnz/mail_confirmed.html')
            else:
                return render(request,
                              'authnz/mail_confirm_invalid.html',
                              status=400)

        except exceptions.ValidationError as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
        except Exception as e:
            return responses.ErrorResponse(message=str(e)).send()
Esempio n. 16
0
 def get(self, request, id=None, *args, **kwargs):
     try:
         if id is None and self.model == User:
             instance = request.user
         elif hasattr(self.model, 'is_deleted'):
             instance = self.model.objects.get(id=id, is_deleted=False)
         else:
             instance = self.model.objects.get(id=id)
         serialize_data = self.get_serializer(instance)
         return responses.SuccessResponse(serialize_data.data).send()
     except self.model.DoesNotExist as e:
         return responses.ErrorResponse(message='Instance does not Found.',
                                        status=404).send()
Esempio n. 17
0
    def post(self, request):
        try:
            admin_data = {
                'email': '*****@*****.**',
                'password': '******',
            }
            user = User.register_user(admin_data['email'],
                                      admin_data['password'])
            user.is_staff = True
            user.is_superuser = True
            user.confirm_email()

            varzesh3_data = {
                'title': 'Varzesh3',
                'link': 'https://www.varzesh3.com/rss/all',
            }

            isna_data = {
                'title': 'Isna',
                'link': 'https://www.isna.ir/rss',
            }

            varzesh3_rss = Rss(**varzesh3_data)
            varzesh3_rss.save()
            tasks.check_new_rss.apply_async(args=(varzesh3_rss.id, ),
                                            retry=False)
            isna_rss = Rss(**isna_data)
            isna_rss.save()
            tasks.check_new_rss.apply_async(args=(isna_rss.id, ), retry=False)

            return responses.SuccessResponse({}, status=201).send()
        except IntegrityError as e:
            return responses.ErrorResponse(message=str(e), status=400).send()
        except (authnz_exceptions.CustomException,
                exceptions.ValidationError) as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 18
0
    def get(self, id):
        """
        Get ad details by id

        :param id:
        :return:
        """
        try:
            ad_item = Ad.query.get(id)
            if ad_item is None or ad_item.is_deleted:
                raise CustomException(detail='Ad does not exist.')
            return responses.SuccessResponse(marshal(ad_item, AdSchema)).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 19
0
 def get(self, request):
     try:
         index, size, args = utils.pagination_util(request)
         filters = {'followers': request.user}
         if args.get('title'):
             filters['title__icontains'] = args['title']
         rss_list = self.model.objects.filter(**filters)
         total = rss_list.count()
         data = self.get_serializer(rss_list[index:size], many=True).data
         return responses.SuccessResponse(data, index=index,
                                          total=total).send()
     except (exceptions.CustomException,
             drf_exceptions.ValidationError) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 20
0
 def get(self, request, id):
     try:
         rss = self.model.objects.get(id=id, is_active=True)
         fs = FollowRss.objects.filter(rss=rss, user=request.user)
         if fs:
             count = Feed.objects.filter(
                 rss=rss, published__gte=fs[0].last_seen).count()
             data = {'unread': count if count else 0}
             return responses.SuccessResponse(data).send()
         else:
             raise exceptions.CustomException(
                 detail=ugettext('You did not follow this Rss.'))
     except (exceptions.CustomException, drf_exceptions.ValidationError,
             Rss.DoesNotExist) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 21
0
    def post(self):
        """
        Create Category

            name string min_length 3, max_length 50


        :return:
        """
        try:
            data = CategoryParser.parse_args()
            category = Category(**data).create()
            return responses.SuccessResponse(marshal(category, CategorySchema),
                                             status=201).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 22
0
 def get(self, request, id):
     try:
         index, size, args = utils.pagination_util(request)
         comment_list = Comment.objects.filter(feed__id=id,
                                               feed__is_deleted=False,
                                               is_deleted=False)
         if args.get('order_by') and args['order_by'] == 'OLDEST':
             comment_list = comment_list.order_by('created')
         total = comment_list.count()
         data = self.get_serializer(comment_list[index:size],
                                    many=True).data
         return responses.SuccessResponse(data, index=index,
                                          total=total).send()
     except (exceptions.CustomException,
             drf_exceptions.ValidationError) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 23
0
 def delete(self, request, id):
     try:
         if hasattr(self.model, 'is_deleted'):
             instance = self.model.objects.get(id=id, is_deleted=False)
         else:
             instance = self.model.objects.get(id=id)
         permissions.check_delete_permission(request, instance)
         if hasattr(self.model, 'is_deleted'):
             instance.is_deleted = True
             instance.save()
         else:
             instance.delete()
         data = {}
         return responses.SuccessResponse(data, status=204).send()
     except (self.model.DoesNotExist, exceptions.CustomException) as e:
         return responses.ErrorResponse(
             message=ugettext('Instance does not exist.'),
             status=404).send()
Esempio n. 24
0
 def get(self, request):
     try:
         index, size, args = utils.pagination_util(request)
         filters = {'favorites': request.user}
         feed_list = self.model.objects.filter(**filters)
         if args.get('search'):
             feed_list = feed_list.filter(
                 Q(title__icontains=args['search'])
                 | Q(description__icontains=args['search'])).distinct()
         if args.get('order_by') and args['order_by'] == 'OLDEST':
             feed_list = feed_list.order_by('published')
         total = feed_list.count()
         data = self.get_serializer(feed_list[index:size], many=True).data
         return responses.SuccessResponse(data, index=index,
                                          total=total).send()
     except (exceptions.CustomException,
             drf_exceptions.ValidationError) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 25
0
    def delete(self, id):
        """
        Delete ad

            Soft delete

        :param id:
        :return:
        """
        try:
            ad_item = Ad.query.get(id)
            if ad_item is None or ad_item.is_deleted:
                raise CustomException(detail='Ad does not exist.')
            ad_item.has_permission()
            ad_item.delete()
            return responses.SuccessResponse(status=204).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 26
0
    def get(self):
        """
        List of categories

            with pagination index default 0, size default 20

        :return:
        """
        try:
            arg = dict(request.args)
            index, size = handle_pagination(arg)
            categories = Category.query.all()
            total = len(categories)
            return responses.SuccessResponse(marshal_list(
                categories[index:size], CategorySchema),
                                             index=index,
                                             total=total).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 27
0
 def post(self, request):
     try:
         serialized_data = self.serializer_class(data=request.data)
         if serialized_data.is_valid(raise_exception=True):
             email = serialized_data.data['email']
             password = serialized_data.data['password']
             try:
                 user = User.objects.get(email=email)
             except User.DoesNotExist as e:
                 raise authnz_exceptions.CustomException(
                     detail=ugettext('You did not registered before.'))
             if user.email_confirmed and user.is_active and user.check_password(
                     password):
                 user.save_last_login()
                 jwt_token = utils.jwt_response_payload_handler(
                     user.generate_token())
                 return responses.SuccessResponse(jwt_token).send()
             elif not user.email_confirmed:
                 try:
                     permissions.check_send_email_permission(email)
                 except authnz_exceptions.CustomException as e:
                     raise authnz_exceptions.CustomException(
                         detail=ugettext(
                             'You did not confirm your email and you'
                             ' reached max email sent, try later.'))
                 user.send_email_confirm(request)
                 raise authnz_exceptions.CustomException(
                     detail=ugettext('You did not confirm your email,'
                                     ' We sent you a confirmation email'))
             elif not user.is_active:
                 raise authnz_exceptions.CustomException(
                     detail=ugettext('Your account is not active,'
                                     ' please contact support.'))
             else:
                 raise authnz_exceptions.CustomException(
                     detail=ugettext('Wrong login credentials.'))
     except (authnz_exceptions.CustomException,
             exceptions.ValidationError) as e:
         return responses.ErrorResponse(message=e.detail,
                                        status=e.status_code).send()
Esempio n. 28
0
    def get(self, request, id):
        try:
            index, size, args = utils.pagination_util(request)
            rss = Rss.objects.get(id=id, is_active=True)
            # Update last seen this rss
            FollowRss.objects.filter(
                rss=rss, user=request.user).update(last_seen=utils.now_time())

            filters = {'rss': rss}
            if args.get('title'):
                filters['title__icontains'] = args['title']

            feed_list = self.model.objects.filter(**filters)
            if args.get('order_by') and args['order_by'] == 'OLDEST':
                feed_list = feed_list.order_by('published')
            total = feed_list.count()
            data = self.get_serializer(feed_list[index:size], many=True).data
            return responses.SuccessResponse(data, index=index,
                                             total=total).send()
        except (exceptions.CustomException, drf_exceptions.ValidationError,
                Rss.DoesNotExist) as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 29
0
 def post(self, request, *args, **kwargs):
     serialize_data = self.get_serializer(data=request.data)
     if serialize_data.is_valid():
         file = serialize_data.validated_data['file']
         xl = pd.ExcelFile(file)
         df = xl.parse(xl.sheet_names[0])
         for index, row in df.iterrows():
             if isinstance(row['date'], str):
                 date = datetime.strptime(row['date'], '%d/%m/%Y')
             else:
                 date = row['date']
             if date.year < 1900:
                 date = jdatetime.date(day=date.day,
                                       month=date.month,
                                       year=date.year).togregorian()
             name = row['name']
             price = row['price']
             total = row['total']
             try:
                 car = Car.objects.get(name=name)
             except Car.DoesNotExist as e:
                 car = Car(name=name)
                 car.save()
             car_stock = CarStock(car=car,
                                  price=price,
                                  total=total,
                                  date=date)
             car_stock.save()
         data = {}
         return responses.SuccessResponse(data, status=200).send()
     else:
         dev_error = serialize_data.errors
         message = 'Failed to upload {}'.format(
             serialize_data.data['file'].name)
         return responses.ErrorResponse(message=message,
                                        dev_error=dev_error,
                                        status=400).send()