openbot-id 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openbot_id-1.0.0/LICENSE +21 -0
- openbot_id-1.0.0/PKG-INFO +84 -0
- openbot_id-1.0.0/README.md +70 -0
- openbot_id-1.0.0/pyproject.toml +22 -0
- openbot_id-1.0.0/setup.cfg +4 -0
- openbot_id-1.0.0/src/openbot_id/__init__.py +5 -0
- openbot_id-1.0.0/src/openbot_id/client.py +122 -0
- openbot_id-1.0.0/src/openbot_id.egg-info/PKG-INFO +84 -0
- openbot_id-1.0.0/src/openbot_id.egg-info/SOURCES.txt +10 -0
- openbot_id-1.0.0/src/openbot_id.egg-info/dependency_links.txt +1 -0
- openbot_id-1.0.0/src/openbot_id.egg-info/top_level.txt +1 -0
- openbot_id-1.0.0/tests/test_client.py +73 -0
openbot_id-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kafnik
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: openbot-id
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the Openbot ID authorization API
|
|
5
|
+
Author: Kafnik
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: telegram,authorization,fastapi,telebot
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# Openbot ID — Python-библиотека
|
|
16
|
+
|
|
17
|
+
Релиз `1.0.0`. Библиотека проверяет права пользователей Telegram через защищённый Openbot ID API. База пользователей хранится только на сервере.
|
|
18
|
+
|
|
19
|
+
Лицензия: MIT. Автор: Kafnik.
|
|
20
|
+
|
|
21
|
+
## Установка из исходной папки
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -m pip install .
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Используй виртуальное окружение (`python3 -m venv venv`).
|
|
28
|
+
|
|
29
|
+
## С pyTelegramBotAPI
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import os
|
|
33
|
+
import telebot
|
|
34
|
+
from openbot_id import OpenbotID
|
|
35
|
+
|
|
36
|
+
bot = telebot.TeleBot(os.environ["TELEGRAM_BOT_TOKEN"])
|
|
37
|
+
openbot = OpenbotID(api_key=os.environ["OPENBOT_API_KEY"], bot=bot)
|
|
38
|
+
|
|
39
|
+
@bot.message_handler(commands=["test"])
|
|
40
|
+
@openbot.check_level("tester", level=2)
|
|
41
|
+
def test(message):
|
|
42
|
+
bot.reply_to(message, "✅ Доступ разрешён")
|
|
43
|
+
|
|
44
|
+
@bot.message_handler(commands=["panel"])
|
|
45
|
+
@openbot.require_access()
|
|
46
|
+
def panel(message):
|
|
47
|
+
bot.reply_to(message, "Панель доступна")
|
|
48
|
+
|
|
49
|
+
bot.infinity_polling()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Декоратор `@bot.message_handler` должен стоять выше `@openbot.check_level` и `@openbot.require_access`.
|
|
53
|
+
|
|
54
|
+
## Другие функции
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
openbot.get_user(123456789) # словарь с user_id, exists, status, level
|
|
58
|
+
openbot.get_status(123456789) # статус
|
|
59
|
+
openbot.get_level(123456789) # числовой уровень
|
|
60
|
+
openbot.has_level(123456789, "tester", 2) # bool
|
|
61
|
+
openbot.check_access(123456789) # bool
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
При отсутствии доступа команда не выполняется. Если API недоступен, проверка также не пропускает команду. При переданном `bot=bot` библиотека отвечает пользователю сообщением.
|
|
65
|
+
|
|
66
|
+
Сервер по умолчанию: `https://server.tail116c85.ts.net`. При смене сервера можно передать `api_url="https://..."`.
|
|
67
|
+
|
|
68
|
+
## Безопасность
|
|
69
|
+
|
|
70
|
+
- Выдавай разработчикам только их собственные ключи `ob_live_...`.
|
|
71
|
+
- Не публикуй главный секрет сервера, токены ботов или SQLite-базу.
|
|
72
|
+
- Для реального бота храни секреты в переменных окружения.
|
|
73
|
+
- Библиотека требует HTTPS.
|
|
74
|
+
- При отключении домашнего интернета API временно недоступен.
|
|
75
|
+
|
|
76
|
+
## Совпадение имён
|
|
77
|
+
|
|
78
|
+
На Linux-сервере есть локальный `openbot_id.py`, который управляет SQLite. Не устанавливай клиентский пакет в то же Python-окружение, пока серверный модуль не переименован или не вынесен в отдельный пакет.
|
|
79
|
+
|
|
80
|
+
## Тесты
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
python -m unittest discover -s tests -v
|
|
84
|
+
```
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Openbot ID — Python-библиотека
|
|
2
|
+
|
|
3
|
+
Релиз `1.0.0`. Библиотека проверяет права пользователей Telegram через защищённый Openbot ID API. База пользователей хранится только на сервере.
|
|
4
|
+
|
|
5
|
+
Лицензия: MIT. Автор: Kafnik.
|
|
6
|
+
|
|
7
|
+
## Установка из исходной папки
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
python -m pip install .
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Используй виртуальное окружение (`python3 -m venv venv`).
|
|
14
|
+
|
|
15
|
+
## С pyTelegramBotAPI
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import os
|
|
19
|
+
import telebot
|
|
20
|
+
from openbot_id import OpenbotID
|
|
21
|
+
|
|
22
|
+
bot = telebot.TeleBot(os.environ["TELEGRAM_BOT_TOKEN"])
|
|
23
|
+
openbot = OpenbotID(api_key=os.environ["OPENBOT_API_KEY"], bot=bot)
|
|
24
|
+
|
|
25
|
+
@bot.message_handler(commands=["test"])
|
|
26
|
+
@openbot.check_level("tester", level=2)
|
|
27
|
+
def test(message):
|
|
28
|
+
bot.reply_to(message, "✅ Доступ разрешён")
|
|
29
|
+
|
|
30
|
+
@bot.message_handler(commands=["panel"])
|
|
31
|
+
@openbot.require_access()
|
|
32
|
+
def panel(message):
|
|
33
|
+
bot.reply_to(message, "Панель доступна")
|
|
34
|
+
|
|
35
|
+
bot.infinity_polling()
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Декоратор `@bot.message_handler` должен стоять выше `@openbot.check_level` и `@openbot.require_access`.
|
|
39
|
+
|
|
40
|
+
## Другие функции
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
openbot.get_user(123456789) # словарь с user_id, exists, status, level
|
|
44
|
+
openbot.get_status(123456789) # статус
|
|
45
|
+
openbot.get_level(123456789) # числовой уровень
|
|
46
|
+
openbot.has_level(123456789, "tester", 2) # bool
|
|
47
|
+
openbot.check_access(123456789) # bool
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
При отсутствии доступа команда не выполняется. Если API недоступен, проверка также не пропускает команду. При переданном `bot=bot` библиотека отвечает пользователю сообщением.
|
|
51
|
+
|
|
52
|
+
Сервер по умолчанию: `https://server.tail116c85.ts.net`. При смене сервера можно передать `api_url="https://..."`.
|
|
53
|
+
|
|
54
|
+
## Безопасность
|
|
55
|
+
|
|
56
|
+
- Выдавай разработчикам только их собственные ключи `ob_live_...`.
|
|
57
|
+
- Не публикуй главный секрет сервера, токены ботов или SQLite-базу.
|
|
58
|
+
- Для реального бота храни секреты в переменных окружения.
|
|
59
|
+
- Библиотека требует HTTPS.
|
|
60
|
+
- При отключении домашнего интернета API временно недоступен.
|
|
61
|
+
|
|
62
|
+
## Совпадение имён
|
|
63
|
+
|
|
64
|
+
На Linux-сервере есть локальный `openbot_id.py`, который управляет SQLite. Не устанавливай клиентский пакет в то же Python-окружение, пока серверный модуль не переименован или не вынесен в отдельный пакет.
|
|
65
|
+
|
|
66
|
+
## Тесты
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
python -m unittest discover -s tests -v
|
|
70
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "openbot-id"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Python client for the Openbot ID authorization API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
authors = [{name = "Kafnik"}]
|
|
13
|
+
license = "MIT"
|
|
14
|
+
license-files = ["LICENSE"]
|
|
15
|
+
keywords = ["telegram", "authorization", "fastapi", "telebot"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""HTTPS-only client for Openbot ID API."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from urllib.error import HTTPError, URLError
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
from urllib.request import Request, urlopen
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
DEFAULT_API_URL = "https://server.tail116c85.ts.net"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class APIError(Exception):
|
|
15
|
+
"""The API could not complete the verification."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AccessDenied(Exception):
|
|
19
|
+
"""The checked user does not have permission."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class OpenbotID:
|
|
23
|
+
def __init__(self, api_key=None, *, api_url=DEFAULT_API_URL, timeout=5, bot=None):
|
|
24
|
+
self.api_key = api_key or os.getenv("OPENBOT_API_KEY")
|
|
25
|
+
if not self.api_key:
|
|
26
|
+
raise ValueError("An API key is required")
|
|
27
|
+
self.api_url = api_url.rstrip("/")
|
|
28
|
+
if not self.api_url.startswith("https://"):
|
|
29
|
+
raise ValueError("API URL must use HTTPS")
|
|
30
|
+
if timeout <= 0:
|
|
31
|
+
raise ValueError("timeout must be positive")
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
self.bot = bot
|
|
34
|
+
|
|
35
|
+
def _get(self, path, params=None):
|
|
36
|
+
url = self.api_url + path
|
|
37
|
+
if params:
|
|
38
|
+
url += "?" + urlencode(params)
|
|
39
|
+
request = Request(url, headers={"X-API-Key": self.api_key, "Accept": "application/json"})
|
|
40
|
+
try:
|
|
41
|
+
with urlopen(request, timeout=self.timeout) as response:
|
|
42
|
+
result = json.load(response)
|
|
43
|
+
except HTTPError as exc:
|
|
44
|
+
raise APIError(f"API returned HTTP {exc.code}") from exc
|
|
45
|
+
except (URLError, TimeoutError, OSError, ValueError) as exc:
|
|
46
|
+
raise APIError("Openbot ID API is unavailable or returned invalid JSON") from exc
|
|
47
|
+
if not isinstance(result, dict):
|
|
48
|
+
raise APIError("Unexpected API response")
|
|
49
|
+
return result
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def _valid_user_id(user_id):
|
|
53
|
+
if type(user_id) is not int or user_id <= 0:
|
|
54
|
+
raise ValueError("user_id must be a positive integer")
|
|
55
|
+
return user_id
|
|
56
|
+
|
|
57
|
+
def get_user(self, user_id):
|
|
58
|
+
return self._get(f"/api/user/{self._valid_user_id(user_id)}")
|
|
59
|
+
|
|
60
|
+
def get_status(self, user_id):
|
|
61
|
+
return self.get_user(user_id)["status"]
|
|
62
|
+
|
|
63
|
+
def get_level(self, user_id):
|
|
64
|
+
return self.get_user(user_id)["level"]
|
|
65
|
+
|
|
66
|
+
def check_access(self, user_id):
|
|
67
|
+
result = self._get(f"/api/check_access/{self._valid_user_id(user_id)}")
|
|
68
|
+
if type(result.get("allowed")) is not bool:
|
|
69
|
+
raise APIError("API response lacks an allowed flag")
|
|
70
|
+
return result["allowed"]
|
|
71
|
+
|
|
72
|
+
def has_level(self, user_id, status, level=1):
|
|
73
|
+
if not isinstance(status, str) or not status.strip():
|
|
74
|
+
raise ValueError("status must be a non-empty string")
|
|
75
|
+
if type(level) is not int or level < 1:
|
|
76
|
+
raise ValueError("level must be a positive integer")
|
|
77
|
+
result = self._get(
|
|
78
|
+
f"/api/check_level/{self._valid_user_id(user_id)}",
|
|
79
|
+
{"status": status, "level": level},
|
|
80
|
+
)
|
|
81
|
+
if type(result.get("allowed")) is not bool:
|
|
82
|
+
raise APIError("API response lacks an allowed flag")
|
|
83
|
+
return result["allowed"]
|
|
84
|
+
|
|
85
|
+
def check_level(self, status, level=1, *, on_denied=None, on_error=None):
|
|
86
|
+
"""Decorator for handlers whose first argument has .from_user.id.
|
|
87
|
+
|
|
88
|
+
Rejection is fail-closed: the wrapped handler never executes without
|
|
89
|
+
a successful permission check. Provide a bot at construction time or
|
|
90
|
+
callbacks to notify users of denial and service outages.
|
|
91
|
+
"""
|
|
92
|
+
return self._decorate_permission(
|
|
93
|
+
lambda user_id: self.has_level(user_id, status, level),
|
|
94
|
+
on_denied=on_denied, on_error=on_error,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def require_access(self, *, on_denied=None, on_error=None):
|
|
98
|
+
"""Decorator requiring the server's general access policy."""
|
|
99
|
+
return self._decorate_permission(self.check_access, on_denied=on_denied, on_error=on_error)
|
|
100
|
+
|
|
101
|
+
def _decorate_permission(self, verify, *, on_denied, on_error):
|
|
102
|
+
def decorate(handler):
|
|
103
|
+
@functools.wraps(handler)
|
|
104
|
+
def wrapped(message, *args, **kwargs):
|
|
105
|
+
try:
|
|
106
|
+
user_id = message.from_user.id
|
|
107
|
+
allowed = verify(user_id)
|
|
108
|
+
except APIError as exc:
|
|
109
|
+
if on_error:
|
|
110
|
+
return on_error(message, exc)
|
|
111
|
+
if self.bot:
|
|
112
|
+
return self.bot.reply_to(message, "⚠️ Openbot ID недоступен. Попробуйте позже.")
|
|
113
|
+
raise
|
|
114
|
+
if not allowed:
|
|
115
|
+
if on_denied:
|
|
116
|
+
return on_denied(message)
|
|
117
|
+
if self.bot:
|
|
118
|
+
return self.bot.reply_to(message, "⛔ Недостаточно прав для этой команды.")
|
|
119
|
+
raise AccessDenied("User is not permitted")
|
|
120
|
+
return handler(message, *args, **kwargs)
|
|
121
|
+
return wrapped
|
|
122
|
+
return decorate
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: openbot-id
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the Openbot ID authorization API
|
|
5
|
+
Author: Kafnik
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: telegram,authorization,fastapi,telebot
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# Openbot ID — Python-библиотека
|
|
16
|
+
|
|
17
|
+
Релиз `1.0.0`. Библиотека проверяет права пользователей Telegram через защищённый Openbot ID API. База пользователей хранится только на сервере.
|
|
18
|
+
|
|
19
|
+
Лицензия: MIT. Автор: Kafnik.
|
|
20
|
+
|
|
21
|
+
## Установка из исходной папки
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -m pip install .
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Используй виртуальное окружение (`python3 -m venv venv`).
|
|
28
|
+
|
|
29
|
+
## С pyTelegramBotAPI
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import os
|
|
33
|
+
import telebot
|
|
34
|
+
from openbot_id import OpenbotID
|
|
35
|
+
|
|
36
|
+
bot = telebot.TeleBot(os.environ["TELEGRAM_BOT_TOKEN"])
|
|
37
|
+
openbot = OpenbotID(api_key=os.environ["OPENBOT_API_KEY"], bot=bot)
|
|
38
|
+
|
|
39
|
+
@bot.message_handler(commands=["test"])
|
|
40
|
+
@openbot.check_level("tester", level=2)
|
|
41
|
+
def test(message):
|
|
42
|
+
bot.reply_to(message, "✅ Доступ разрешён")
|
|
43
|
+
|
|
44
|
+
@bot.message_handler(commands=["panel"])
|
|
45
|
+
@openbot.require_access()
|
|
46
|
+
def panel(message):
|
|
47
|
+
bot.reply_to(message, "Панель доступна")
|
|
48
|
+
|
|
49
|
+
bot.infinity_polling()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Декоратор `@bot.message_handler` должен стоять выше `@openbot.check_level` и `@openbot.require_access`.
|
|
53
|
+
|
|
54
|
+
## Другие функции
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
openbot.get_user(123456789) # словарь с user_id, exists, status, level
|
|
58
|
+
openbot.get_status(123456789) # статус
|
|
59
|
+
openbot.get_level(123456789) # числовой уровень
|
|
60
|
+
openbot.has_level(123456789, "tester", 2) # bool
|
|
61
|
+
openbot.check_access(123456789) # bool
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
При отсутствии доступа команда не выполняется. Если API недоступен, проверка также не пропускает команду. При переданном `bot=bot` библиотека отвечает пользователю сообщением.
|
|
65
|
+
|
|
66
|
+
Сервер по умолчанию: `https://server.tail116c85.ts.net`. При смене сервера можно передать `api_url="https://..."`.
|
|
67
|
+
|
|
68
|
+
## Безопасность
|
|
69
|
+
|
|
70
|
+
- Выдавай разработчикам только их собственные ключи `ob_live_...`.
|
|
71
|
+
- Не публикуй главный секрет сервера, токены ботов или SQLite-базу.
|
|
72
|
+
- Для реального бота храни секреты в переменных окружения.
|
|
73
|
+
- Библиотека требует HTTPS.
|
|
74
|
+
- При отключении домашнего интернета API временно недоступен.
|
|
75
|
+
|
|
76
|
+
## Совпадение имён
|
|
77
|
+
|
|
78
|
+
На Linux-сервере есть локальный `openbot_id.py`, который управляет SQLite. Не устанавливай клиентский пакет в то же Python-окружение, пока серверный модуль не переименован или не вынесен в отдельный пакет.
|
|
79
|
+
|
|
80
|
+
## Тесты
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
python -m unittest discover -s tests -v
|
|
84
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/openbot_id/__init__.py
|
|
5
|
+
src/openbot_id/client.py
|
|
6
|
+
src/openbot_id.egg-info/PKG-INFO
|
|
7
|
+
src/openbot_id.egg-info/SOURCES.txt
|
|
8
|
+
src/openbot_id.egg-info/dependency_links.txt
|
|
9
|
+
src/openbot_id.egg-info/top_level.txt
|
|
10
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
openbot_id
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import unittest
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
from unittest.mock import patch
|
|
6
|
+
|
|
7
|
+
from openbot_id import AccessDenied, APIError, OpenbotID
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Response(io.BytesIO):
|
|
11
|
+
def __enter__(self):
|
|
12
|
+
return self
|
|
13
|
+
|
|
14
|
+
def __exit__(self, *args):
|
|
15
|
+
self.close()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ClientTests(unittest.TestCase):
|
|
19
|
+
def setUp(self):
|
|
20
|
+
self.client = OpenbotID(api_key="test-only-token")
|
|
21
|
+
|
|
22
|
+
@patch("openbot_id.client.urlopen")
|
|
23
|
+
def test_check_uses_auth_header_and_query(self, mock_urlopen):
|
|
24
|
+
mock_urlopen.return_value = Response(json.dumps({"allowed": True}).encode())
|
|
25
|
+
self.assertTrue(self.client.has_level(123, "tester", 2))
|
|
26
|
+
request = mock_urlopen.call_args.args[0]
|
|
27
|
+
self.assertEqual(request.get_header("X-api-key"), "test-only-token")
|
|
28
|
+
self.assertIn("status=tester&level=2", request.full_url)
|
|
29
|
+
|
|
30
|
+
@patch("openbot_id.client.urlopen")
|
|
31
|
+
def test_denied_never_executes_handler(self, mock_urlopen):
|
|
32
|
+
mock_urlopen.return_value = Response(b'{"allowed": false}')
|
|
33
|
+
executed = []
|
|
34
|
+
|
|
35
|
+
@self.client.check_level("tester", 2)
|
|
36
|
+
def handler(message):
|
|
37
|
+
executed.append(True)
|
|
38
|
+
|
|
39
|
+
with self.assertRaises(AccessDenied):
|
|
40
|
+
handler(SimpleNamespace(from_user=SimpleNamespace(id=123)))
|
|
41
|
+
self.assertEqual(executed, [])
|
|
42
|
+
|
|
43
|
+
@patch("openbot_id.client.urlopen", side_effect=OSError("offline"))
|
|
44
|
+
def test_offline_never_executes_handler(self, mock_urlopen):
|
|
45
|
+
executed = []
|
|
46
|
+
|
|
47
|
+
@self.client.check_level("tester", 2)
|
|
48
|
+
def handler(message):
|
|
49
|
+
executed.append(True)
|
|
50
|
+
|
|
51
|
+
with self.assertRaises(APIError):
|
|
52
|
+
handler(SimpleNamespace(from_user=SimpleNamespace(id=123)))
|
|
53
|
+
self.assertEqual(executed, [])
|
|
54
|
+
|
|
55
|
+
def test_http_required(self):
|
|
56
|
+
with self.assertRaises(ValueError):
|
|
57
|
+
OpenbotID(api_key="token", api_url="http://localhost:8000")
|
|
58
|
+
|
|
59
|
+
@patch("openbot_id.client.urlopen")
|
|
60
|
+
def test_general_access_decorator(self, mock_urlopen):
|
|
61
|
+
mock_urlopen.return_value = Response(b'{"allowed": true}')
|
|
62
|
+
executed = []
|
|
63
|
+
|
|
64
|
+
@self.client.require_access()
|
|
65
|
+
def handler(message):
|
|
66
|
+
executed.append(message.from_user.id)
|
|
67
|
+
|
|
68
|
+
handler(SimpleNamespace(from_user=SimpleNamespace(id=321)))
|
|
69
|
+
self.assertEqual(executed, [321])
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
unittest.main()
|