diff --git a/.coverage b/.coverage index e697fe7..1ff4a45 100644 Binary files a/.coverage and b/.coverage differ diff --git a/.env.example b/.env.example index d692faf..cdff469 100644 --- a/.env.example +++ b/.env.example @@ -3,12 +3,13 @@ DATABASE_URL=sqlite:///data/duty_teller.db MINI_APP_BASE_URL= HTTP_PORT=8080 -# Miniapp access: comma-separated Telegram usernames (no @). Empty = no one allowed. -ALLOWED_USERNAMES=username1,username2 +# Access: roles are assigned in the DB by an admin via /set_role. When a user has no role in DB, +# ADMIN_USERNAMES and ADMIN_PHONES act as fallback for admin only. ALLOWED_* are not used for access. +ALLOWED_USERNAMES= ADMIN_USERNAMES=admin1,admin2 -# Optional: allow by phone (user sets phone via /set_phone in bot). Comma-separated; normalized to digits for comparison. -# ALLOWED_PHONES=79001234567,79007654321 +# Optional: admin fallback by phone (user sets phone via /set_phone). Comma-separated; digits only for comparison. +# ALLOWED_PHONES= # ADMIN_PHONES=79001111111 # Dev only: set to 1 to allow calendar without Telegram initData (insecure; do not use in production). diff --git a/README.md b/README.md index ab7c4b1..4c86862 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ A minimal Telegram bot boilerplate using [python-telegram-bot](https://github.co Edit `.env` and set `BOT_TOKEN` to the token from BotFather. 5. **Miniapp access (calendar)** - Set `ALLOWED_USERNAMES` (and optionally `ADMIN_USERNAMES`) to allow access to the calendar miniapp; if both are empty, no one can open it. Users can also be allowed by phone via `ALLOWED_PHONES` / `ADMIN_PHONES` after setting a phone with `/set_phone`. + Access is controlled by **roles in the DB** (assigned by an admin with `/set_role @username user|admin`). Set `ADMIN_USERNAMES` (and optionally `ADMIN_PHONES`) so that at least one admin can use the bot and assign roles; these also act as a fallback for admin when a user has no role in the DB. See [docs/configuration.md](docs/configuration.md). **Mini App URL:** When configuring the bot's menu button or Web App URL (e.g. in @BotFather or via `setChatMenuButton`), use the URL **with a trailing slash**, e.g. `https://your-domain.com/app/`. A redirect from `/app` to `/app/` can cause the browser to drop the fragment that Telegram sends, which breaks authorization. **How to open:** Users must open the calendar **via the bot's menu button** (⋮ → "Calendar" or the configured label) or a **Web App inline button**. If they use "Open in browser" or a direct link, Telegram may not send user data (`tgWebAppData`), and access will be denied. **BOT_TOKEN:** The server that serves `/api/duties` (e.g. your production host) must have in `.env` the **same** bot token as the bot from which users open the Mini App. If the token differs (e.g. test vs production bot), validation returns "hash_mismatch" and access is denied. @@ -63,7 +63,8 @@ The bot runs in polling mode. Send `/start` or `/help` to your bot in Telegram t - **`/start`** — Greeting and user registration in the database. - **`/help`** — Help on available commands. - **`/set_phone [number]`** — Set or clear phone number (private chat only); used for access via `ALLOWED_PHONES` / `ADMIN_PHONES`. -- **`/import_duty_schedule`** — Import duty schedule (only for `ADMIN_USERNAMES` / `ADMIN_PHONES`); see **Duty schedule import** below for the two-step flow. +- **`/import_duty_schedule`** — Import duty schedule (admin only); see **Duty schedule import** below for the two-step flow. +- **`/set_role @username user|admin`** — Set a user’s role (admin only). Alternatively, reply to a message and send `/set_role user|admin`. - **`/pin_duty`** — Pin the current duty message in a group (reply to the bot’s duty message); time/timezone for the pinned message come from `DUTY_DISPLAY_TZ`. ## Run with Docker diff --git a/alembic/versions/007_roles_table_and_user_role_id.py b/alembic/versions/007_roles_table_and_user_role_id.py new file mode 100644 index 0000000..070b9a3 --- /dev/null +++ b/alembic/versions/007_roles_table_and_user_role_id.py @@ -0,0 +1,55 @@ +"""Add roles table and users.role_id (variant B: roles in DB). + +Revision ID: 007 +Revises: 006 +Create Date: 2025-02-20 + +Roles: 'user', 'admin'. users.role_id is nullable; no role = no access except +env fallback for admins (ADMIN_USERNAMES/ADMIN_PHONES). +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + +revision: str = "007" +down_revision: Union[str, None] = "006" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + conn = op.get_bind() + inspector = sa.inspect(conn) + tables = inspector.get_table_names() + + if "roles" not in tables: + op.create_table( + "roles", + sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), + sa.Column("name", sa.Text(), nullable=False, unique=True), + ) + # Ensure role rows exist (table may exist from create_all or partial run) + result = conn.execute(sa.text("SELECT COUNT(*) FROM roles")).scalar() + if result == 0: + op.execute(sa.text("INSERT INTO roles (name) VALUES ('user'), ('admin')")) + + # SQLite does not support ALTER TABLE ADD COLUMN with FK; add column without FK. + # The ORM model keeps ForeignKey for other backends and documentation. + users_columns = [c["name"] for c in inspector.get_columns("users")] + if "role_id" not in users_columns: + op.add_column( + "users", + sa.Column("role_id", sa.Integer(), nullable=True), + ) + + +def downgrade() -> None: + conn = op.get_bind() + inspector = sa.inspect(conn) + users_columns = [c["name"] for c in inspector.get_columns("users")] + if "role_id" in users_columns: + op.drop_column("users", "role_id") + if "roles" in inspector.get_table_names(): + op.drop_table("roles") diff --git a/docs/configuration.md b/docs/configuration.md index 4fdcfd1..489cfbd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -8,10 +8,10 @@ All configuration is read from the environment (e.g. `.env` via python-dotenv). | **DATABASE_URL** | string (SQLAlchemy URL) | `sqlite:///data/duty_teller.db` | Database connection URL. Example: `sqlite:///data/duty_teller.db`. | | **MINI_APP_BASE_URL** | string (URL, no trailing slash) | *(empty)* | Base URL of the miniapp (for documentation and CORS). Trailing slash is stripped. Example: `https://your-domain.com/app`. | | **HTTP_PORT** | integer | `8080` | Port for the HTTP server (FastAPI + static webapp). | -| **ALLOWED_USERNAMES** | comma-separated list | *(empty)* | Telegram usernames allowed to open the calendar miniapp (without `@`; case-insensitive). If both this and `ADMIN_USERNAMES` are empty, no one can open the calendar. Example: `alice,bob`. | -| **ADMIN_USERNAMES** | comma-separated list | *(empty)* | Telegram usernames with admin role (access to miniapp + `/import_duty_schedule` and future admin features). Example: `admin1,admin2`. | -| **ALLOWED_PHONES** | comma-separated list | *(empty)* | Phone numbers allowed to access the miniapp (user sets via `/set_phone`). Comparison uses digits only (spaces, `+`, parentheses, dashes ignored). Example: `+7 999 123-45-67,89001234567`. | -| **ADMIN_PHONES** | comma-separated list | *(empty)* | Phone numbers with admin role; same format as `ALLOWED_PHONES`. | +| **ALLOWED_USERNAMES** | comma-separated list | *(empty)* | **Not used for access.** Kept for reference only. Access to the miniapp is controlled by **roles in the DB** (assigned by an admin via `/set_role`). | +| **ADMIN_USERNAMES** | comma-separated list | *(empty)* | Telegram usernames treated as **admin fallback** when the user has **no role in the DB**. If a user has a role in the DB, only that role applies. Example: `admin1,admin2`. | +| **ALLOWED_PHONES** | comma-separated list | *(empty)* | **Not used for access.** Kept for reference only. | +| **ADMIN_PHONES** | comma-separated list | *(empty)* | Phones treated as **admin fallback** when the user has **no role in the DB** (user sets phone via `/set_phone`). Comparison uses digits only. Example: `+7 999 123-45-67`. | | **MINI_APP_SKIP_AUTH** | `1`, `true`, or `yes` | *(unset)* | If set, `/api/duties` is allowed without Telegram initData (dev only; insecure). | | **INIT_DATA_MAX_AGE_SECONDS** | integer | `0` | Reject Telegram initData older than this many seconds. `0` = disabled. Example: `86400` for 24 hours. | | **CORS_ORIGINS** | comma-separated list | `*` | Allowed origins for CORS. Leave unset or set to `*` for allow-all. Example: `https://your-domain.com`. | @@ -19,11 +19,15 @@ All configuration is read from the environment (e.g. `.env` via python-dotenv). | **DUTY_DISPLAY_TZ** | string (timezone name) | `Europe/Moscow` | Timezone for the pinned duty message in groups. Example: `Europe/Moscow`, `UTC`. | | **DEFAULT_LANGUAGE** | `en` or `ru` (normalized) | `en` | Default UI language when the user's Telegram language is unknown. Values starting with `ru` are normalized to `ru`, otherwise `en`. | +## Roles and access + +Access to the calendar miniapp and admin actions is determined by **roles stored in the database** (table `roles`, link `users.role_id`). Roles: `user` (miniapp access) and `admin` (miniapp + `/import_duty_schedule`, `/set_role`). An admin assigns roles with **`/set_role @username user|admin`** (or by replying to a message with `/set_role user|admin`). If a user has **no role in the DB**, they are treated as admin only if they are listed in **ADMIN_USERNAMES** or **ADMIN_PHONES** (env fallback). `ALLOWED_USERNAMES` and `ALLOWED_PHONES` are not used for access. + ## Quick setup 1. Copy `.env.example` to `.env`. 2. Set `BOT_TOKEN` to the token from BotFather. -3. For miniapp access, set `ALLOWED_USERNAMES` and/or `ADMIN_USERNAMES` (and optionally `ALLOWED_PHONES` / `ADMIN_PHONES`). +3. Set `ADMIN_USERNAMES` (and optionally `ADMIN_PHONES`) so that at least one admin can use the bot and assign roles via `/set_role`. For Mini App URL and production deployment notes (reverse proxy, initData), see the [README](../README.md) Setup and Docker sections. diff --git a/duty_teller.egg-info/PKG-INFO b/duty_teller.egg-info/PKG-INFO index 017bc7f..bacef5b 100644 --- a/duty_teller.egg-info/PKG-INFO +++ b/duty_teller.egg-info/PKG-INFO @@ -60,7 +60,7 @@ A minimal Telegram bot boilerplate using [python-telegram-bot](https://github.co Edit `.env` and set `BOT_TOKEN` to the token from BotFather. 5. **Miniapp access (calendar)** - Set `ALLOWED_USERNAMES` (and optionally `ADMIN_USERNAMES`) to allow access to the calendar miniapp; if both are empty, no one can open it. Users can also be allowed by phone via `ALLOWED_PHONES` / `ADMIN_PHONES` after setting a phone with `/set_phone`. + Access is controlled by **roles in the DB** (assigned by an admin with `/set_role @username user|admin`). Set `ADMIN_USERNAMES` (and optionally `ADMIN_PHONES`) so that at least one admin can use the bot and assign roles; these also act as a fallback for admin when a user has no role in the DB. See [docs/configuration.md](docs/configuration.md). **Mini App URL:** When configuring the bot's menu button or Web App URL (e.g. in @BotFather or via `setChatMenuButton`), use the URL **with a trailing slash**, e.g. `https://your-domain.com/app/`. A redirect from `/app` to `/app/` can cause the browser to drop the fragment that Telegram sends, which breaks authorization. **How to open:** Users must open the calendar **via the bot's menu button** (⋮ → "Calendar" or the configured label) or a **Web App inline button**. If they use "Open in browser" or a direct link, Telegram may not send user data (`tgWebAppData`), and access will be denied. **BOT_TOKEN:** The server that serves `/api/duties` (e.g. your production host) must have in `.env` the **same** bot token as the bot from which users open the Mini App. If the token differs (e.g. test vs production bot), validation returns "hash_mismatch" and access is denied. @@ -87,7 +87,8 @@ The bot runs in polling mode. Send `/start` or `/help` to your bot in Telegram t - **`/start`** — Greeting and user registration in the database. - **`/help`** — Help on available commands. - **`/set_phone [number]`** — Set or clear phone number (private chat only); used for access via `ALLOWED_PHONES` / `ADMIN_PHONES`. -- **`/import_duty_schedule`** — Import duty schedule (only for `ADMIN_USERNAMES` / `ADMIN_PHONES`); see **Duty schedule import** below for the two-step flow. +- **`/import_duty_schedule`** — Import duty schedule (admin only); see **Duty schedule import** below for the two-step flow. +- **`/set_role @username user|admin`** — Set a user’s role (admin only). Alternatively, reply to a message and send `/set_role user|admin`. - **`/pin_duty`** — Pin the current duty message in a group (reply to the bot’s duty message); time/timezone for the pinned message come from `DUTY_DISPLAY_TZ`. ## Run with Docker diff --git a/duty_teller.egg-info/SOURCES.txt b/duty_teller.egg-info/SOURCES.txt index 7569ec9..6ebb7ad 100644 --- a/duty_teller.egg-info/SOURCES.txt +++ b/duty_teller.egg-info/SOURCES.txt @@ -22,11 +22,13 @@ duty_teller/db/schemas.py duty_teller/db/session.py duty_teller/handlers/__init__.py duty_teller/handlers/commands.py +duty_teller/handlers/common.py duty_teller/handlers/errors.py duty_teller/handlers/group_duty_pin.py duty_teller/handlers/import_duty_schedule.py duty_teller/i18n/__init__.py duty_teller/i18n/core.py +duty_teller/i18n/lang.py duty_teller/i18n/messages.py duty_teller/importers/__init__.py duty_teller/importers/duty_schedule.py @@ -55,6 +57,7 @@ tests/test_import_service.py tests/test_package_init.py tests/test_personal_calendar_ics.py tests/test_repository_duty_range.py +tests/test_repository_roles.py tests/test_run.py tests/test_telegram_auth.py tests/test_utils.py \ No newline at end of file diff --git a/duty_teller/api/dependencies.py b/duty_teller/api/dependencies.py index 857ffcc..082d401 100644 --- a/duty_teller/api/dependencies.py +++ b/duty_teller/api/dependencies.py @@ -9,7 +9,11 @@ from sqlalchemy.orm import Session import duty_teller.config as config from duty_teller.api.telegram_auth import validate_init_data_with_reason -from duty_teller.db.repository import get_duties, get_user_by_telegram_id +from duty_teller.db.repository import ( + get_duties, + get_user_by_telegram_id, + can_access_miniapp_for_telegram_user, +) from duty_teller.db.schemas import DUTY_EVENT_TYPES, DutyWithUser from duty_teller.db.session import session_scope from duty_teller.i18n import t @@ -181,22 +185,27 @@ def get_authenticated_username( raise HTTPException( status_code=403, detail=_auth_error_detail(auth_reason, lang) ) - if username and config.can_access_miniapp(username): - return username - failed_phone: str | None = None - if telegram_user_id is not None: - user = get_user_by_telegram_id(session, telegram_user_id) - if user and user.phone and config.can_access_miniapp_by_phone(user.phone): - return username or (user.full_name or "") or f"id:{telegram_user_id}" - if user and user.phone: - failed_phone = config.normalize_phone(user.phone) - log.warning( - "username/phone not in allowlist (username=%s, telegram_id=%s, phone=%s)", - username, - telegram_user_id, - failed_phone if failed_phone else "—", - ) - raise HTTPException(status_code=403, detail=t(lang, "api.access_denied")) + if telegram_user_id is None: + log.warning("initData valid but telegram_user_id missing") + raise HTTPException(status_code=403, detail=t(lang, "api.access_denied")) + user = get_user_by_telegram_id(session, telegram_user_id) + if not user: + log.warning( + "user not in DB (username=%s, telegram_id=%s)", + username, + telegram_user_id, + ) + raise HTTPException(status_code=403, detail=t(lang, "api.access_denied")) + if not can_access_miniapp_for_telegram_user(session, telegram_user_id): + failed_phone = config.normalize_phone(user.phone) if user.phone else None + log.warning( + "access denied (username=%s, telegram_id=%s, phone=%s)", + username, + telegram_user_id, + failed_phone or "—", + ) + raise HTTPException(status_code=403, detail=t(lang, "api.access_denied")) + return username or (user.full_name or "") or f"id:{telegram_user_id}" def fetch_duties_response( diff --git a/duty_teller/db/__init__.py b/duty_teller/db/__init__.py index b7b5cae..1602fa2 100644 --- a/duty_teller/db/__init__.py +++ b/duty_teller/db/__init__.py @@ -1,6 +1,6 @@ """Database layer: SQLAlchemy models, Pydantic schemas, repository, init.""" -from duty_teller.db.models import Base, User, Duty +from duty_teller.db.models import Base, User, Duty, Role from duty_teller.db.schemas import ( UserCreate, UserInDb, @@ -28,6 +28,7 @@ __all__ = [ "Base", "User", "Duty", + "Role", "UserCreate", "UserInDb", "DutyCreate", diff --git a/duty_teller/db/models.py b/duty_teller/db/models.py index b5e7a60..f2357f3 100644 --- a/duty_teller/db/models.py +++ b/duty_teller/db/models.py @@ -10,6 +10,17 @@ class Base(DeclarativeBase): pass +class Role(Base): + """Role for access control: 'user' (miniapp access), 'admin' (admin actions).""" + + __tablename__ = "roles" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + name: Mapped[str] = mapped_column(Text, nullable=False, unique=True) + + users: Mapped[list["User"]] = relationship("User", back_populates="role") + + class User(Base): """Telegram user and display name; may have telegram_user_id=None for import-only users.""" @@ -27,7 +38,11 @@ class User(Base): name_manually_edited: Mapped[bool] = mapped_column( Boolean, nullable=False, server_default="0", default=False ) + role_id: Mapped[int | None] = mapped_column( + Integer, ForeignKey("roles.id"), nullable=True + ) + role: Mapped["Role | None"] = relationship("Role", back_populates="users") duties: Mapped[list["Duty"]] = relationship("Duty", back_populates="user") diff --git a/duty_teller/db/repository.py b/duty_teller/db/repository.py index 2e35ecd..6c9b39c 100644 --- a/duty_teller/db/repository.py +++ b/duty_teller/db/repository.py @@ -7,9 +7,19 @@ from datetime import datetime, timezone from sqlalchemy.orm import Session import duty_teller.config as config -from duty_teller.db.models import User, Duty, GroupDutyPin, CalendarSubscriptionToken +from duty_teller.db.models import ( + User, + Duty, + GroupDutyPin, + CalendarSubscriptionToken, + Role, +) from duty_teller.utils.dates import parse_utc_iso_naive, to_date_exclusive_iso +# Role names stored in DB (table roles). +ROLE_USER = "user" +ROLE_ADMIN = "admin" + def get_user_by_telegram_id(session: Session, telegram_user_id: int) -> User | None: """Find user by Telegram user ID. @@ -24,22 +34,123 @@ def get_user_by_telegram_id(session: Session, telegram_user_id: int) -> User | N return session.query(User).filter(User.telegram_user_id == telegram_user_id).first() +def get_user_by_username(session: Session, username: str) -> User | None: + """Find user by Telegram username (case-insensitive, optional @ prefix). + + Args: + session: DB session. + username: Telegram username with or without @. + + Returns: + User or None if not found. + """ + from sqlalchemy import func + + name = (username or "").strip().lstrip("@").lower() + if not name: + return None + return session.query(User).filter(func.lower(User.username) == name).first() + + +def get_user_role(session: Session, user_id: int) -> str | None: + """Return role name for user by internal user id, or None if no role. + + Args: + session: DB session. + user_id: Internal user id (users.id). + + Returns: + Role name ('user' or 'admin') or None. + """ + user = session.get(User, user_id) + if not user or not user.role: + return None + return user.role.name + + def is_admin_for_telegram_user(session: Session, telegram_user_id: int) -> bool: - """Check if the Telegram user is admin (by username or by stored phone). + """Check if the Telegram user is admin. + + If user has a role in DB, returns True only for role 'admin'. + If user has no role in DB, fallback: True if in ADMIN_USERNAMES or ADMIN_PHONES. Args: session: DB session. telegram_user_id: Telegram user id. Returns: - True if user is in ADMIN_USERNAMES or their stored phone is in ADMIN_PHONES. + True if admin (by DB role or env fallback). """ user = get_user_by_telegram_id(session, telegram_user_id) if not user: return False + if user.role is not None: + return user.role.name == ROLE_ADMIN return config.is_admin(user.username or "") or config.is_admin_by_phone(user.phone) +def can_access_miniapp_for_telegram_user( + session: Session, telegram_user_id: int +) -> bool: + """Check if Telegram user can access the calendar miniapp. + + Access if: user has role 'user' or 'admin' in DB, or (no role in DB and + env fallback: in ADMIN_USERNAMES or ADMIN_PHONES). No user in DB -> no access. + + Args: + session: DB session. + telegram_user_id: Telegram user id. + + Returns: + True if user may open the miniapp. + """ + user = get_user_by_telegram_id(session, telegram_user_id) + return can_access_miniapp_for_user(session, user) if user else False + + +def can_access_miniapp_for_user(session: Session, user: User | None) -> bool: + """Check if user (already loaded) can access the calendar miniapp. + + Access if: user has role 'user' or 'admin' in DB, or (no role in DB and + env fallback: in ADMIN_USERNAMES or ADMIN_PHONES). + + Args: + session: DB session (unused; kept for API consistency). + user: User instance or None. + + Returns: + True if user may open the miniapp. + """ + if not user: + return False + if user.role is not None: + return user.role.name in (ROLE_USER, ROLE_ADMIN) + return config.is_admin(user.username or "") or config.is_admin_by_phone(user.phone) + + +def set_user_role(session: Session, user_id: int, role_name: str) -> User | None: + """Set user role by internal user id and role name. + + Args: + session: DB session. + user_id: Internal user id (users.id). + role_name: 'user' or 'admin'. + + Returns: + Updated User or None if user or role not found. + """ + user = session.get(User, user_id) + if not user: + return None + role = session.query(Role).filter(Role.name == role_name).first() + if not role: + return None + user.role_id = role.id + session.commit() + session.refresh(user) + return user + + def get_or_create_user( session: Session, telegram_user_id: int, diff --git a/duty_teller/handlers/__init__.py b/duty_teller/handlers/__init__.py index 4cdd1d8..6f416de 100644 --- a/duty_teller/handlers/__init__.py +++ b/duty_teller/handlers/__init__.py @@ -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) diff --git a/duty_teller/handlers/commands.py b/duty_teller/handlers/commands.py index 1fb050d..9c16245 100644 --- a/duty_teller/handlers/commands.py +++ b/duty_teller/handlers/commands.py @@ -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) diff --git a/duty_teller/i18n/messages.py b/duty_teller/i18n/messages.py index 027d80b..d1ac43f 100644 --- a/duty_teller/i18n/messages.py +++ b/duty_teller/i18n/messages.py @@ -22,6 +22,11 @@ MESSAGES: dict[str, dict[str, str]] = { ), "calendar_link.error": "Could not generate link. Please try again later.", "help.import_schedule": "/import_duty_schedule — Import duty schedule (JSON)", + "help.set_role": "/set_role — Set user role (user | admin)", + "set_role.usage": "Usage: /set_role @username user|admin or reply to a message and send /set_role user|admin", + "set_role.user_not_found": "User not found.", + "set_role.done": "Role set: {name} → {role}", + "set_role.error": "Could not set role.", "errors.generic": "An error occurred. Please try again later.", "pin_duty.group_only": "The /pin_duty command works only in groups.", "pin_duty.no_message": "There is no duty message in this chat yet. Add the bot to the group — it will create one automatically.", @@ -81,6 +86,11 @@ MESSAGES: dict[str, dict[str, str]] = { "calendar_link.help_hint": "Подпишитесь на эту ссылку в Google Календаре, Календаре Apple или Outlook, чтобы видеть только свои дежурства.", "calendar_link.error": "Не удалось сформировать ссылку. Попробуйте позже.", "help.import_schedule": "/import_duty_schedule — Импорт расписания дежурств (JSON)", + "help.set_role": "/set_role — Выдать роль пользователю (user | admin)", + "set_role.usage": "Использование: /set_role @username user|admin или ответьте на сообщение и отправьте /set_role user|admin", + "set_role.user_not_found": "Пользователь не найден.", + "set_role.done": "Роль установлена: {name} → {role}", + "set_role.error": "Не удалось установить роль.", "errors.generic": "Произошла ошибка. Попробуйте позже.", "pin_duty.group_only": "Команда /pin_duty работает только в группах.", "pin_duty.no_message": "В этом чате ещё нет сообщения о дежурстве. Добавьте бота в группу — оно создастся автоматически.", diff --git a/tests/test_app.py b/tests/test_app.py index 14cc645..b433abc 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -82,14 +82,11 @@ def test_duties_403_when_init_data_invalid(mock_validate, client): @patch("duty_teller.api.dependencies.get_user_by_telegram_id") @patch("duty_teller.api.dependencies.validate_init_data_with_reason") -@patch("duty_teller.api.dependencies.config.can_access_miniapp") @patch("duty_teller.api.dependencies.config.MINI_APP_SKIP_AUTH", False) -def test_duties_403_when_username_not_allowed( - mock_can_access, mock_validate, mock_get_user, client -): +def test_duties_403_when_user_not_in_db(mock_validate, mock_get_user, client): + """User not in DB -> 403 (access only for users with role or env-admin fallback).""" mock_validate.return_value = (123, "someuser", "ok", "en") - mock_can_access.return_value = False - mock_get_user.return_value = None # no user in DB or no phone path + mock_get_user.return_value = None with patch("duty_teller.api.app.fetch_duties_response") as mock_fetch: r = client.get( "/api/duties", @@ -103,21 +100,21 @@ def test_duties_403_when_username_not_allowed( mock_fetch.assert_not_called() -@patch("duty_teller.api.dependencies.config.can_access_miniapp_by_phone") +@patch("duty_teller.api.dependencies.can_access_miniapp_for_telegram_user") @patch("duty_teller.api.dependencies.get_user_by_telegram_id") @patch("duty_teller.api.dependencies.validate_init_data_with_reason") -@patch("duty_teller.api.dependencies.config.can_access_miniapp") @patch("duty_teller.api.dependencies.config.MINI_APP_SKIP_AUTH", False) -def test_duties_403_when_no_username_and_phone_not_in_allowlist( - mock_can_access, mock_validate, mock_get_user, mock_can_access_phone, client +def test_duties_403_when_no_username_and_no_access( + mock_validate, mock_get_user, mock_can_access, client ): - """No username in initData and user's phone not in ALLOWED_PHONES -> 403.""" + """User in DB but no miniapp access (no role, not env admin) -> 403.""" from types import SimpleNamespace mock_validate.return_value = (456, None, "ok", "en") + mock_get_user.return_value = SimpleNamespace( + phone="+79001111111", full_name="User", username=None + ) mock_can_access.return_value = False - mock_get_user.return_value = SimpleNamespace(phone="+79001111111", full_name="User") - mock_can_access_phone.return_value = False with patch("duty_teller.api.app.fetch_duties_response") as mock_fetch: r = client.get( "/api/duties", @@ -128,23 +125,21 @@ def test_duties_403_when_no_username_and_phone_not_in_allowlist( mock_fetch.assert_not_called() -@patch("duty_teller.api.dependencies.config.can_access_miniapp_by_phone") +@patch("duty_teller.api.dependencies.can_access_miniapp_for_telegram_user") @patch("duty_teller.api.dependencies.get_user_by_telegram_id") @patch("duty_teller.api.dependencies.validate_init_data_with_reason") -@patch("duty_teller.api.dependencies.config.can_access_miniapp") @patch("duty_teller.api.dependencies.config.MINI_APP_SKIP_AUTH", False) -def test_duties_200_when_no_username_but_phone_in_allowlist( - mock_can_access, mock_validate, mock_get_user, mock_can_access_phone, client +def test_duties_200_when_user_has_access( + mock_validate, mock_get_user, mock_can_access, client ): - """No username in initData but user's phone in ALLOWED_PHONES -> 200.""" + """User in DB with miniapp access (role or env fallback) -> 200.""" from types import SimpleNamespace mock_validate.return_value = (789, None, "ok", "en") - mock_can_access.return_value = False mock_get_user.return_value = SimpleNamespace( - phone="+7 900 123-45-67", full_name="Иван" + phone="+7 900 123-45-67", full_name="Иван", username=None ) - mock_can_access_phone.return_value = True + mock_can_access.return_value = True with patch("duty_teller.api.app.fetch_duties_response") as mock_fetch: mock_fetch.return_value = [] r = client.get( @@ -180,10 +175,18 @@ def test_duties_200_with_valid_init_data_and_skip_auth_not_in_allowlist( mock_validate.assert_not_called() +@patch("duty_teller.api.dependencies.can_access_miniapp_for_telegram_user") +@patch("duty_teller.api.dependencies.get_user_by_telegram_id") @patch("duty_teller.api.dependencies.validate_init_data_with_reason") -@patch("duty_teller.api.dependencies.config.can_access_miniapp") -def test_duties_200_with_allowed_user(mock_can_access, mock_validate, client): +def test_duties_200_with_allowed_user( + mock_validate, mock_get_user, mock_can_access, client +): + from types import SimpleNamespace + mock_validate.return_value = (1, "alloweduser", "ok", "en") + mock_get_user.return_value = SimpleNamespace( + full_name="Иван Иванов", username="alloweduser", phone=None + ) mock_can_access.return_value = True with patch("duty_teller.api.app.fetch_duties_response") as mock_fetch: mock_fetch.return_value = [ @@ -206,11 +209,16 @@ def test_duties_200_with_allowed_user(mock_can_access, mock_validate, client): mock_fetch.assert_called_once_with(ANY, "2025-01-01", "2025-01-31") -def test_duties_e2e_auth_real_validation(client, monkeypatch): +@patch("duty_teller.api.dependencies.can_access_miniapp_for_telegram_user") +@patch("duty_teller.api.dependencies.get_user_by_telegram_id") +def test_duties_e2e_auth_real_validation( + mock_get_user, mock_can_access, client, monkeypatch +): + from types import SimpleNamespace + test_token = "123:ABC" test_username = "e2euser" monkeypatch.setattr(config, "BOT_TOKEN", test_token) - monkeypatch.setattr(config, "ALLOWED_USERNAMES", {test_username}) monkeypatch.setattr(config, "ADMIN_USERNAMES", set()) monkeypatch.setattr(config, "INIT_DATA_MAX_AGE_SECONDS", 0) init_data = make_init_data( @@ -218,6 +226,10 @@ def test_duties_e2e_auth_real_validation(client, monkeypatch): test_token, auth_date=int(time.time()), ) + mock_get_user.return_value = SimpleNamespace( + full_name="E2E User", username=test_username, phone=None + ) + mock_can_access.return_value = True with patch("duty_teller.api.app.fetch_duties_response") as mock_fetch: mock_fetch.return_value = [] r = client.get( diff --git a/tests/test_handlers_commands.py b/tests/test_handlers_commands.py index c3a8068..f5f6a9b 100644 --- a/tests/test_handlers_commands.py +++ b/tests/test_handlers_commands.py @@ -175,24 +175,26 @@ async def test_calendar_link_with_user_and_token_replies_with_url(): mock_user.id = 10 mock_user.phone = None mock_get_user.return_value = mock_user - with patch("duty_teller.handlers.commands.config") as mock_cfg: - mock_cfg.can_access_miniapp.return_value = True - mock_cfg.can_access_miniapp_by_phone.return_value = False - mock_cfg.MINI_APP_BASE_URL = "https://example.com" - with patch( - "duty_teller.handlers.commands.create_calendar_token", - return_value="abc43token", - ): + with patch( + "duty_teller.handlers.commands.can_access_miniapp_for_telegram_user", + return_value=True, + ): + with patch("duty_teller.handlers.commands.config") as mock_cfg: + mock_cfg.MINI_APP_BASE_URL = "https://example.com" with patch( - "duty_teller.handlers.commands.get_lang", return_value="en" + "duty_teller.handlers.commands.create_calendar_token", + return_value="abc43token", ): - with patch("duty_teller.handlers.commands.t") as mock_t: - mock_t.side_effect = lambda lang, key, **kw: ( - f"URL: {kw.get('url', '')}" - if "success" in key - else "Hint" - ) - await calendar_link(update, MagicMock()) + with patch( + "duty_teller.handlers.commands.get_lang", return_value="en" + ): + with patch("duty_teller.handlers.commands.t") as mock_t: + mock_t.side_effect = lambda lang, key, **kw: ( + f"URL: {kw.get('url', '')}" + if "success" in key + else "Hint" + ) + await calendar_link(update, MagicMock()) message.reply_text.assert_called_once() call_args = message.reply_text.call_args[0][0] assert "abc43token" in call_args or "example.com" in call_args @@ -216,9 +218,10 @@ async def test_calendar_link_denied_replies_access_denied(): mock_user.id = 10 mock_user.phone = None mock_get_user.return_value = mock_user - with patch("duty_teller.handlers.commands.config") as mock_cfg: - mock_cfg.can_access_miniapp.return_value = False - mock_cfg.can_access_miniapp_by_phone.return_value = False + with patch( + "duty_teller.handlers.commands.can_access_miniapp_for_telegram_user", + return_value=False, + ): with patch("duty_teller.handlers.commands.get_lang", return_value="en"): with patch("duty_teller.handlers.commands.t") as mock_t: mock_t.return_value = "Access denied" diff --git a/tests/test_handlers_init.py b/tests/test_handlers_init.py index 70bff27..72e4965 100644 --- a/tests/test_handlers_init.py +++ b/tests/test_handlers_init.py @@ -9,5 +9,5 @@ def test_register_handlers_adds_all_handlers(): """register_handlers: adds command, import, group pin handlers and error handler.""" mock_app = MagicMock() register_handlers(mock_app) - assert mock_app.add_handler.call_count >= 9 + assert mock_app.add_handler.call_count >= 10 assert mock_app.add_error_handler.call_count == 1 diff --git a/tests/test_repository_roles.py b/tests/test_repository_roles.py new file mode 100644 index 0000000..236c581 --- /dev/null +++ b/tests/test_repository_roles.py @@ -0,0 +1,172 @@ +"""Tests for role-related repository: get_user_role, set_user_role, is_admin, can_access_miniapp.""" + +from unittest.mock import patch + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from duty_teller.db.models import Base, Role +from duty_teller.db.repository import ( + ROLE_USER, + ROLE_ADMIN, + get_user_by_username, + get_user_role, + set_user_role, + is_admin_for_telegram_user, + can_access_miniapp_for_telegram_user, + can_access_miniapp_for_user, + get_or_create_user, +) + + +@pytest.fixture +def session(): + """Session with roles and users tables; roles 'user' and 'admin' inserted.""" + engine = create_engine( + "sqlite:///:memory:", connect_args={"check_same_thread": False} + ) + Base.metadata.create_all(engine) + Session = sessionmaker(bind=engine, autocommit=False, autoflush=False) + s = Session() + try: + for name in (ROLE_USER, ROLE_ADMIN): + r = Role(name=name) + s.add(r) + s.commit() + yield s + finally: + s.close() + engine.dispose() + + +@pytest.fixture +def user_no_role(session): + """User with telegram_user_id set, no role.""" + u = get_or_create_user( + session, + telegram_user_id=100, + full_name="No Role", + username="norole", + ) + return u + + +@pytest.fixture +def role_user(session): + return session.query(Role).filter(Role.name == ROLE_USER).first() + + +@pytest.fixture +def role_admin(session): + return session.query(Role).filter(Role.name == ROLE_ADMIN).first() + + +def test_get_user_role_none_when_no_role(session, user_no_role): + assert get_user_role(session, user_no_role.id) is None + + +def test_get_user_role_returns_name(session, user_no_role, role_user, role_admin): + user_no_role.role_id = role_user.id + session.commit() + assert get_user_role(session, user_no_role.id) == ROLE_USER + user_no_role.role_id = role_admin.id + session.commit() + assert get_user_role(session, user_no_role.id) == ROLE_ADMIN + + +def test_set_user_role(session, user_no_role, role_user): + updated = set_user_role(session, user_no_role.id, ROLE_USER) + assert updated is not None + assert updated.id == user_no_role.id + assert updated.role_id == role_user.id + session.refresh(user_no_role) + assert user_no_role.role.name == ROLE_USER + + +def test_set_user_role_invalid_name_returns_none(session, user_no_role): + assert set_user_role(session, user_no_role.id, "superuser") is None + assert set_user_role(session, 99999, ROLE_USER) is None + + +@patch("duty_teller.db.repository.config.is_admin") +@patch("duty_teller.db.repository.config.is_admin_by_phone") +def test_is_admin_for_telegram_user_from_db_role( + mock_admin_phone, mock_admin, session, user_no_role, role_admin, role_user +): + mock_admin.return_value = False + mock_admin_phone.return_value = False + user_no_role.role_id = role_user.id + session.commit() + assert is_admin_for_telegram_user(session, 100) is False + user_no_role.role_id = role_admin.id + session.commit() + assert is_admin_for_telegram_user(session, 100) is True + mock_admin.assert_not_called() + mock_admin_phone.assert_not_called() + + +@patch("duty_teller.db.repository.config.is_admin") +@patch("duty_teller.db.repository.config.is_admin_by_phone") +def test_is_admin_for_telegram_user_fallback_when_no_role( + mock_admin_phone, mock_admin, session, user_no_role +): + mock_admin.return_value = True + mock_admin_phone.return_value = False + assert is_admin_for_telegram_user(session, 100) is True + mock_admin.assert_called_once() + mock_admin.return_value = False + mock_admin_phone.return_value = True + assert is_admin_for_telegram_user(session, 100) is True + + +@patch("duty_teller.db.repository.config.is_admin") +@patch("duty_teller.db.repository.config.is_admin_by_phone") +def test_is_admin_for_telegram_user_false_when_no_user( + mock_admin_phone, mock_admin, session +): + mock_admin.return_value = False + mock_admin_phone.return_value = False + assert is_admin_for_telegram_user(session, 99999) is False + + +def test_can_access_miniapp_for_telegram_user_no_user(session): + assert can_access_miniapp_for_telegram_user(session, 99999) is False + + +def test_can_access_miniapp_for_telegram_user_with_role( + session, user_no_role, role_user, role_admin +): + user_no_role.role_id = role_user.id + session.commit() + assert can_access_miniapp_for_telegram_user(session, 100) is True + user_no_role.role_id = role_admin.id + session.commit() + assert can_access_miniapp_for_telegram_user(session, 100) is True + + +@patch("duty_teller.db.repository.config.is_admin") +@patch("duty_teller.db.repository.config.is_admin_by_phone") +def test_can_access_miniapp_for_telegram_user_fallback_when_no_role( + mock_admin_phone, mock_admin, session, user_no_role +): + mock_admin.return_value = False + mock_admin_phone.return_value = False + assert can_access_miniapp_for_telegram_user(session, 100) is False + mock_admin.return_value = True + assert can_access_miniapp_for_telegram_user(session, 100) is True + + +def test_can_access_miniapp_for_user_none(session): + assert can_access_miniapp_for_user(session, None) is False + + +def test_get_user_by_username(session, user_no_role): + u = get_user_by_username(session, "norole") + assert u is not None and u.id == user_no_role.id + u2 = get_user_by_username(session, "@norole") + assert u2 is not None and u2.id == user_no_role.id + u3 = get_user_by_username(session, "NOROLE") + assert u3 is not None and u3.id == user_no_role.id + assert get_user_by_username(session, "unknown") is None + assert get_user_by_username(session, "") is None