feat: implement role-based access control for miniapp
All checks were successful
CI / lint-and-test (push) Successful in 22s

- Introduced a new roles table in the database to manage user roles ('user' and 'admin') for access control.
- Updated the user model to include a foreign key reference to the roles table, allowing for role assignment.
- Enhanced command handlers to support the `/set_role` command for admins to assign roles to users.
- Refactored access control logic to utilize role checks instead of username/phone allowlists, improving security and maintainability.
- Updated documentation to reflect changes in access control mechanisms and role management.
- Added unit tests to ensure correct functionality of role assignment and access checks.
This commit is contained in:
2026-02-20 23:58:54 +03:00
parent d02d0a1835
commit 4824450088
18 changed files with 554 additions and 83 deletions

View File

@@ -15,6 +15,7 @@ def register_handlers(app: Application) -> None:
app.add_handler(commands.help_handler)
app.add_handler(commands.set_phone_handler)
app.add_handler(commands.calendar_link_handler)
app.add_handler(commands.set_role_handler)
app.add_handler(import_duty_schedule.import_duty_schedule_handler)
app.add_handler(import_duty_schedule.handover_time_handler)
app.add_handler(import_duty_schedule.duty_schedule_document_handler)

View File

@@ -6,11 +6,18 @@ import duty_teller.config as config
from telegram import Update
from telegram.ext import CommandHandler, ContextTypes
from duty_teller.db.models import User
from duty_teller.db.session import session_scope
from duty_teller.db.repository import (
get_or_create_user,
get_user_by_telegram_id,
get_user_by_username,
set_user_phone,
create_calendar_token,
can_access_miniapp_for_telegram_user,
set_user_role,
ROLE_USER,
ROLE_ADMIN,
)
from duty_teller.handlers.common import is_admin_async
from duty_teller.i18n import get_lang, t
@@ -98,7 +105,6 @@ async def calendar_link(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N
await update.message.reply_text(t(lang, "calendar_link.private_only"))
return
telegram_user_id = update.effective_user.id
username = (update.effective_user.username or "").strip()
full_name = build_full_name(
update.effective_user.first_name, update.effective_user.last_name
)
@@ -113,9 +119,7 @@ async def calendar_link(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
)
if not config.can_access_miniapp(
username
) and not config.can_access_miniapp_by_phone(user.phone):
if not can_access_miniapp_for_telegram_user(session, telegram_user_id):
return (None, "denied")
token = create_calendar_token(session, user.id)
base = (config.MINI_APP_BASE_URL or "").rstrip("/")
@@ -153,10 +157,78 @@ async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
]
if await is_admin_async(update.effective_user.id):
lines.append(t(lang, "help.import_schedule"))
lines.append(t(lang, "help.set_role"))
await update.message.reply_text("\n".join(lines))
async def set_role(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /set_role: set user role (admin only). Usage: /set_role @username user|admin or reply + user|admin."""
if not update.message or not update.effective_user:
return
lang = get_lang(update.effective_user)
if not await is_admin_async(update.effective_user.id):
await update.message.reply_text(t(lang, "import.admin_only"))
return
args = (context.args or [])[:2]
# Resolve target: reply -> telegram_user_id; or first arg @username / numeric telegram_id
target_user = None
role_name = None
if update.message.reply_to_message and update.message.reply_to_message.from_user:
target_telegram_id = update.message.reply_to_message.from_user.id
role_name = (args[0] or "").strip().lower() if args else None
def do_get_reply() -> User | None:
with session_scope(config.DATABASE_URL) as session:
return get_user_by_telegram_id(session, target_telegram_id)
target_user = await asyncio.get_running_loop().run_in_executor(
None, do_get_reply
)
elif len(args) >= 2:
first = (args[0] or "").strip()
role_name = (args[1] or "").strip().lower()
if first.lstrip("@").isdigit():
target_telegram_id = int(first.lstrip("@"))
def do_get_by_tid() -> User | None:
with session_scope(config.DATABASE_URL) as session:
return get_user_by_telegram_id(session, target_telegram_id)
target_user = await asyncio.get_running_loop().run_in_executor(
None, do_get_by_tid
)
else:
def do_get_by_username() -> User | None:
with session_scope(config.DATABASE_URL) as session:
return get_user_by_username(session, first)
target_user = await asyncio.get_running_loop().run_in_executor(
None, do_get_by_username
)
if not role_name or role_name not in (ROLE_USER, ROLE_ADMIN):
await update.message.reply_text(t(lang, "set_role.usage"))
return
if not target_user:
await update.message.reply_text(t(lang, "set_role.user_not_found"))
return
def do_set_role() -> bool:
with session_scope(config.DATABASE_URL) as session:
updated = set_user_role(session, target_user.id, role_name)
return updated is not None
ok = await asyncio.get_running_loop().run_in_executor(None, do_set_role)
if ok:
await update.message.reply_text(
t(lang, "set_role.done", name=target_user.full_name, role=role_name)
)
else:
await update.message.reply_text(t(lang, "set_role.error"))
start_handler = CommandHandler("start", start)
help_handler = CommandHandler("help", help_cmd)
set_phone_handler = CommandHandler("set_phone", set_phone)
calendar_link_handler = CommandHandler("calendar_link", calendar_link)
set_role_handler = CommandHandler("set_role", set_role)