Example #1
0
 def confirm_email_and_auth(cls, user, request: Request, **kwargs):
     phone = Phone(request.get("phone")).get_value()
     target_user = cls.users_collection().get_item({"account.login": phone, "phone_verified": True})
     if target_user.verification_code == request.get("vc1") and target_user.verification_code2 == request.get("vc2"):
         target_user.email_verified = True
         target_user.verification_code = None
         target_user.verification_code_failed_attempts = 0
         target_user.save()
         user.refresh()
         cls.auth_service().send_email_confirmation_success(target_user.email)
         return {
             "user": user.stringify(["position_name", "name", "phone", "phone_verified", "email", "email_verified"]),
             "preview_randomizer": datetime.now().microsecond
         }
     else:
         target_user.verification_code_failed_attempts += 1
         if target_user.verification_code_failed_attempts < 3:
             target_user.save()
             raise IncorrectVerificationCode()
         else:
             target_user.email = None
             target_user.email_verified = False
             target_user.verification_code = None
             target_user.verification_code2 = None
             target_user.verification_code_failed_attempts = 0
             target_user.save()
             raise IncorrectVerificationCodeFatal()
Example #2
0
 def send_sms(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     return service.send_sms(request.get("address"), request.get("text"))
Example #3
0
 def ajax_auth(cls, user, request: Request, **kwargs):
     request.set("login", Phone(request.get("login")).get_value())
     if AuthController.auth(request, **kwargs):
         return {
             "user": user.stringify(["position_name", "name", "phone", "phone_verified", "email", "email_verified"]),
             "preview_randomizer": datetime.now().microsecond
         }
Example #4
0
 def test_getter(self):
     """ Запрос инициализируется любым количеством словарей """
     request = Request({'a': 1}, {'b': 2}, {'c': 3}, {'d': 4})
     self.assertEqual(1, request.get('a'))
     self.assertEqual(2, request.get('b'))
     self.assertEqual(3, request.get('c'))
     self.assertEqual(4, request.get('d'))
Example #5
0
 def test_getter_default(self):
     request = Request({'a': 1}, {'b': 2}, {'c': 3}, {'d': 4})
     self.assertRaises(Request.RequiredArgumentIsMissing, request.get, 'x')
     self.assertEqual("xxx", request.get('x', "xxx"))
     self.assertEqual("xxx", request.get('x', default="xxx"))
     self.assertEqual(None, request.get('x', None))
     self.assertEqual(None, request.get('x', default=None))
Example #6
0
 def test_getter(self):
     """ Запрос инициализируется любым количеством словарей """
     request = Request({'a': 1}, {'b': 2}, {'c': 3}, {'d': 4})
     self.assertEqual(1, request.get('a'))
     self.assertEqual(2, request.get('b'))
     self.assertEqual(3, request.get('c'))
     self.assertEqual(4, request.get('d'))
Example #7
0
    def test_json_rpc_type_detection(self):
        """ JsonRPC запрос определяется по наличию аргумента q в запросе и только по нему одному """
        request = Request({"q": "{}"})
        self.assertEqual(Request.Types.JSON_RPC, request.type())

        request = Request({"q": "{}"}, environ={"HTTP_X_REQUESTED_WITH": "XMLHttpRequest"})
        self.assertEqual(Request.Types.JSON_RPC, request.type())
Example #8
0
 def crop(request: Request, *args, **kwargs):
     """ Обрезает загруженное изображение
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     payload = {
         "base64": request.get("img"),
         "coords": request.get("coords"),
         "from_size": request.get("from_size")
     }
     cropped_base64 = microservice("http://img/crop", payload, "base64")
     resized_base64_800 = microservice("http://img/scale", {
         "base64": cropped_base64,
         "size": 800
     }, "base64")
     resized_base64_400 = microservice("http://img/scale", {
         "base64": cropped_base64,
         "size": 400
     }, "base64")
     return {
         "url":
         microservice("http://s3/upload", {'base64': resized_base64_400},
                      "url"),
         "url_800":
         microservice("http://s3/upload", {'base64': resized_base64_800},
                      "url")
     }
Example #9
0
 def upload(request: Request, *args, **kwargs):
     """ Загружает изображение в облако и возвращает URL
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     if request.get("size", False):
         size = int(request.get("size"))
         resized_base64 = microservice("http://img/scale", {
             "base64": request.get("img"),
             "size": size
         }, "base64")
         return {
             "url_%s" % size:
             microservice("http://s3/upload", {'base64': resized_base64},
                          "url")
         }
     else:
         resized_base64_800 = microservice("http://img/scale", {
             "base64": request.get("img"),
             "size": 800
         }, "base64")
         resized_base64_400 = microservice("http://img/scale", {
             "base64": resized_base64_800,
             "size": 400
         }, "base64")
         return {
             "url_800":
             microservice("http://s3/upload",
                          {'base64': resized_base64_800}, "url"),
             "url_400":
             microservice("http://s3/upload",
                          {'base64': resized_base64_400}, "url")
         }
Example #10
0
 def test_pjax_type_detection(self):
     """ Pjax запрос определяется по двум заголовкам HTTP_X_REQUESTED_WITH и HTTP_X_PJAX """
     request = Request(environ={
         "HTTP_X_PJAX": True,
         "HTTP_X_REQUESTED_WITH": "XMLHttpRequest"
     })
     self.assertEqual(Request.Types.PJAX, request.type())
Example #11
0
 def recover_password(cls, user, request: Request, **kwargs):
     phone = Phone(request.get("phone")).get_value()
     target_user = cls.users_collection().get_item({"account.login": phone, "phone_verified": True})
     if target_user.email_verified:
         cls.auth_service().change_password(target_user.email)
         return True
     if target_user.verification_code == request.get("vc1") and target_user.verification_code2 == request.get("vc2"):
         target_user.email_verified = True
         target_user.verification_code = None
         target_user.verification_code_failed_attempts = 0
         target_user.save()
         cls.auth_service().change_password(target_user.email)
         return True
     else:
         target_user.verification_code_failed_attempts += 1
         if target_user.verification_code_failed_attempts < 3:
             target_user.save()
             raise IncorrectVerificationCode()
         else:
             target_user.email = None
             target_user.email_verified = False
             target_user.verification_code = None
             target_user.verification_code2 = None
             target_user.verification_code_failed_attempts = 0
             target_user.save()
             raise IncorrectVerificationCodeFatal()
Example #12
0
 def test_getter_type_casting_exception(self):
     """ Выброс исключения при невозможности приведения аргументов к нужному типу """
     request = Request({'a': '1abc'})
     self.assertRaises(Request.ArgumentTypeError,
                       request.get,
                       'a',
                       cast_type=int)
     self.assertEqual('1abc', request.get('a'))
Example #13
0
 def send_email(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     html = base64.b64decode(request.get("base64").replace(" ", "+").encode()).decode()
     return service.send_email(request.get("address"), request.get("subject"), html)
Example #14
0
 def new_default_account(cls, request: Request, do_auth=True, auto_register=False) -> Account:
     account = Account({"login": AuthentificationService.gen_password(), "password": AuthentificationService.gen_password()})
     if do_auth:
         request.set("token", account.set_new_token())
         cls.auth(request)
     if auto_register:
         cls.users_collection().get_new_item().load_from_array({"name": "Анонимный пользователь", "account": account}).save()
     return account
Example #15
0
 def get_wishlist(cls, request: Request, *args, **kwargs):
     """ Метод для получения списка избранных товаров покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     wishlist = carts.get_cart(int(request.get("wishlist_id")) if request.get("wishlist_id", None) else None)
     return {"wishlist": wishlist.get_data() if wishlist else None}
Example #16
0
 def get_cart(cls, request: Request, *args, **kwargs):
     """ Метод для получения объекта корзины покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     cart = carts.get_cart(int(request.get("cart_id")) if request.get("cart_id", None) else None)
     return {"cart": cart.get_data()}
Example #17
0
 def authenticate_vk(cls, request: Request, **kwargs):
     """ Метод для выполнения аутентификации через Вк
     :param request:
     :param kwargs:
     :return:
     """
     code = request.get("code")
     redirect_url = request.get("redirect_url", None)
     return service.authenticate_vk(cls.build_credentials(request), code, redirect_url)
Example #18
0
 def create_category(cls, request: Request, *args, **kwargs):
     """ Метод для создания новых рубрик
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     catalog.create_category(request.get("category_name"), request.get("slug"))
     return {"categories": catalog.get_categories()}
Example #19
0
 def auth(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     login = request.get("login")
     password = request.get("password")
     return microservice("http://auth/auth", {"login": login, "password": password}, "result")
Example #20
0
 def scale(cls, request: Request, **kwargs):
     """ Метод для изменения размера изображения (масштабирование)
     :param request:
     :param kwargs:
     :return:
     """
     bytes_object = BytesIO(base64.b64decode(request.get("base64").replace(" ", "+").encode()))
     converted = ImageProcessor(bytes_object).scale(request.get("size"))
     return {"base64": base64.b64encode(converted.getvalue()).decode()}
Example #21
0
 def delete(cls, request: Request, *args, **kwargs):
     """ Метод для удаления поста
     :param request:
     :param kwargs:
     :return:
     """
     if request.get("id", False):
         return {"result": catalog.delete_item(request.get("id"))}
     return {"result": False}
Example #22
0
 def upload(request: Request, *args, **kwargs):
     import requests
     import json
     payload = {'base64': request.get("img")}
     r = requests.post("http://z9s3/upload", data=payload)
     if r.status_code == 200:
         return json.loads(r.text).get("url")
     else:
         return request.get("img")
Example #23
0
 def crop(cls, request: Request, **kwargs):
     """ Метод для обрезки изображения
     :param request:
     :param kwargs:
     :return:
     """
     bytes_object = BytesIO(base64.b64decode(request.get("base64").replace(" ", "+").encode()))
     converted = ImageProcessor(bytes_object).crop(request.get("coords"), request.get("from_size"))
     return {"base64": base64.b64encode(converted.getvalue()).decode()}
Example #24
0
 def crop(request: Request, *args, **kwargs):
     import requests
     import json
     payload = {'img': request.get("img"), 'coords': json.dumps(request.get("coords")), "from_size": json.dumps(request.get("from_size"))}
     r = requests.post("http://z9img/crop", data=payload)
     if r.status_code == 200:
         return r.text
     else:
         return request.get("img")
Example #25
0
 def send_sms(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     as_json = request.get("as_json", False)
     result = service.send_sms(request.get("address"), request.get("text"))
     return result if not as_json else {"result": result}
Example #26
0
 def auth(cls, request: Request, **kwargs):
     """ Authenticating """
     token = request.get("token", None)
     if token:
         return CredentialsRecords.auth_by_token(token)
     else:
         login = request.get("login")
         password = request.get("password")
         return CredentialsRecords.auth(login, password)
Example #27
0
 def set_quantity_for_item(cls, request: Request, *args, **kwargs):
     """ Метод для установки количества товара в корзине покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     cart = carts.get_cart(int(request.get("cart_id")) if request.get("cart_id", None) else None)
     cart.set_quantity_for_item(int(request.get("item_id")), int(request.get("quantity")))
     return {"cart": cart.get_data()}
Example #28
0
 def update_customer(cls, request: Request, *args, **kwargs):
     """ Метод для изменения объекта покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     customer = customers.get_customer(int(request.get("customer_id")))
     customer.update(request.get("name"), request.get("address"))
     return customer.get_data() if customer else None
Example #29
0
 def authenticate_vk(cls, request: Request, **kwargs):
     """ Метод для выполнения аутентификации через Вк
     :param request:
     :param kwargs:
     :return:
     """
     code = request.get("code")
     redirect_url = request.get("redirect_url", None)
     return service.authenticate_vk(cls.build_credentials(request), code,
                                    redirect_url)
Example #30
0
 def add_to_cart(cls, request: Request, *args, **kwargs):
     """ Метод для добавления товара в корзину покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     cart = carts.get_cart(int(request.get("cart_id")) if request.get("cart_id", None) else None)
     cart.add_item(int(request.get("item_id")), int(request.get("quantity")))
     return {"cart": cart.get_data()}
Example #31
0
 def set_quantity_for_wishlist_item(cls, request: Request, *args, **kwargs):
     """ Метод для установки количества товара в избранном покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     wishlist = carts.get_cart(int(request.get("wishlist_id")) if request.get("wishlist_id", None) else None)
     wishlist.set_quantity_for_item(int(request.get("item_id")), int(request.get("quantity")))
     return {"wishlist": wishlist.get_data()}
Example #32
0
 def clear_cart(cls, request: Request, *args, **kwargs):
     """ Метод для очистки корзины покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     cart = carts.get_cart(int(request.get("cart_id")) if request.get("cart_id", None) else None)
     cart.clear()
     return {"cart": cart.get_data()}
Example #33
0
 def add_to_wishlist(cls, request: Request, *args, **kwargs):
     """ Метод для добавления товара в избранное покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     wishlist = carts.get_cart(int(request.get("wishlist_id")) if request.get("wishlist_id", None) else None)
     wishlist.add_item(int(request.get("item_id")), int(request.get("quantity")))
     return {"wishlist": wishlist.get_data()}
Example #34
0
 def remove_from_wishlist(cls, request: Request, *args, **kwargs):
     """ Метод для удаление товара из избранного покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     wishlist = carts.get_cart(int(request.get("wishlist_id")) if request.get("wishlist_id", None) else None)
     wishlist.remove_item(int(request.get("item_id")))
     return {"wishlist": wishlist.get_data()}
Example #35
0
 def remove_from_cart(cls, request: Request, *args, **kwargs):
     """ Метод для удаление товара из корзины покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     cart = carts.get_cart(int(request.get("cart_id")) if request.get("cart_id", None) else None)
     cart.remove_item(int(request.get("item_id")))
     return {"cart": cart.get_data()}
Example #36
0
 def clear_wishlist(cls, request: Request, *args, **kwargs):
     """ Метод для очистки избранного покупателя
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     wishlist = carts.get_cart(int(request.get("wishlist_id")) if request.get("wishlist_id", None) else None)
     wishlist.clear()
     return {"wishlist": wishlist.get_data()}
Example #37
0
 def set_new_password(cls, request: Request, **kwargs):
     """ Метод для восстановления пароля пользователя
     :param request:
     :param kwargs:
     :return:
     """
     return service.set_new_password(cls.build_credentials(request),
                                     request.get("current_password"),
                                     request.get("new_password"),
                                     request.get("new_password2"))
Example #38
0
File: models.py Project: verteen/z9
 def authentificate_by_request(cls, request: Request):
     """
     Выполняет аутентификацию пользователя по переданному объекту Request
     :param request: Запрос пользователя
     :return:
     """
     return cls.authentificate(
         (request.get("login"), request.get("password")) if request.get("login", False) else None,
         request.get("token", False)
     )
Example #39
0
 def test_no_data(self):
     r = Request()
     r.set("base_currency", Currencies.EUR)
     self.assertEqual(
         {
             "error": {
                 "code": "CONVERTER_1",
                 "message": "No Data For Requested Currency"
             }
         }, json.loads(DefaultController.get_last_value(r)))
Example #40
0
 def set_new_password(cls, request: Request, **kwargs):
     """ Метод для восстановления пароля пользователя
     :param request:
     :param kwargs:
     :return:
     """
     return service.set_new_password(
         cls.build_credentials(request), request.get("current_password"),
         request.get("new_password"), request.get("new_password2")
     )
Example #41
0
    def get_transactions(cls, request: Request, **kwargs):
        """ Get history of transactions """
        login = request.get("login")
        period_starts = datetime.strptime(request.get("period_starts"), "%c") \
            if request.get("period_starts", None) else None

        period_ends = datetime.strptime(request.get("period_ends"), "%c") \
            if request.get("period_ends", None) else None

        return Wallets.get_transactions(login, period_starts, period_ends)
Example #42
0
 def test_creating_on_demand(self):
     """ gracefull degradation: if someone authenticates with given login - we have to create a wallet for him """
     r = Request()
     r.set("login", "MyLogin")
     self.assertEqual(
         {
             "login": "******",
             "base_currency": Currencies.USD,
             "balance": 0
         },
         json.loads(DefaultController.get(r))["result"])
Example #43
0
 def test_creating_on_demand(self):
     """ gracefull degradation: if someone authenticates with given login - we have to create a user for him """
     r = Request()
     r.set("login", "MyLogin")
     self.assertEqual(
         {
             "login": "******",
             "name": "Unknown",
             "country_id": None,
             "city_id": None
         },
         json.loads(DefaultController.get(r))["result"])
Example #44
0
    def test_override(self):
        """ Из нескольких значений аргумента в запросе сохранится последнее переданное """
        request = Request({'prop': 1}, {'prop': 2})
        self.assertEqual(2, request.get('prop'))

        request.set('prop', 3)
        self.assertEqual(3, request.get('prop'))

        request.update({'prop': 4})
        self.assertEqual(4, request.get('prop'))
Example #45
0
 def saveRate(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     base_currency = request.get("base_currency")
     value = request.get("value")
     datetime = request.get("datetime")
     return microservice("http://converter/save", {
         "base_currency": base_currency,
         "value": value,
         "datetime": datetime
     }, "result")
Example #46
0
 def getTransactions(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     login = request.get("login")
     period_starts = request.get("period_starts", None)
     period_ends = request.get("period_ends", None)
     return microservice(
         "http://wallets/get_transactions", {
             "login": login,
             "period_starts": period_starts,
             "period_ends": period_ends
         }, "result")
Example #47
0
 def get_credentials(cls, request: Request, **kwargs):
     """ Возвращает учетные данные по id
     :param request:
     :param kwargs:
     :return:
     """
     return service.get_credentials(request.get("uid"))
Example #48
0
    def topUpBalance(cls, request: Request, **kwargs):
        """
        :param request:
        :param kwargs:
        :return:
        """
        login = request.get("login")
        base_currency = request.get("base_currency")
        amount = request.get("amount")
        microservice("http://wallets/topup", {
            "login": login,
            "base_currency": base_currency,
            "amount": amount
        }, "result")

        return True
Example #49
0
 def delete_credentials(cls, request: Request, **kwargs):
     """ Удаляет учетные данные по id
     :param request:
     :param kwargs:
     :return:
     """
     return service.delete_credentials(request.get("uid"))
Example #50
0
 def verify_phone(cls, request: Request, **kwargs):
     """ Метод для подтверждения номера телефона
     :param request:
     :param kwargs:
     :return:
     """
     return service.verify_phone(cls.build_credentials(request),
                                 request.get("verification_code"))
Example #51
0
 def verify_email(cls, request: Request, **kwargs):
     """ Метод для подтверждения электронной почты
     :param request:
     :param kwargs:
     :return:
     """
     return service.verify_email(cls.build_credentials(request),
                                 request.get("verification_code"))
Example #52
0
 def createWallet(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     token = request.get("token")
     login = microservice("http://auth/auth", {"token": token}, "result")
     base_currency = request.get("base_currency")
     return microservice(
         "http://wallets/create",
         {
             "login": login,
             "base_currency": base_currency
         },
         "result"
     )
Example #53
0
 def getConvertionRates(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     from_base_currency = request.get("from_base_currency")
     to_base_currency = request.get("to_base_currency")
     conversion_rate1 = microservice(
         "http://converter/get_last_value", {"base_currency": from_base_currency}, "result"
     )
     conversion_rate2 = microservice(
         "http://converter/get_last_value", {"base_currency": to_base_currency}, "result"
     )
     return {
         "conversion_rate1": conversion_rate1,
         "conversion_rate2": conversion_rate2
     }
Example #54
0
 def saveRatesBulk(cls, request: Request, **kwargs):
     """
     :param request:
     :param kwargs:
     :return:
     """
     data = request.get("data")
     return microservice("http://converter/save_bulk", {"data": data},
                         "result")
Example #55
0
 def delete_item(request: Request, *args, **kwargs):
     """ Удаляет запись
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     return microservice("http://catalog-api/delete",
                         {"id": request.get("id", False)}, "result")
Example #56
0
 def set_new_phone(cls, request: Request, **kwargs):
     """ Метод для восстановления пароля пользователя
     :param request:
     :param kwargs:
     :return:
     """
     return service.set_new_phone(
         cls.build_credentials(request),
         normalize_phone_number(request.get("new_phone")))
Example #57
0
 def test_getter_default(self):
     request = Request({'a': 1}, {'b': 2}, {'c': 3}, {'d': 4})
     self.assertRaises(Request.RequiredArgumentIsMissing, request.get, 'x')
     self.assertEqual("xxx", request.get('x', "xxx"))
     self.assertEqual("xxx", request.get('x', default="xxx"))
     self.assertEqual(None, request.get('x', None))
     self.assertEqual(None, request.get('x', default=None))
Example #58
0
    def transferMoney(cls, request: Request, **kwargs):
        """
        :param request:
        :param kwargs:
        :return:
        """
        token = request.get("token")
        login = microservice("http://auth/auth", {"token": token}, "result")
        from_base_currency = request.get("from_base_currency")

        to_login = request.get("to_login")
        to_base_currency = request.get("to_base_currency")

        amount = request.get("amount")
        conversion_rate_uuid_1 = request.get("conversion_rate_uuid_1", None)
        conversion_rate_uuid_2 = request.get("conversion_rate_uuid_2", None)

        return microservice(
            "http://wallets/transfer",
            {
                "from_login": login, "from_base_currency": from_base_currency,
                "to_login": to_login, "to_base_currency": to_base_currency,
                "amount": amount,
                "conversion_rate_uuid_1": conversion_rate_uuid_1,
                "conversion_rate_uuid_2": conversion_rate_uuid_2
            },
            "result"
        )
Example #59
0
 def create_category(request: Request, *args, **kwargs):
     """ Создает новую рубрику в блоге
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     payload = {"category_name": request.get("category_name", False)}
     return {
         "categories":
         microservice("http://catalog-api/create_category", payload,
                      "categories")
     }
Example #60
0
    def test_json_rpc_type_detection(self):
        """ JsonRPC запрос определяется по наличию аргумента q в запросе и только по нему одному """
        request = Request({"q": "{}"})
        self.assertEqual(Request.Types.JSON_RPC, request.type())

        request = Request({"q": "{}"},
                          environ={"HTTP_X_REQUESTED_WITH": "XMLHttpRequest"})
        self.assertEqual(Request.Types.JSON_RPC, request.type())