Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1022,6 +1022,47 @@ def get_order_monitop():
|
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1025 |
|
| 1026 |
# Чтение ордера по ключу и ВК ИД для приложения
|
| 1027 |
@app.route('/get_order', methods=['POST'])
|
|
@@ -1033,8 +1074,9 @@ def get_order():
|
|
| 1033 |
vkid = request.form.get('vk_id', '')
|
| 1034 |
order = request.form.get('order', '')
|
| 1035 |
apps_id = request.form.get('apps_id', '') # Сюда придёт ИД ВК приложения
|
|
|
|
| 1036 |
|
| 1037 |
-
logging.debug(f"Received data: vk_id={vkid}, order={order}, apps_id={apps_id}")
|
| 1038 |
|
| 1039 |
# Преобразуем строку в JSON
|
| 1040 |
try:
|
|
@@ -1043,17 +1085,35 @@ def get_order():
|
|
| 1043 |
logging.error(f"Error decoding JSON: {e}")
|
| 1044 |
return jsonify({"status": "invalid"}), 200
|
| 1045 |
|
| 1046 |
-
#
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
logging.error("Key not found")
|
| 1051 |
-
return jsonify({"status": "invalid"}), 200
|
| 1052 |
|
|
|
|
| 1053 |
logging.debug(f"Using secret: {secret}")
|
| 1054 |
|
| 1055 |
-
#
|
| 1056 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1057 |
return jsonify(response), 200
|
| 1058 |
|
| 1059 |
except Exception as e:
|
|
@@ -1078,7 +1138,6 @@ def get_order():
|
|
| 1078 |
|
| 1079 |
|
| 1080 |
|
| 1081 |
-
|
| 1082 |
|
| 1083 |
|
| 1084 |
|
|
|
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
+
|
| 1026 |
+
# Функция для валидации подписи ВК приложения
|
| 1027 |
+
def is_valid(*, query: dict, secret: str) -> bool:
|
| 1028 |
+
"""Check VK Apps signature"""
|
| 1029 |
+
# Отфильтровываем параметры, начинающиеся с "vk_"
|
| 1030 |
+
vk_subset = OrderedDict(sorted((k, v) for k, v in query.items() if k.startswith("vk_")))
|
| 1031 |
+
logging.debug(f"Filtered VK params: {vk_subset}")
|
| 1032 |
+
|
| 1033 |
+
# Объединяем параметры в строку
|
| 1034 |
+
encoded_params = urlencode(vk_subset, doseq=True)
|
| 1035 |
+
logging.debug(f"Encoded params: {encoded_params}")
|
| 1036 |
+
|
| 1037 |
+
# Вычисляем хеш-код с использованием HMAC и SHA256
|
| 1038 |
+
hash_code = b64encode(HMAC(secret.encode(), encoded_params.encode(), sha256).digest())
|
| 1039 |
+
decoded_hash_code = hash_code.decode('utf-8')[:-1].replace('+', '-').replace('/', '_')
|
| 1040 |
+
logging.debug(f"Calculated signature: {decoded_hash_code}")
|
| 1041 |
+
|
| 1042 |
+
# Сравниваем с переданной подписью
|
| 1043 |
+
return query.get("sign") == decoded_hash_code
|
| 1044 |
+
|
| 1045 |
+
# Функция для работы с базой данных
|
| 1046 |
+
def get_order_from_db(vkid):
|
| 1047 |
+
conn = sqlite3.connect(DATABASE_NEW)
|
| 1048 |
+
cursor = conn.cursor()
|
| 1049 |
+
|
| 1050 |
+
# Ищем запись по vk_id
|
| 1051 |
+
cursor.execute("SELECT orders FROM contacts WHERE vk_id = ?", (vkid,))
|
| 1052 |
+
result = cursor.fetchone()
|
| 1053 |
+
logging.debug(f"Database result: {result}")
|
| 1054 |
+
|
| 1055 |
+
# Если запись по vk_id не найдена, возвращаем значение "not" для ордера
|
| 1056 |
+
if not result:
|
| 1057 |
+
logging.error(f"VK ID {vkid} not found")
|
| 1058 |
+
return None
|
| 1059 |
+
|
| 1060 |
+
shop_st = result[0] if result[0] else '{}'
|
| 1061 |
+
logging.debug(f"Shop_st: {shop_st}")
|
| 1062 |
+
shop_st_data = json.loads(shop_st)
|
| 1063 |
+
logging.debug(f"Existing record found. Loaded JSON: {shop_st_data}")
|
| 1064 |
+
|
| 1065 |
+
return shop_st_data
|
| 1066 |
|
| 1067 |
# Чтение ордера по ключу и ВК ИД для приложения
|
| 1068 |
@app.route('/get_order', methods=['POST'])
|
|
|
|
| 1074 |
vkid = request.form.get('vk_id', '')
|
| 1075 |
order = request.form.get('order', '')
|
| 1076 |
apps_id = request.form.get('apps_id', '') # Сюда придёт ИД ВК приложения
|
| 1077 |
+
fullUrl = request.form.get('fullUrl', '') # Полный URL, который выдаёт ВКонтакте
|
| 1078 |
|
| 1079 |
+
logging.debug(f"Received data: vk_id={vkid}, order={order}, apps_id={apps_id}, fullUrl={fullUrl}")
|
| 1080 |
|
| 1081 |
# Преобразуем строку в JSON
|
| 1082 |
try:
|
|
|
|
| 1085 |
logging.error(f"Error decoding JSON: {e}")
|
| 1086 |
return jsonify({"status": "invalid"}), 200
|
| 1087 |
|
| 1088 |
+
# Проверка подписи для приложения
|
| 1089 |
+
if str(apps_id) not in api_key_apps_vk_dict: # Приводим apps_id к строке
|
| 1090 |
+
logging.error("Invalid apps_id")
|
| 1091 |
+
return json.dumps({"error": "Invalid apps_id"}), 400
|
|
|
|
|
|
|
| 1092 |
|
| 1093 |
+
secret = api_key_apps_vk_dict[str(apps_id)] # Приводим apps_id к строке
|
| 1094 |
logging.debug(f"Using secret: {secret}")
|
| 1095 |
|
| 1096 |
+
# Парсим полный URL для получения параметров запроса
|
| 1097 |
+
query_params = dict(parse_qsl(urlparse(fullUrl).query, keep_blank_values=True))
|
| 1098 |
+
logging.debug(f"Query params for signature check: {query_params}")
|
| 1099 |
+
|
| 1100 |
+
# Проверяем подпись
|
| 1101 |
+
if not is_valid(query=query_params, secret=secret):
|
| 1102 |
+
logging.error("Invalid signature")
|
| 1103 |
+
return json.dumps({"error": "Invalid signature"}), 400
|
| 1104 |
+
|
| 1105 |
+
# Получаем данные из базы данных
|
| 1106 |
+
shop_st_data = get_order_from_db(vkid)
|
| 1107 |
+
if not shop_st_data:
|
| 1108 |
+
response = {order: 'not'}
|
| 1109 |
+
return jsonify(response), 200
|
| 1110 |
+
|
| 1111 |
+
# Ищем значение по ключу order
|
| 1112 |
+
value = shop_st_data.get(order, 'not')
|
| 1113 |
+
logging.debug(f"Value for order {order}: {value}")
|
| 1114 |
+
|
| 1115 |
+
# Возвращаем данные из столбца
|
| 1116 |
+
response = {order: value}
|
| 1117 |
return jsonify(response), 200
|
| 1118 |
|
| 1119 |
except Exception as e:
|
|
|
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
|
|
|
| 1141 |
|
| 1142 |
|
| 1143 |
|