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()
def send_sms(cls, request: Request, **kwargs): """ :param request: :param kwargs: :return: """ return service.send_sms(request.get("address"), request.get("text"))
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 }
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'))
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))
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())
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") }
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") }
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())
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()
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'))
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)
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
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}
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()}
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)
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()}
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")
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()}
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}
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")
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()}
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")
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}
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)
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()}
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
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()}
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()}
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()}
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()}
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()}
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()}
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()}
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"))
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) )
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)))
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") )
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)
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"])
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"])
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'))
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")
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")
def get_credentials(cls, request: Request, **kwargs): """ Возвращает учетные данные по id :param request: :param kwargs: :return: """ return service.get_credentials(request.get("uid"))
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
def delete_credentials(cls, request: Request, **kwargs): """ Удаляет учетные данные по id :param request: :param kwargs: :return: """ return service.delete_credentials(request.get("uid"))
def verify_phone(cls, request: Request, **kwargs): """ Метод для подтверждения номера телефона :param request: :param kwargs: :return: """ return service.verify_phone(cls.build_credentials(request), request.get("verification_code"))
def verify_email(cls, request: Request, **kwargs): """ Метод для подтверждения электронной почты :param request: :param kwargs: :return: """ return service.verify_email(cls.build_credentials(request), request.get("verification_code"))
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" )
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 }
def saveRatesBulk(cls, request: Request, **kwargs): """ :param request: :param kwargs: :return: """ data = request.get("data") return microservice("http://converter/save_bulk", {"data": data}, "result")
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")
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")))
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" )
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") }