Compare commits

...
Author SHA1 Message Date
codex 96987e90c9 fix: restore login throttling after lock expiry
CI / test (pull_request) Successful in 10m10s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Has been skipped
2026-10-10 20:26:28 +03:00
codex a82f63d6cb feat: add system users, password management and activity history
CI / test (pull_request) Successful in 10m8s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Has been skipped
2026-10-10 18:55:05 +03:00
admin 03ac2f5ee8 Merge pull request 'Ускорение диссовета: подгрузка публикаций по сотруднику и понятные подсказки' (#68) from fix/council-loading into main
CI / test (push) Successful in 9m33s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (push) Has been skipped
Reviewed-on: #68
Reviewed-by: agent <agent@vakanaut.ru>
2026-10-10 14:33:17 +00:00
codex a7de80de3b fix: dismiss hovered council tooltips with Escape
CI / test (pull_request) Successful in 9m32s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Has been skipped
2026-10-10 16:43:27 +03:00
codex e08c30848f perf: load council publications on demand and reduce database payload
CI / test (pull_request) Successful in 9m30s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (pull_request) Has been skipped
2026-10-09 16:23:55 +03:00
admin 2554cbf39a Merge pull request 'Редактор публикаций диссовета, настройка оценки и компактный XLSX' (#67) from feature/council-publication-editor into main
CI / test (push) Successful in 9m30s
CI / Fingerprint diagnostics (production deployment temporarily disabled) (push) Has been skipped
Reviewed-on: #67
Reviewed-by: agent <agent@vakanaut.ru>
2026-10-09 11:50:52 +00:00
42 changed files with 1584 additions and 195 deletions

No files matched your search

+1
View File
@@ -29,6 +29,7 @@ jobs:
- run: python -m pytest -q
- run: node --check app/static/admin.js
- run: node --check app/static/council.js
- run: node --check app/static/users.js
- run: sh -n infra/postgres-backup.sh
- run: sh -n infra/install-postgres-backup-cron.sh
+27 -3
View File
@@ -24,7 +24,7 @@ cp .env.example .env
- `SOURCE_URL`: список сотрудников МИЭМ.
- `CRAWL_CRON`: расписание в формате crontab, по умолчанию `0 3 * * 1`.
- `CRAWL_LIMIT`: опциональный лимит профилей для тестового запуска.
- `ADMIN_USERNAME`, `ADMIN_PASSWORD`: логин и пароль админки.
- `ADMIN_USERNAME`, `ADMIN_PASSWORD`: начальные данные администратора для создания учётной записи в БД. После смены пароля используется пароль из БД; значения окружения его не перезаписывают.
- `SESSION_SECRET`: секрет подписи cookie.
- `PARSER_USE_PLAYWRIGHT`: включение Playwright-рендера динамических вкладок.
- `DISMISSAL_CONFIRMATION_RUNS`: сколько последовательных проверок недоступности нужно для увольнения, по умолчанию `3`.
@@ -53,6 +53,24 @@ uvicorn app.main:app --reload
Каталог формируется сервером: отдельная клиентская загрузка списка не нужна, переход показывает браузер. Пустой результат предлагает сбросить фильтры, пустая база — запустить парсинг. При ошибке базы каталог возвращает HTTP 503 и предлагает повторить загрузку с теми же фильтрами. При обновлении прогресса показывается состояние загрузки; при ошибке сохраняются последние значения с предупреждением об их актуальности и кнопкой «Повторить». Автоматические попытки продолжаются каждые 4 секунды, запрос ограничен 15 секундами; параллельные запросы не запускаются.
## Пользователи и личный кабинет
`/admin/users` доступен только администратору: создание учётных записей с ролями «Администратор»/«Пользователь», включение и отключение доступа, сброс пароля, первый и последний вход, дата смены пароля пользователем и выдачи временного пароля. Пользователь может читать служебные страницы и редактировать карточки, но не запускает парсинг (включая обновление одного сотрудника) и не управляет учётными записями. Проверки выполняются на сервере для HTML и API. Публичный просмотр диссовета и XLSX сохранён.
Временный пароль создаётся криптографическим генератором, содержит 8 символов и все четыре группы: строчные/заглавные латинские буквы, цифры и символы. Показывается администратору только в ответе на создание или сброс; повторно прочитать его нельзя. В БД — PBKDF2-HMAC-SHA256 с 600 000 итерациями и отдельной случайной солью. Пароли и их хеши не включаются в журнал действий или страницы просмотра истории.
При первом успешном входе и после сброса требуется задать свой пароль (15–128 символов, можно фразу), указав текущий пароль. Попап нельзя закрыть Escape или нажатием на фон; можно сменить пароль либо выйти. Без JavaScript доступна обычная форма, а серверные операции до смены пароля заблокированы. Начальный администратор также меняет пароль при первом входе после обновления.
`/admin/account` показывает первый/последний вход, смену пароля и историю действий. Каждый видит только свои действия и события, относящиеся к его учётной записи; администратор на странице пользователей видит общую историю или фильтр по учётной записи. Журнал фиксирует успешные входы, смену/сброс пароля, изменения ролей/доступа и реальные правки карточек: сотрудник, статья, год, прежние/новые значения названия, журнала, квартиля и тематической связи. Сохранение правки и запись истории — одна транзакция; отклонённые и неизменённые сохранения не создают запись о редактировании. История разбита на страницы по 30 записей.
Сессия ограничена 12 часами. Смена/сброс пароля, изменение роли/доступа и выход отзывают прежние сессии. Собственную роль/доступ и пароль через административный сброс менять нельзя: свой пароль меняется в личном кабинете. Изменения доступа сериализуются, чтобы параллельные администраторы не лишили систему всех администраторов. После пяти неверных входов учётная запись блокирует новые входы на 15 минут; административный сброс снимает это ограничение.
Все POST-формы требуют CSRF-токен; JSON-редактор сохраняет обязательный специальный заголовок при отключённом CORS. Проверяется Origin. Cookie — HttpOnly/SameSite, при HTTPS или HTTPS за обратным прокси — Secure; приватные страницы и одноразовые пароли возвращаются с Cache-Control: no-store. Для программного запуска парсинга передавайте CSRF-токен действующей административной сессии в X-CSRF-Token.
При штатном запуске создаются таблицы `system_users` и `user_actions` и начальная административная запись, если её нет. Для ручного добавления схемы доступна `migrations/013_system_users.sql`. Перед обновлением рабочей БД сделайте штатную резервную копию. После обновления потребуется повторный вход; первый вход и история отсчитываются от введения этой функции, прежние события не восстанавливаются. Изменение переменных окружения не сбрасывает существующий пароль и не включает отключённый аккаунт.
Проверки: `python -m pytest -q`, `python tests/browser_users.py`. Браузерный сценарий использует только синтетическую SQLite-БД и временный локальный HTTP-сервер без запуска миграций рабочего приложения; временные пароли на скриншотах скрыты. Для native PostgreSQL-проверок тестов пользователей задайте USERS_TEST_DATABASE_URL на отдельную одноразовую БД **miem_users_test**: эти тесты создают и удаляют в ней схему и не должны запускаться на рабочей БД.
## Docker Compose
```bash
@@ -94,7 +112,13 @@ Compose запускает `api`, `worker` и `postgres`. API привязан
Отдельно показаны предварительные Q1/Q2/К1/К2/RSCI, их объединение ВСЕГО и подтверждённое число, порог, монографии, пункт и причины проверки. Одна работа учитывается один раз, основания сохраняют исходные записи. Без подтверждения высшей степени, даты, отрасли и достаточного числа проверенных работ результат — «Требует проверки». Недостаток записей не доказывает отсутствие работ; соответствие публикационным критериям не означает автоматического включения в совет.
Кнопка «Статьи, журналы и квартили» открывает `/admin/council/publications` в отдельной вкладке. Здесь доступны совместные фильтры по ФИО, названию статьи и журнала. Нажатие на карточку статьи (или Enter/пробел с клавиатуры) показывает иконку редактирования; она открывает форму названия статьи, журнала и квартиля. Та же форма доступна в карточках основного списка. Для сохранения требуется вход администратора.
Начальный список диссовета содержит только сотрудников и счётчики. Публикации загружаются при раскрытии карточки через `/admin/council/employees/{id}/articles` с сохранением отрасли и специальности; повторное раскрытие использует уже загруженные данные текущей страницы. При ошибке доступна кнопка повтора, без JavaScript — ссылка на публикации. Экспорт XLSX продолжает включать все найденные записи.
До загрузки публикаций применяется поиск по ФИО и выбор конкретного сотрудника. Проверка одинаковых ФИО остаётся глобальной, а общий счётчик сотрудников не зависит от поиска. PostgreSQL возвращает только разделы профиля об образовании/степенях и необходимые поля публикаций; аннотации, авторы и остальной профиль не загружаются. Plain-text описания журналов не проходят через HTML-парсер; HTML и сущности обрабатываются как прежде.
Предупреждения публикации показаны красным значком рядом с типом, годом, журналом, квартилем или специальностью. Подсказка открывается при наведении, фокусе или нажатии, закрывается Escape. При отсутствии/неоднозначности типа подпись «Статья» — только отображение: красный значок объясняет отсутствие/расхождение исходного типа, и правило зачёта не ослабляется. Конфликт названия журнала поясняет, для какого журнала сохранён квартиль и к какому отнесена статья; проверки DOI/ISSN сохранены.
Кнопка «Статьи, журналы и квартили» открывает `/admin/council/publications` в отдельной вкладке. Здесь доступны совместные фильтры по ФИО, названию статьи и журнала. Нажатие на карточку статьи (или Enter/пробел с клавиатуры) показывает иконку редактирования; она открывает форму названия статьи, журнала и квартиля. Та же форма доступна в карточках основного списка. Для сохранения требуется вход пользователя или администратора.
Ручные изменения хранятся в отдельной таблице `council_corrections`, создаваемой при запуске приложения (`migrations/012_council_corrections.sql` для ручного обновления схемы). Исходные публикации и файлы выгрузки не перезаписываются. Квартиль применяется к выбранному журналу за год статьи, в том числе к другим статьям и сотрудникам; при неизвестном или конфликтующем годе можно исправить только название и журнал. Правки учитываются в фильтрах, предварительных счётчиках и XLSX. Ручные изменения журнала или квартиля требуют подтверждения источниками; изменение тематической связи само по себе не отменяет проверенный квартиль. Одновременное сохранение из устаревшей вкладки отклоняется: нужно обновить страницу. Привязка статьи использует исходный DOI или название и год; при изменении этих идентификаторов в источнике ручную привязку нужно проверить заново.
@@ -121,7 +145,7 @@ Compose запускает `api`, `worker` и `postgres`. API привязан
Worker запускает обход по `CRAWL_CRON`. Ручной запуск также доступен в админке на `Dashboard` и странице `Runs` или через REST:
```bash
curl -X POST http://localhost:8000/api/crawl-runs --cookie "miem_admin_session=..."
curl -X POST http://localhost:8000/api/crawl-runs --cookie "miem_admin_session=..." -H "X-CSRF-Token: ..."
```
Алгоритм обновления:
+94 -29
View File
@@ -9,8 +9,10 @@ from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.db import SessionLocal, get_db
from app.models import CrawlError, CrawlRun, Employee, CouncilCorrections
from app.security import SESSION_COOKIE, require_admin, sign_session, verify_admin, read_session
from app.models import CrawlError, CrawlRun, Employee, CouncilCorrections, UserAction
from app.security import (SESSION_COOKIE, LOGIN_CSRF_COOKIE, SESSION_SECONDS, require_admin, require_user,
optional_user, sign_session, authenticate, check_csrf)
import secrets
from app.services.admin_data import (
employee_detail_payload,
format_admin_datetime,
@@ -25,13 +27,14 @@ from app.services.council import CouncilInputError, council_candidates, _journal
from app.services.council_export import council_xlsx
from app.version import BACKEND_VERSION, FRONTEND_VERSION
router = APIRouter(prefix="/admin")
router = APIRouter(prefix="/admin", dependencies=[Depends(check_csrf)])
templates = Jinja2Templates(directory="app/templates")
templates.env.filters["admin_datetime"] = format_admin_datetime
@router.get("", response_class=HTMLResponse)
def dashboard(request: Request, db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
require_admin(request, settings)
require_user(request, settings, db)
counts = stats_payload(db)
counts["runs"] = db.scalar(select(func.count()).select_from(CrawlRun)) or 0
counts["errors"] = db.scalar(select(func.count()).select_from(CrawlError)) or 0
@@ -42,25 +45,48 @@ def dashboard(request: Request, db: Session = Depends(get_db), settings: Setting
@router.get("/login", response_class=HTMLResponse)
def login_form(request: Request):
return _render(request, "login.html", {"error": None})
csrf = secrets.token_urlsafe(24)
response = _render(request, "login.html", {"error": None, "csrf_token": csrf})
response.set_cookie(LOGIN_CSRF_COOKIE, csrf, httponly=True, samesite="strict", max_age=600, secure=request.url.scheme == 'https' or request.headers.get('x-forwarded-proto') == 'https')
return response
@router.post("/login")
def login(
request: Request,
username: str = Form(...),
password: str = Form(...),
username: str = Form(..., max_length=64),
password: str = Form(..., max_length=1024),
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
if not verify_admin(username, password, settings):
return _render(request, "login.html", {"error": "Неверный логин или пароль"}, status_code=401)
redirect = RedirectResponse("/admin", status_code=303)
redirect.set_cookie(SESSION_COOKIE, sign_session(username, settings), httponly=True, samesite="lax")
try:
user = authenticate(db, username, password, settings)
if user is None:
return _render(request, "login.html", {"error": "Неверный логин или пароль, либо вход временно недоступен",
"csrf_token": request.cookies.get(LOGIN_CSRF_COOKIE, '')}, status_code=401)
db.add(UserAction(user_id=user.id, action="login"))
db.commit()
except SQLAlchemyError:
db.rollback()
return _render(request, "login.html", {"error": "Вход временно недоступен. Попробуйте ещё раз",
"csrf_token": request.cookies.get(LOGIN_CSRF_COOKIE, '')}, status_code=503)
redirect = RedirectResponse("/admin/account" if user.must_change_password else "/admin", status_code=303)
redirect.set_cookie(SESSION_COOKIE, sign_session(user.username, settings, user.session_version),
httponly=True, samesite="lax", max_age=SESSION_SECONDS, secure=request.url.scheme == 'https' or request.headers.get('x-forwarded-proto') == 'https')
redirect.delete_cookie(LOGIN_CSRF_COOKIE)
return redirect
@router.post("/logout")
def logout():
def logout(request: Request, db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
user = optional_user(request, settings, db, allow_password_change=True, lock=True)
if user is not None:
try:
user.session_version += 1
db.commit()
except SQLAlchemyError:
db.rollback()
raise HTTPException(503, "Не удалось завершить сессии. Попробуйте ещё раз")
redirect = RedirectResponse("/admin/login", status_code=303)
redirect.delete_cookie(SESSION_COOKIE)
return redirect
@@ -71,9 +97,10 @@ def employees(
request: Request,
status: str | None = None,
q: str | None = None,
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_user(request, settings, db)
return RedirectResponse("/admin/directory", status_code=303)
@@ -93,7 +120,7 @@ def directory(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_user(request, settings, db)
parsed_started_from = _parse_date(started_from)
parsed_started_to = _parse_date(started_to)
parsed_has_email = None if has_email in (None, "") else has_email == "true"
@@ -139,6 +166,7 @@ def directory(
@router.get("/council", response_class=HTMLResponse)
def council(request: Request, q: str = "", offset: int = 0, sort: str = "total_count", direction: str = "desc", specialty: str = "", branch: str = "технические",
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
authenticated = optional_user(request, settings, db)
try:
result = council_candidates(db, q=q, offset=offset, sort=sort, direction=direction, specialty=specialty,
branch=branch)
@@ -147,7 +175,24 @@ def council(request: Request, q: str = "", offset: int = 0, sort: str = "total_c
except (SQLAlchemyError, OSError, ValueError, KeyError):
db.rollback()
return _render(request, "council.html", {"error": True, "public_page": True}, status_code=503)
return _render(request, "council.html", {"error": False, "public_page": True, "can_edit": read_session(request.cookies.get(SESSION_COOKIE), settings) == settings.admin_username, **result})
return _render(request, "council.html", {"error": False, "public_page": True, "can_edit": authenticated is not None, **result})
@router.get("/council/employees/{employee_id}/articles", response_class=HTMLResponse)
def council_employee_articles(employee_id: int, request: Request, specialty: str = "", branch: str = "технические",
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
authenticated = optional_user(request, settings, db)
try:
result = council_candidates(db, employee_id=employee_id, paginate=False, specialty=specialty, branch=branch)
if not result["candidates"]:
raise HTTPException(404, "Сотрудник не найден или не соответствует фильтру. Обновите список")
except CouncilInputError as exc:
raise HTTPException(422, str(exc))
except (SQLAlchemyError, OSError, ValueError, KeyError):
db.rollback()
raise HTTPException(503, "Не удалось загрузить публикации. Попробуйте ещё раз")
return _render(request, "council_candidate_articles.html", {"candidate": result["candidates"][0],
"can_edit": authenticated is not None, **result})
class CouncilArticleEdit(BaseModel):
@@ -165,9 +210,9 @@ class CouncilArticleEdit(BaseModel):
def council_publications(request: Request, employee: str = "", title: str = "", journal: str = "", offset: int = 0,
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
context = {"public_page": True, "employee": employee, "title": title, "journal": journal,
"can_edit": read_session(request.cookies.get(SESSION_COOKIE), settings) == settings.admin_username}
"can_edit": optional_user(request, settings, db) is not None}
try:
result = council_candidates(db, paginate=False, sort="full_name", direction="asc")
result = council_candidates(db, q=employee, paginate=False, sort="full_name", direction="asc")
articles = [{**article, "employee_id": candidate["employee_id"], "employee_name": candidate["name"]}
for candidate in result["candidates"] for article in candidate["articles"]
if employee.casefold().strip() in candidate["name"].casefold()
@@ -186,16 +231,15 @@ def council_publications(request: Request, employee: str = "", title: str = "",
@router.post("/council/publications")
def edit_council_publication(request: Request, change: CouncilArticleEdit,
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
username = read_session(request.cookies.get(SESSION_COOKIE), settings)
if username != settings.admin_username:
raise HTTPException(401, "Для сохранения войдите в админку")
actor = require_user(request, settings, db, lock=True)
username = actor.username
# A custom header plus JSON prevents cross-site form submissions; CORS is disabled.
if request.headers.get("X-Council-Edit") != "1":
raise HTTPException(403, "Недопустимый запрос на изменение")
if not _journal_key(change.journal):
raise HTTPException(422, "Укажите название журнала")
try:
result = council_candidates(db, paginate=False)
result = council_candidates(db, employee_id=change.employee_id, paginate=False)
article = next((a for c in result["candidates"] if c["employee_id"] == change.employee_id
for a in c["articles"] if a["edit_key"] == change.edit_key), None)
if not article:
@@ -228,6 +272,22 @@ def edit_council_publication(request: Request, change: CouncilArticleEdit,
raise HTTPException(409, "Данные уже изменены. Обновите страницу перед сохранением")
else:
db.add(CouncilCorrections(id=1, data=data, revision=1, updated_by=username))
changes = {}
for field, before, after in (("title", article["title"], change.title),
("journal", " / ".join(article["journals"]), change.journal),
("quartile", article["edit_quartile"], change.quartile)):
if before != after:
changes[field] = {"before": before, "after": after}
if "specialty_codes" in change.model_fields_set:
before = {"manual": article["manual_specialties"], "codes": article["edit_specialty_codes"] if article["manual_specialties"] else None}
after = {"manual": change.specialty_codes is not None,
"codes": sorted(set(change.specialty_codes or [])) if change.specialty_codes is not None else None}
if before != after:
changes["specialty_codes"] = {"before": before, "after": after}
if changes:
candidate = next(c for c in result["candidates"] if c["employee_id"] == change.employee_id)
db.add(UserAction(user_id=actor.id, action="card_edit", employee_id=change.employee_id,
employee_name=candidate["name"], publication_year=article["year"], publication_key=change.edit_key, article_title=change.title, changes=changes))
db.commit()
except IntegrityError:
db.rollback()
@@ -261,7 +321,7 @@ def employee_detail(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_user(request, settings, db)
employee = db.get(Employee, employee_id)
if not employee:
return RedirectResponse("/admin/employees", status_code=303)
@@ -292,7 +352,7 @@ def refresh_employee_detail(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_admin(request, settings, db)
employee = db.get(Employee, employee_id)
if not employee:
return RedirectResponse("/admin/directory", status_code=303)
@@ -303,7 +363,7 @@ def refresh_employee_detail(
@router.get("/runs", response_class=HTMLResponse)
def runs(request: Request, db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
require_admin(request, settings)
require_user(request, settings, db)
run_models = db.scalars(select(CrawlRun).order_by(desc(CrawlRun.started_at)).limit(50)).all()
items = [run_payload(run) for run in run_models]
errors = db.scalars(select(CrawlError).order_by(desc(CrawlError.created_at)).limit(50)).all()
@@ -317,7 +377,7 @@ def run_detail(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_user(request, settings, db)
run = db.get(CrawlRun, run_id)
if not run:
return RedirectResponse("/admin/runs", status_code=303)
@@ -331,7 +391,7 @@ def trigger_run(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_admin(request, settings, db)
if get_running_run(db):
return RedirectResponse("/admin/runs", status_code=303)
@@ -350,7 +410,7 @@ def crawl_now(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_admin(request, settings, db)
if get_running_run(db):
return RedirectResponse("/admin", status_code=303)
@@ -369,7 +429,7 @@ def refresh_dismissed(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
):
require_admin(request, settings)
require_admin(request, settings, db)
if get_running_run(db):
return RedirectResponse("/admin", status_code=303)
@@ -384,11 +444,16 @@ def refresh_dismissed(
def _render(request: Request, template: str, context: dict, status_code: int = 200) -> HTMLResponse:
payload = {
"request": request,
"current_user": getattr(request.state, "user", None),
"csrf_token": getattr(request.state, "csrf_token", ""),
"backend_version": BACKEND_VERSION,
"frontend_version": FRONTEND_VERSION,
**context,
}
return templates.TemplateResponse(request, template, payload, status_code=status_code)
response = templates.TemplateResponse(request, template, payload, status_code=status_code)
if getattr(request.state, "user", None) is not None or template == "login.html":
response.headers["Cache-Control"] = "no-store"
return response
def _parse_date(value: str | None):
+9 -9
View File
@@ -7,12 +7,12 @@ from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.db import SessionLocal, get_db
from app.models import CrawlRun, Employee
from app.security import require_admin
from app.security import require_admin, require_user, check_csrf
from app.services.admin_data import employee_display_payload, list_employees_page, run_detail_payload, run_payload, stats_payload
from app.services.crawl_control import get_running_run, run_crawl_if_idle
from app.version import BACKEND_VERSION, FRONTEND_VERSION
router = APIRouter(prefix="/api")
router = APIRouter(prefix="/api", dependencies=[Depends(check_csrf)])
@router.get("/health")
@@ -36,7 +36,7 @@ def list_employees(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_user(request, settings, db)
return list_employees_page(
db,
status=status,
@@ -59,7 +59,7 @@ def get_employee(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_user(request, settings, db)
employee = db.get(Employee, employee_id)
if not employee:
return {"error": "not_found"}
@@ -73,7 +73,7 @@ def list_crawl_runs(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_user(request, settings, db)
runs = db.scalars(select(CrawlRun).order_by(desc(CrawlRun.started_at)).limit(limit)).all()
return {"items": [run_payload(run) for run in runs]}
@@ -84,7 +84,7 @@ def latest_crawl_run(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_user(request, settings, db)
running = get_running_run(db)
latest = db.scalar(select(CrawlRun).order_by(desc(CrawlRun.started_at)).limit(1))
return {"running": run_payload(running), "latest": run_payload(latest)}
@@ -97,7 +97,7 @@ def get_crawl_run(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_user(request, settings, db)
run = db.get(CrawlRun, run_id)
if not run:
return {"error": "not_found"}
@@ -111,7 +111,7 @@ def trigger_crawl(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_admin(request, settings, db)
running = get_running_run(db)
if running:
return {"status": "already_running", "run": run_payload(running)}
@@ -130,7 +130,7 @@ def stats(
db: Session = Depends(get_db),
settings: Settings = Depends(get_settings),
) -> dict:
require_admin(request, settings)
require_user(request, settings, db)
return stats_payload(db)
+3
View File
@@ -26,6 +26,9 @@ def init_db() -> None:
Base.metadata.create_all(bind=engine)
_ensure_runtime_schema()
from app.security import ensure_bootstrap_admin
with SessionLocal() as db:
ensure_bootstrap_admin(db, settings)
def _ensure_runtime_schema() -> None:
+2
View File
@@ -3,12 +3,14 @@ from fastapi.staticfiles import StaticFiles
from app.admin import router as admin_router
from app.api import router as api_router
from app.users import router as users_router
from app.db import init_db
from app.version import BACKEND_VERSION
app = FastAPI(title="MIEM Employees", version=BACKEND_VERSION)
app.mount("/static", StaticFiles(directory="app/static"), name="static")
app.include_router(api_router)
app.include_router(users_router)
app.include_router(admin_router)
+40 -1
View File
@@ -1,6 +1,6 @@
from datetime import datetime, timezone
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, LargeBinary, String, Text, UniqueConstraint
from sqlalchemy import CheckConstraint, Boolean, DateTime, ForeignKey, Index, Integer, LargeBinary, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import JSON
@@ -254,3 +254,42 @@ class CouncilCorrections(Base):
data: Mapped[dict] = mapped_column(json_type, nullable=False)
updated_by: Mapped[str] = mapped_column(String(255), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, onupdate=utcnow, nullable=False)
class SystemUser(Base):
__tablename__ = "system_users"
__table_args__ = (CheckConstraint("role IN ('admin', 'user')", name="ck_system_users_role"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
full_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
role: Mapped[str] = mapped_column(String(16), default="user", nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
must_change_password: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
session_version: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
first_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
password_changed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
password_reset_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
failed_login_attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
locked_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, nullable=False)
class UserAction(Base):
__tablename__ = "user_actions"
__table_args__ = (Index("ix_user_actions_user_created", "user_id", "created_at"),
Index("ix_user_actions_target_created", "target_user_id", "created_at"))
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("system_users.id"), nullable=False)
action: Mapped[str] = mapped_column(String(32), nullable=False)
target_user_id: Mapped[int | None] = mapped_column(ForeignKey("system_users.id"))
employee_id: Mapped[int | None] = mapped_column(Integer)
employee_name: Mapped[str | None] = mapped_column(Text)
publication_year: Mapped[int | None] = mapped_column(Integer)
publication_key: Mapped[str | None] = mapped_column(String(64))
article_title: Mapped[str | None] = mapped_column(Text)
changes: Mapped[dict] = mapped_column(json_type, default=dict, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, nullable=False)
+177 -25
View File
@@ -2,45 +2,197 @@ import base64
import hashlib
import hmac
import json
import secrets
import time
from datetime import timedelta, timezone
from urllib.parse import urlsplit
from fastapi import HTTPException, Request, status
from fastapi import Depends, HTTPException, Request
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import Session
from app.config import Settings
from app.config import Settings, get_settings
from app.models import SystemUser, utcnow
SESSION_COOKIE = "miem_admin_session"
LOGIN_CSRF_COOKIE = "miem_login_csrf"
SESSION_SECONDS = 12 * 60 * 60
PASSWORD_ITERATIONS = 600_000
def verify_admin(username: str, password: str, settings: Settings) -> bool:
return hmac.compare_digest(username, settings.admin_username) and hmac.compare_digest(
password, settings.admin_password
)
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, PASSWORD_ITERATIONS)
return f"pbkdf2_sha256${PASSWORD_ITERATIONS}${salt.hex()}${digest.hex()}"
def sign_session(username: str, settings: Settings) -> str:
payload = base64.urlsafe_b64encode(
json.dumps({"sub": username, "iat": int(time.time())}, separators=(",", ":")).encode("utf-8")
).decode("ascii")
signature = hmac.new(settings.session_secret.encode("utf-8"), payload.encode("ascii"), hashlib.sha256).hexdigest()
return f"{payload}.{signature}"
def verify_password(password: str, encoded: str) -> bool:
try:
scheme, iterations, salt, expected = encoded.split('$')
if scheme != 'pbkdf2_sha256' or int(iterations) != PASSWORD_ITERATIONS:
return False
actual = hashlib.pbkdf2_hmac('sha256', password.encode(), bytes.fromhex(salt), PASSWORD_ITERATIONS)
return hmac.compare_digest(actual, bytes.fromhex(expected))
except (ValueError, TypeError, AttributeError):
return False
_DUMMY_HASH = hash_password('dummy password for unknown account timing')
def temporary_password() -> str:
groups = ('ABCDEFGHJKLMNPQRSTUVWXYZ', 'abcdefghijkmnpqrstuvwxyz', '23456789', '!@#$%+-_')
characters = [secrets.choice(group) for group in groups]
characters.extend(secrets.choice(''.join(groups)) for _ in range(4))
secrets.SystemRandom().shuffle(characters)
return ''.join(characters)
def ensure_bootstrap_admin(db: Session, settings: Settings) -> SystemUser:
username = settings.admin_username.strip().casefold()
user = db.scalar(select(SystemUser).where(SystemUser.username == username))
if user is not None:
return user
user = SystemUser(username=username, role='admin', password_hash=hash_password(settings.admin_password),
must_change_password=False)
db.add(user)
try:
db.commit()
except IntegrityError:
db.rollback()
user = db.scalar(select(SystemUser).where(SystemUser.username == username))
return user
def sign_session(username: str, settings: Settings, version: int = 0) -> str:
payload = base64.urlsafe_b64encode(json.dumps({'sub': username, 'iat': int(time.time()),
'v': version, 'csrf': secrets.token_urlsafe(24)}, separators=(',', ':')).encode()).decode().rstrip('=')
signature = hmac.new(settings.session_secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
return f'{payload}.{signature}'
def _session_data(token: str | None, settings: Settings) -> dict | None:
if not token or len(token) > 2048 or '.' not in token:
return None
payload, signature = token.rsplit('.', 1)
expected = hmac.new(settings.session_secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature.encode(), expected.encode()):
return None
try:
data = json.loads(base64.urlsafe_b64decode((payload + '=' * (-len(payload) % 4)).encode()))
now = int(time.time())
if (not isinstance(data, dict) or not isinstance(data.get('sub'), str)
or type(data.get('iat')) is not int or not now - SESSION_SECONDS <= data['iat'] <= now + 60
or type(data.get('v')) is not int or not isinstance(data.get('csrf'), str)):
return None
return data
except (ValueError, TypeError, UnicodeError):
return None
def read_session(token: str | None, settings: Settings) -> str | None:
if not token or "." not in token:
return None
payload, signature = token.rsplit(".", 1)
expected = hmac.new(settings.session_secret.encode("utf-8"), payload.encode("ascii"), hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
data = _session_data(token, settings)
return data['sub'] if data else None
def session_csrf(request: Request, settings: Settings) -> str:
data = _session_data(request.cookies.get(SESSION_COOKIE), settings)
return data['csrf'] if data else ''
async def check_csrf(request: Request, settings: Settings = Depends(get_settings)):
if request.method != 'POST':
return
origin = request.headers.get('origin')
if origin:
try:
parsed = urlsplit(origin)
except ValueError:
raise HTTPException(403, 'Недопустимый источник запроса')
if parsed.scheme not in {'http', 'https'} or parsed.netloc.casefold() != request.url.netloc.casefold():
raise HTTPException(403, 'Запрос должен исходить со страницы этой системы')
# JSON with a custom header cannot be submitted by a cross-site HTML form; CORS stays disabled.
if request.headers.get('X-Council-Edit') == '1' and request.headers.get('content-type', '').startswith('application/json'):
return
expected = (request.cookies.get(LOGIN_CSRF_COOKIE, '') if request.url.path == '/admin/login'
else session_csrf(request, settings))
if request.url.path == '/admin/logout' and not expected:
return
supplied = request.headers.get('X-CSRF-Token', '')
if not supplied:
form = await request.form()
supplied = form.get('csrf_token', '')
if not expected or not isinstance(supplied, str) or not hmac.compare_digest(supplied.encode(), expected.encode()):
raise HTTPException(403, 'Обновите страницу и повторите действие')
def optional_user(request: Request, settings: Settings, db: Session, *, allow_password_change=False, lock=False) -> SystemUser | None:
data = _session_data(request.cookies.get(SESSION_COOKIE), settings)
if not data:
return None
query = select(SystemUser).where(SystemUser.username == data['sub'].casefold())
if lock:
query = query.with_for_update().execution_options(populate_existing=True)
try:
data = json.loads(base64.urlsafe_b64decode(payload.encode("ascii")))
except Exception:
user = db.scalar(query)
if user is None and data['sub'].casefold() == settings.admin_username.strip().casefold():
user = ensure_bootstrap_admin(db, settings)
except SQLAlchemyError:
db.rollback()
raise HTTPException(503, 'Не удалось проверить учётную запись. Попробуйте ещё раз')
if user is None or not user.is_active or user.session_version != data['v']:
return None
return data.get("sub")
request.state.user = user
request.state.csrf_token = data['csrf']
if user.must_change_password and not allow_password_change:
if request.url.path.startswith('/api/') or (request.method == 'POST' and request.url.path == '/admin/council/publications'):
raise HTTPException(403, 'Сначала смените временный пароль в личном кабинете')
raise HTTPException(303, headers={'Location': '/admin/account'})
return user
def require_admin(request: Request, settings: Settings) -> str:
username = read_session(request.cookies.get(SESSION_COOKIE), settings)
if not username:
raise HTTPException(status_code=status.HTTP_303_SEE_OTHER, headers={"Location": "/admin/login"})
return username
def require_user(request: Request, settings: Settings, db: Session, *, allow_password_change=False, lock=False) -> SystemUser:
user = optional_user(request, settings, db, allow_password_change=allow_password_change, lock=lock)
if user is None:
if request.url.path.startswith('/api/') or (request.method == 'POST' and request.url.path == '/admin/council/publications'):
raise HTTPException(401, 'Для этого действия войдите в систему')
raise HTTPException(303, headers={'Location': '/admin/login'})
return user
def require_admin(request: Request, settings: Settings, db: Session) -> SystemUser:
user = require_user(request, settings, db)
if user.role != 'admin':
raise HTTPException(403, 'Это действие доступно только администратору')
return user
def authenticate(db: Session, username: str, password: str, settings: Settings) -> SystemUser | None:
ensure_bootstrap_admin(db, settings)
user = db.scalar(select(SystemUser).where(SystemUser.username == username.strip().casefold()).with_for_update())
valid = verify_password(password, user.password_hash if user else _DUMMY_HASH)
if user is None:
return None
now = utcnow()
locked_until = user.locked_until
if locked_until and locked_until.tzinfo is None:
locked_until = locked_until.replace(tzinfo=timezone.utc)
if not user.is_active or (locked_until and locked_until > now):
return None
if not valid:
if locked_until:
user.locked_until = None
user.failed_login_attempts = 0
user.failed_login_attempts += 1
if user.failed_login_attempts >= 5:
user.locked_until = now + timedelta(minutes=15)
db.commit()
return None
user.failed_login_attempts = 0
user.locked_until = None
if user.first_login_at is None:
user.first_login_at = now
user.must_change_password = True
user.last_login_at = now
return user
+60 -20
View File
@@ -10,10 +10,11 @@ from pathlib import Path
from urllib.parse import quote, urlsplit
from zoneinfo import ZoneInfo
from sqlalchemy import select
from sqlalchemy.orm import Session, selectinload
from sqlalchemy import select, func, case, cast
from sqlalchemy.dialects.postgresql import JSONPATH
from sqlalchemy.orm import Session
from app.models import Employee, CouncilCorrections
from app.models import Employee, EmployeePublication, CouncilCorrections, json_type
from app.services.academic_degrees import academic_degrees
from app.services.council_source import _doi, _journal_names, _name, load_reference, _description_journals
from app.services.council_catalog import catalog, publication_catalog
@@ -101,7 +102,7 @@ def _articles_by_author() -> dict[str, list[dict]]:
def _database_article(publication) -> dict:
raw = publication.raw_data if isinstance(publication.raw_data, dict) else {}
imported = raw.get("csv_enrichment")
from_site = not imported or bool(publication.publication_id or publication.url or any(key != "csv_enrichment" for key in raw))
from_site = not imported or bool(publication.publication_id or publication.url or getattr(publication, "raw_has_metadata", any(key != "csv_enrichment" for key in raw)))
origins = ["ЛК сотрудника ВШЭ"] if from_site else []
if imported:
origins.append("Данные ВШЭ")
@@ -252,7 +253,7 @@ def _unique_articles(articles: list[dict], start: date, end: date, corrections=N
def council_candidates(db: Session, today: date | None = None, q: str = "", offset: int = 0,
sort: str = "total_count", direction: str = "desc", paginate: bool = True, specialty: str = "",
branch: str = "технические") -> dict:
branch: str = "технические", employee_id: int | None = None) -> dict:
if branch and branch not in BRANCHES:
raise CouncilInputError("Неизвестная отрасль науки")
today = today or datetime.now(ZoneInfo("Europe/Moscow")).date()
@@ -261,27 +262,64 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
if specialty and specialty not in {s["code"] for s in specialties}:
raise CouncilInputError("Неизвестная специальность ВАК")
specialty_name = next((s["name"] for s in specialties if s["code"] == specialty), "")
employees = db.scalars(select(Employee).options(selectinload(Employee.publications))).all()
degree_sections = Employee.current_data["sections"]
if db.get_bind().dialect.name == "postgresql":
degree_sections = func.jsonb_path_query_array(Employee.current_data,
cast('$.sections[*] ? (@.title like_regex "образован|степен|academic degree|education" flag "i")', JSONPATH), type_=json_type)
employees = db.execute(select(Employee.id, Employee.profile_key, Employee.full_name, Employee.status,
Employee.canonical_url, degree_sections.label("degree_sections"))).all()
name_counts = Counter(_name(employee.full_name or "") for employee in employees)
by_author = _articles_by_author()
verified = evidence()
corrections_record = db.get(CouncilCorrections, 1)
corrections = corrections_record.data if corrections_record else {}
revision = corrections_record.revision if corrections_record else 0
candidates = []
eligible = []
degrees_by_employee = {}
for employee in employees:
try:
degrees = academic_degrees({"sections": employee.degree_sections})
except (AttributeError, TypeError):
degrees = []
if any(degree_level(degree) for degree in degrees) or verified["employees"].get(employee.profile_key, {}).get("degrees"):
eligible.append(employee)
degrees_by_employee[employee.id] = degrees
total = len(eligible)
query = _name(q)
eligible = [employee for employee in eligible if query in _name(employee.full_name or "ФИО не указано")
and (employee_id is None or employee.id == employee_id)]
publication_fields = [EmployeePublication.employee_id, EmployeePublication.title, EmployeePublication.year,
EmployeePublication.publication_type, EmployeePublication.publication_id, EmployeePublication.url,
EmployeePublication.doi_url, EmployeePublication.source_hash, EmployeePublication.quartiles]
raw_data, description = EmployeePublication.raw_data, EmployeePublication.description
if db.get_bind().dialect.name == "postgresql":
# Only council metadata crosses the DB boundary; abstracts/authors stay in PostgreSQL.
description = case((func.jsonb_typeof(description) == "object", func.jsonb_build_object(
"short", description["short"], "shortLeft", description["shortLeft"], type_=json_type)),
else_=description)
raw = EmployeePublication.raw_data
raw_has_metadata = case((func.jsonb_typeof(raw) == "object",
raw != func.jsonb_build_object("csv_enrichment", raw["csv_enrichment"])), else_=False)
raw_keys = ("csv_enrichment", "journal", "Журнал", "Название журнала", "issn", "eissn", "ISSN", "EISSN")
raw_data = case((func.jsonb_typeof(raw) == "object", func.jsonb_build_object(
*[value for key in raw_keys for value in (key, raw[key])],
"description", case((func.jsonb_typeof(EmployeePublication.description) == "object", None),
else_=raw["description"]), type_=json_type)), else_=None)
publication_fields.append(raw_has_metadata.label("raw_has_metadata"))
publications_by_employee = defaultdict(list)
if eligible:
publications = db.execute(select(*publication_fields, raw_data.label("raw_data"), description.label("description"))
.where(EmployeePublication.employee_id.in_([e.id for e in eligible]))).all()
for publication in publications:
publications_by_employee[publication.employee_id].append(publication)
candidates = []
for employee in eligible:
author = _name(employee.full_name or "")
ambiguous = bool(author and name_counts[author] > 1 and by_author.get(author))
csv_articles = by_author.get(author, []) if author and name_counts[author] == 1 else []
data = employee.current_data if isinstance(employee.current_data, dict) else {}
try:
degrees = academic_degrees(data)
except (AttributeError, TypeError):
degrees = []
degrees = degrees_by_employee[employee.id]
employee_evidence = verified["employees"].get(employee.profile_key, {})
if not any(degree_level(degree) for degree in degrees) and not employee_evidence.get("degrees"):
continue
articles = _unique_articles([*csv_articles, *(_database_article(p) for p in employee.publications)], start, end, corrections, employee.id)
articles = _unique_articles([*csv_articles, *(_database_article(p) for p in publications_by_employee[employee.id])], start, end, corrections, employee.id)
for article in articles:
article["manual_review"] = article["journal_corrected"] or (len(article["journals"]) == 1 and
f"{_journal_key(article['journals'][0])}:{article['year']}" in corrections.get("journals", {}))
@@ -353,13 +391,18 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
if not any((a["doi"] and p.get("doi") == a["doi"]) or p.get("source_hash") in a["source_hashes"] for a in changed)]}
assessment = assess_candidate(degrees, articles, adjusted_evidence, branch, specialty, start, end)
for article in changed:
article["confirmation_reasons"].append("Ручная корректировка требует повторного подтверждения источниками")
message = "Журнал или квартиль исправлен вручную. Для зачёта требуется источник, подтверждающий эти сведения за год статьи"
article["confirmation_reasons"].append(message)
article["warnings"]["quartile"].append(message)
specialty_count = sum(specialty in a["specialty_codes"] for a in articles) if specialty else 0
for article in articles:
article["matches_specialty"] = bool(specialty and specialty in article["specialty_codes"])
if article["matches_specialty"]:
article["criteria"].append(f"По специальности {specialty}: {specialty_name} ({'ручная связь журнала' if article['manual_specialties'] else 'журнал К1, Перечень ВАК'})")
for article in articles:
if specialty:
article["warnings"]["specialty"].extend(text for record in article["catalog_records"]
for text in record["thematic"] if not text.startswith(("Паспорт ", "Аналитическая связь журнала:")))
article["messages"] = list(dict.fromkeys([*article["criteria"], *article["confirmation_reasons"]]))
candidates.append({**assessment, "specialty_count": specialty_count,"name": employee.full_name or "ФИО не указано", "employee_id": employee.id,
"count": len(articles),
@@ -373,10 +416,7 @@ def council_candidates(db: Session, today: date | None = None, q: str = "", offs
candidates.sort(key=lambda item: _name(item["name"]), reverse=sort == "full_name" and direction == "desc")
if sort != "full_name":
candidates.sort(key=lambda item: (item[sort], item["count"]), reverse=direction == "desc")
total = len(candidates)
query = _name(q)
candidates = [item for item in candidates if query in _name(item["name"])
and (not specialty or item["specialty_count"] > 0)]
candidates = [item for item in candidates if not specialty or item["specialty_count"] > 0]
matched = len(candidates)
limit = 25
offset = min(max(0, offset), ((matched - 1) // limit) * limit) if matched else 0
+26 -11
View File
@@ -127,6 +127,10 @@ def publication_proofs(employee_evidence, article):
def assess_article(article, proofs, start, end, level, branch, specialty, policy):
reasons = [*article.get("catalog_issues", []), *article.get("quartile_issues", [])]
warnings = {"journal": list(dict.fromkeys(reasons)), "year": [], "type": [], "quartile": [], "specialty": []}
def report(field, message):
reasons.append(message)
warnings[field].append(message)
years = article["source_years"]
dates = set()
for proof in proofs:
@@ -138,32 +142,39 @@ def assess_article(article, proofs, start, end, level, branch, specialty, policy
date_years = {value.year for value in dates}
date_conflict = len(years) > 1 or len(date_years) > 1 or bool(date_years and years and not date_years <= set(years))
if date_conflict:
reasons.append("Годы публикации в источниках расходятся")
report("year", "Источники указывают разные годы публикации. Уточните год статьи")
exact = next(iter(dates)) if len(dates) == 1 else None
publication_year = article["year"] if article["year"] is not None else next(iter(date_years)) if len(date_years) == 1 else None
in_period = publication_year is not None and start.year <= publication_year <= end.year
if not in_period:
reasons.append(f"Вне пятилетнего периода {start.year}–{end.year}" if publication_year is not None
report("year", f"Вне пятилетнего периода {start.year}–{end.year}" if publication_year is not None
else "Год не указан — период не подтверждён")
types = {proof["kind"] for proof in proofs if proof.get("kind") and sourced(proof.get("kind_evidence"))}
automatic_bases = [b for b in article.get("automatic_quartile_bases", [])
if b["applicable_year"] == (exact.year if exact else article["year"])
and not article.get("catalog_issues") and not article.get("quartile_issues")]
if len(types) != 1 and not (not types and article["types"] == ["Статья"] and automatic_bases):
reasons.append("Вид материала не подтверждён или расходится")
if not types and not (article["types"] == ["Статья"] and automatic_bases):
if len(article["types"]) > 1:
report("type", "Источники называют разные виды работы: " + ", ".join(article["types"]) + ". Уточните тип материала")
elif not article["types"]:
report("type", "В источниках не указан тип материала. В карточке показано «Статья», но для зачёта нужно уточнить вид работы")
elif article["types"] == ["Статья"]:
report("quartile", "Тип «Статья» указан в источнике, но для зачёта по К1/К2/RSCI отдельная запись проверки работы не сохранена. Проверьте основание зачёта")
else:
report("type", f"Источник указывает вид «{article['types'][0]}». Для включения такого материала в минимум нужно отдельное подтверждение")
kind = next(iter(types)) if len(types) == 1 else "article" if not types and article["types"] == ["Статья"] and automatic_bases else None
type_conflict = len(types) > 1 or bool(article["types"] and kind and article["types"] != [TYPE_LABELS.get(kind)])
if type_conflict:
reasons.append("Виды материала в источниках расходятся")
report("type", "Источники называют разные виды работы. Уточните, является ли публикация статьёй")
eligible_kind = publication_type_allowed(article["types"], kind, policy)
if kind and kind != "article" and not eligible_kind:
reasons.append("Зачёт этого вида материала в общий минимум не подтверждён")
report("type", "Это другой вид работы, а не статья. Его включение в публикационный минимум требует отдельного основания")
bases = []
basis_year = exact.year if exact else article["year"]
for proof in proofs:
for basis in proof.get("bases", []):
if not isinstance(basis, dict):
reasons.append("Некорректное подтверждение основания")
report("quartile", "Запись об основании зачёта повреждена. Проверьте источник категории журнала")
continue
category = basis.get("basis")
valid = sourced(basis) and type(basis.get("applicable_year")) is int and basis["applicable_year"] == basis_year
@@ -174,7 +185,7 @@ def assess_article(article, proofs, start, end, level, branch, specialty, policy
if valid:
bases.append(basis)
else:
reasons.append("Источник или год применимости основания не подтверждены")
report("quartile", "Для категории журнала не подтверждён источник или год применимости. Нельзя переносить категорию автоматически на год статьи")
if kind == "article":
bases.extend(automatic_bases)
# Different categories may legitimately have different quartiles; conflicting
@@ -185,19 +196,19 @@ def assess_article(article, proofs, start, end, level, branch, specialty, policy
key = ("ВАК", basis_year) if basis["basis"] in {"К1", "К2"} else (
basis.get("system", basis["basis"]), basis.get("category"), basis.get("metric"), basis.get("metric_year"), basis_year)
if key in claims and claims[key] != basis["basis"]:
reasons.append("Подтверждённые основания источников расходятся")
report("quartile", "Подтверждённые основания источников расходятся: для одной системы, категории, метрики и года указаны разные значения")
basis_conflict = True
claims[key] = basis["basis"]
accepted = [b for b in bases if level == 2 or b["basis"] != "К2"]
if not accepted:
reasons.append("Нет подтверждённого допустимого основания выбранного пункта")
report("quartile", f"Нет подтверждённого основания за {basis_year or 'год публикации'}: Q1/Q2, К1{'/К2' if level == 2 else ''} или RSCI. Проверьте категорию журнала, год и источник")
# Missing optional evidence is not a veto on another sufficient independent
# basis. Identity/date/type conflicts, however, invalidate the whole work.
identity_conflict = bool(article.get("quartile_issues")) or any("расход" in reason or "идентичности" in reason or "разные журналы" in reason
for reason in article.get("catalog_issues", []))
if article.get("proof_identity_conflict"):
identity_conflict = True
reasons.append("Идентификаторы ручного подтверждения указывают на разные работы")
report("journal", "DOI и идентификатор в ручном подтверждении указывают на разные работы. Проверьте привязку источника к этой статье")
conflicts = date_conflict or type_conflict or basis_conflict or identity_conflict
article["confirmed"] = bool(in_period and eligible_kind and accepted and not conflicts)
mono_policy = policy.get("monograph_period", {})
@@ -205,6 +216,8 @@ def assess_article(article, proofs, start, end, level, branch, specialty, policy
and (mono_policy.get("value") == "all_years" or
(mono_policy.get("value") == "five_years" and in_period)))
article["confirmation_reasons"] = list(dict.fromkeys(reasons))
article["warnings"] = warnings
article["display_type"] = article["type_label"] if len(article["types"]) == 1 else "Статья"
article["publication_date"] = exact
article["confirmed_bases"] = [{**b, "source_url": safe_url(b.get("source_url"))} for b in accepted]
article["thematic_status"] = "Рассмотрение статьи по паспорту не подтверждено" if specialty else "Специальность для рассмотрения статьи не выбрана"
@@ -225,6 +238,8 @@ def assess_article(article, proofs, start, end, level, branch, specialty, policy
f"пункты {review['point_numbers']}; {review['checked_on']}")
if len({r["result"] for r in valid_reviews}) > 1:
article["thematic_status"] = "Результаты рассмотрения статьи расходятся — требуется проверка"
if specialty and (not valid_reviews or any(r["result"] != "confirmed" for r in valid_reviews)):
warnings["specialty"].append("Связь журнала со специальностью не доказывает соответствие содержания каждой статьи. Рассмотрение этой работы по паспорту специальности не подтверждено")
def assess_candidate(degrees, articles, employee_evidence, branch, specialty, start, end):
+1 -1
View File
@@ -149,7 +149,7 @@ def publication_catalog(identifiers, names, specialty=""):
return [], [*issues, "ISSN указывают на разные журналы — требуется проверка"]
records = data["journals"].get(next(iter(matches)), []) if matches else []
if records and names and not any(str(name).casefold().strip() == r["name"].casefold() for name in names for r in records):
issues.append("Название журнала и ISSN требуют подтверждения идентичности")
issues.append("Название журнала в публикации и запись по ISSN расходятся. Проверьте, относятся ли они к одному журналу")
output = []
for record in records:
link = record["links"].get(specialty)
+1 -1
View File
@@ -47,7 +47,7 @@ def _description_journals(description: dict) -> list[str]:
values = value.values() if isinstance(value, dict) else [value]
for text in values:
if isinstance(text, str):
text = BeautifulSoup(text, "html.parser").get_text(" ", strip=True)
text = BeautifulSoup(text, "html.parser").get_text(" ", strip=True) if "<" in text or "&" in text else text.strip()
# HSE short descriptions start with the journal, followed by the year.
names.append(re.split(r"\b(?:19|20)\d{2}\b", text, maxsplit=1)[0].strip(" .,:;"))
return names
+1 -1
View File
@@ -118,7 +118,7 @@ def binding_issue(item, payload, doi="", journals=(), identifiers=()):
source_name = _name(item.get("journal") or "")
names_match = bool(source_name and source_name in {_name(name) for name in journals if name})
if source_name and journals and not names_match and not ids_match:
return "Журнал сохранённого квартиля и публикации расходятся — требуется перепроверка"
return f"Квартиль сохранён для журнала «{item.get('journal')}», а статья отнесена к «{' / '.join(journals)}». Совпадение по ISSN не подтверждено. Уточните журнал статьи и источник квартиля"
if not (source_doi and source_doi == current_doi) and not ids_match and not names_match:
return "Привязка сохранённого квартиля к публикации не подтверждена — требуется перепроверка"
return None
+28
View File
@@ -938,3 +938,31 @@
.council-editor__specialties fieldset { min-width: 0; margin: 0; padding: 12px; border: 1px solid #d6dddc; border-radius: 8px; }
.council-editor__specialties .columns-modal__grid { grid-template-columns: 1fr; margin-block: 12px; }
.council__criteria-list { line-height: 1.55; }
.council__warning { display: inline-block; vertical-align: middle; }
.council__warning-button { display: inline-flex; justify-content: center; align-items: center; min-width: 40px; min-height: 40px; padding: 0; border: 0; border-radius: 4px; color: #991b1b; background: transparent; cursor: pointer; vertical-align: middle; }
.council__warning-button:hover { background: #fee2e2; }
.council__tooltip { position: fixed; z-index: 30; width: min(360px, calc(100vw - 24px)); padding: 12px; box-sizing: border-box; border: 1px solid #d6dddc; border-radius: 8px; color: #1f2937; background: #fff; box-shadow: 0 6px 20px rgba(15, 23, 42, .18); font: 14px/1.5 system-ui, sans-serif; max-height: min(360px, calc(100vh - 24px)); overflow: auto; text-align: start; overflow-wrap: anywhere; }
.council__tooltip[hidden] { display: none; }
.council__load-status--done { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
@media (max-width: 600px) { .council__warning-button { min-width: 44px; min-height: 44px; } }
.users__table-wrap { overflow-x: auto; margin-block: 20px; }
.users__table-wrap .table { min-width: 720px; }
.users__table-wrap .table__cell { vertical-align: top; overflow-wrap: anywhere; max-width: 420px; }
.users__controls { display: grid; gap: 8px; min-width: 160px; }
.users__controls label { display: grid; gap: 4px; }
.users__create { margin-block: 24px; }
.users__create summary { cursor: pointer; padding-block: 10px; font-weight: 600; }
.users__create-form, .users__password-form { max-width: 520px; }
.users__hint { color: #4c5b64; font-size: 14px; line-height: 1.5; }
.users__error { color: #991b1b; line-height: 1.5; }
.users__temporary { padding: 16px; background: #e7f0eb; border: 1px solid #8fa8a5; border-radius: 8px; }
.users__temporary .form__input { max-width: 240px; font-family: monospace; font-size: 20px; }
.users__account-meta { display: flex; gap: 20px; flex-wrap: wrap; }
.users__account-meta dt { color: #4c5b64; font-size: 14px; }
.users__account-meta dd { margin: 4px 0 0; }
.users__change { margin-top: 6px; }
@media (max-width: 600px) { .users .form__input { font-size: 16px; } }
.users__history-table .table__cell:nth-child(2) { min-width: 100px; white-space: nowrap; }
+79 -2
View File
@@ -27,7 +27,19 @@
article.classList.add('council__article--active');
}
document.querySelectorAll('[data-council-article]').forEach(article => {
function positionTooltip(button, tip) {
const rect = button.getBoundingClientRect();
tip.style.left = `${Math.max(12, Math.min(rect.left, innerWidth - tip.offsetWidth - 12))}px`;
tip.style.top = `${Math.max(12, rect.bottom + tip.offsetHeight + 8 < innerHeight ? rect.bottom + 8 : rect.top - tip.offsetHeight - 8)}px`;
}
function repositionTooltips() {
document.querySelectorAll('[data-warning]').forEach(warning => {
const tip = warning.querySelector('[role="tooltip"]');
if (!tip.hidden) positionTooltip(warning.querySelector('button'), tip);
});
}
function setupArticles(root) {
root.querySelectorAll('[data-council-article]').forEach(article => {
article.addEventListener('click', event => {
if (!event.target.closest('a, button')) activate(article);
});
@@ -40,7 +52,7 @@
});
});
document.querySelectorAll('[data-council-edit]').forEach(button => {
root.querySelectorAll('[data-council-edit]').forEach(button => {
button.addEventListener('click', () => {
trigger = button;
selected = JSON.parse(button.dataset.article);
@@ -64,6 +76,71 @@
});
});
root.querySelectorAll('[data-warning]').forEach(warning => {
const button = warning.querySelector('button');
const tip = warning.querySelector('[role="tooltip"]');
let pinned = false;
function show(visible) {
tip.hidden = !visible;
button.setAttribute('aria-expanded', String(visible));
if (!visible) return;
positionTooltip(button, tip);
}
warning.addEventListener('mouseenter', () => show(true));
warning.addEventListener('mouseleave', () => { if (!pinned && document.activeElement !== button) show(false); });
button.addEventListener('focus', () => show(true));
button.addEventListener('blur', () => { pinned = false; show(false); });
button.addEventListener('click', () => { pinned = !pinned; show(pinned); });
warning.addEventListener('council-tooltip-close', () => { pinned = false; show(false); });
});
}
setupArticles(document);
document.addEventListener('keydown', event => {
if (event.key !== 'Escape') return;
document.querySelectorAll('[data-warning] button[aria-expanded="true"]').forEach(button => {
button.closest('[data-warning]').dispatchEvent(new Event('council-tooltip-close'));
});
});
async function loadArticles(details) {
if (details.dataset.loaded || details.dataset.loading) return;
const panel = details.querySelector('[data-council-content]');
const status = panel.querySelector('[data-articles-status]');
const content = panel.querySelector('[data-articles-content]');
details.dataset.loading = '1';
panel.setAttribute('aria-busy', 'true');
status.textContent = 'Загружаем публикации…';
try {
const response = await fetch(panel.dataset.articlesUrl, {credentials: 'same-origin', signal: AbortSignal.timeout(15000)});
if (!response.ok) throw new Error('Не удалось загрузить публикации. Попробуйте ещё раз.');
content.innerHTML = await response.text();
setupArticles(content);
details.dataset.loaded = '1';
status.textContent = 'Публикации загружены';
status.classList.add('council__load-status--done');
} catch (_error) {
status.textContent = 'Не удалось загрузить публикации. Проверьте подключение и повторите загрузку.';
const retry = document.createElement('button');
retry.type = 'button';
retry.className = 'button button--secondary';
retry.textContent = 'Повторить загрузку публикаций';
retry.addEventListener('click', () => loadArticles(details));
content.replaceChildren(retry);
} finally {
delete details.dataset.loading;
panel.removeAttribute('aria-busy');
}
}
document.querySelectorAll('[data-employee-id]').forEach(details => {
details.addEventListener('toggle', () => { if (details.open) loadArticles(details); });
if (details.open) loadArticles(details);
});
document.addEventListener('scroll', event => {
if (event.target instanceof Element && event.target.closest('.council__tooltip')) return;
repositionTooltips();
}, true);
window.addEventListener('resize', repositionTooltips);
dialog.querySelectorAll('[data-edit-close]').forEach(button => {
button.addEventListener('click', () => { if (!saving) dialog.close(); });
});
+15
View File
@@ -0,0 +1,15 @@
(() => {
const required = document.querySelector('[data-required-password]');
if (required) {
const form = document.querySelector('[data-password-form]');
required.querySelector('[data-password-dialog-body]').append(form);
required.addEventListener('cancel', event => event.preventDefault());
required.showModal();
(form.querySelector('[aria-invalid="true"]') || form.querySelector('input[type="password"]')).focus();
}
document.querySelectorAll('[data-password-reset]').forEach(form => {
form.addEventListener('submit', event => {
if (!window.confirm('Сбросить пароль? Текущие сессии пользователя завершатся. При следующем входе потребуется сменить временный пароль.')) event.preventDefault();
});
});
})();
+35
View File
@@ -0,0 +1,35 @@
{% extends "base.html" %}
{% block title %}Личный кабинет · MIEM Employees{% endblock %}
{% block content %}
<section class="panel users">
<h2 class="panel__title">Личный кабинет</h2>
<p>{{ account_user.full_name or account_user.username }} · {{ 'Администратор' if account_user.role == 'admin' else 'Пользователь' }}</p>
<dl class="users__account-meta"><div><dt>Первый вход</dt><dd>{{ account_user.first_login_at|admin_datetime }}</dd></div><div><dt>Последний вход</dt><dd>{{ account_user.last_login_at|admin_datetime }}</dd></div><div><dt>Пароль изменён</dt><dd>{{ account_user.password_changed_at|admin_datetime }}</dd></div></dl>
{% if password_changed %}<p role="status">Пароль изменён. Другие сессии завершены.</p>{% endif %}
</section>
<section class="panel users">
<h2 class="panel__title">Сменить пароль</h2>
<p class="users__hint">Смена пароля или выход из системы завершает все ваши сессии.</p>
<form class="form users__password-form" method="post" action="/admin/account/password" data-password-form>
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
{% if error %}<p class="users__error" id="password-error" role="alert">{{ error }}</p>{% endif %}
<label class="form__label">Текущий пароль<input class="form__input" name="current_password" type="password" required maxlength="1024" autocomplete="current-password"{% if error_field == 'current_password' %} aria-invalid="true" aria-describedby="password-error"{% endif %}></label>
<label class="form__label">Новый пароль<input class="form__input" name="new_password" type="password" required minlength="15" maxlength="128" autocomplete="new-password" aria-describedby="password-hint{% if error_field == 'new_password' %} password-error{% endif %}"{% if error_field == 'new_password' %} aria-invalid="true"{% endif %}></label>
<label class="form__label">Повторите новый пароль<input class="form__input" name="confirmation" type="password" required minlength="15" maxlength="128" autocomplete="new-password"{% if error_field == 'confirmation' %} aria-invalid="true" aria-describedby="password-error"{% endif %}></label>
<p class="users__hint" id="password-hint">От 15 до 128 символов. Можно использовать фразу. Новый пароль должен отличаться от текущего.</p>
<button class="button" type="submit">Сохранить новый пароль</button>
</form>
</section>
<section class="panel users"><h2 class="panel__title">Последние действия</h2>{% include 'user_activity.html' %}</section>
{% if account_user.must_change_password %}
<dialog class="columns-modal" data-required-password aria-labelledby="required-password-title" aria-describedby="required-password-note">
<div class="columns-modal__panel">
<h2 class="columns-modal__title" id="required-password-title">Смените временный пароль</h2>
<p id="required-password-note">Прежде чем пользоваться учётной записью, задайте свой пароль. Закрыть это окно без смены пароля нельзя.</p>
<div data-password-dialog-body></div>
<form method="post" action="/admin/logout"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="button button--ghost" type="submit">Выйти из системы</button></form>
</div>
</dialog>
{% endif %}
{% endblock %}
{% block scripts %}<script src="/static/users.js?v={{ frontend_version }}" defer></script>{% endblock %}
+6 -3
View File
@@ -11,16 +11,19 @@
<header class="admin__header">
<h1 class="admin__brand"><a class="admin__brand-link" href="{{ '/admin/council' if public_page else '/admin' }}">MIEM Employees</a></h1>
<nav class="admin__nav">
{% if public_page %}
{% if public_page and not current_user %}
<a class="admin__link" href="/admin/council" aria-current="page">Диссертационный совет</a>
<a class="admin__link" href="/admin/login">Вход в админку</a>
<a class="admin__link" href="/admin/login">Вход в систему</a>
{% else %}
<a class="admin__link" href="/admin"{% if request.url.path == "/admin" %} aria-current="page"{% endif %}>Обзор</a>
<a class="admin__link" href="/admin/directory"{% if request.url.path == "/admin/directory" %} aria-current="page"{% endif %}>Сотрудники</a>
<a class="admin__link" href="/admin/council"{% if request.url.path == "/admin/council" %} aria-current="page"{% endif %}>Диссертационный совет</a>
<a class="admin__link" href="/admin/runs"{% if request.url.path.startswith("/admin/runs") %} aria-current="page"{% endif %}>Запуски</a>
{% if current_user and current_user.role == 'admin' %}<a class="admin__link" href="/admin/users"{% if request.url.path == '/admin/users' %} aria-current="page"{% endif %}>Пользователи</a>{% endif %}
<a class="admin__link" href="/admin/account"{% if request.url.path == '/admin/account' %} aria-current="page"{% endif %}>Личный кабинет</a>
<form method="post" action="/admin/logout">
<button class="button button--ghost" type="submit">Выйти</button>
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="button button--ghost" type="submit" title="Завершить все сессии учётной записи">Выйти</button>
</form>
{% endif %}
</nav>
+4 -41
View File
@@ -89,47 +89,10 @@
</span>
<span class="council__candidate-cue" aria-hidden="true"></span>
</summary>
<div class="council__candidate-body">
<p><strong>{{ candidate.assessment_status }}</strong>. Текущая степень: {{ candidate.selected_degree or 'не установлена' }}; документальное подтверждение: {{ 'есть' if candidate.degree_confirmed else 'нет' }}.</p>
<p>Подтверждено: {{ candidate.confirmed_count }} · Предварительно: {{ candidate.total_count }} · К2: {{ candidate.k2_count }} · RSCI: {{ candidate.rsci_count }}</p>
{% if candidate.assessment_reasons %}<ul class="council__evidence" aria-label="Причины проверки">{% for reason in candidate.assessment_reasons %}{% if not reason.startswith("Подтверждено ") %}<li>{{ reason }}</li>{% endif %}{% endfor %}</ul>{% endif %}
{% if not candidate.articles %}<p class="council__hint">Доступных публикаций нет. Это не доказывает отсутствие работ сотрудника.</p>{% endif %}
{% if specialty %}<p class="council__hint">Публикаций по выбранной специальности: {{ candidate.specialty_count }}</p>{% endif %}
{% if candidate.profile_url %}<a class="admin__link" href="{{ candidate.profile_url }}" target="_blank" rel="noopener noreferrer">Профиль на сайте ВШЭ</a>{% endif %}
{% if candidate.ambiguous %}<p class="council__hint">Есть сотрудники с одинаковым ФИО. Публикации из данных ВШЭ не присвоены автоматически; показаны записи из личного кабинета этого сотрудника.</p>{% endif %}
<ol class="council__articles">
{% for article in candidate.articles %}
<li class="council__article" tabindex="0" data-council-article aria-label="{{ article.title }}. Нажмите, чтобы показать редактирование">
{% set employee_id = candidate.employee_id %}
{% include "council_edit_button.html" %}
<div class="council__article-heading">
<strong>{{ article.title }}</strong>
<span>{{ article.year or 'Год не указан' }}</span>
</div>
<div class="council__article-meta">
{% for origin in article.origins %}<span class="council__source">{{ origin }}</span>{% endfor %}
<span>{{ article.type_label }}</span>
{% if article.doi_url %}<a class="admin__link" href="{{ article.doi_url }}" target="_blank" rel="noopener noreferrer">DOI</a>{% endif %}
{% if article.url %}<a class="admin__link" href="{{ article.url }}" target="_blank" rel="noopener noreferrer">Публикация на сайте</a>{% endif %}
{% if article.rows %}<span>Строки выгрузки ВШЭ: {{ article.rows|join(', ') }}</span>{% endif %}
</div>
<p class="council__hint">Журнал: {{ article.journals|join(" / ") or "не указан" }} · Квартиль: {{ article.edit_quartile or "не указан или неоднозначен" }}</p>
<ul class="council__evidence" aria-label="Критерии и подтверждения">
<li>Зачёт в подтверждённое число: {{ 'да' if article.confirmed else 'требует проверки' }}{% if article.publication_date %}; точная дата: {{ article.publication_date.strftime('%d.%m.%Y') }}{% endif %}</li>
{% if specialty %}<li>{{ article.thematic_status }}</li>{% endif %}
{% for message in article.messages %}<li>{{ message }}</li>{% endfor %}
{% for basis in article.confirmed_bases %}<li>{{ basis.basis }} · {{ basis.system or 'издание' }} · {{ basis.category or '' }} · {{ basis.metric or '' }} · применимо к {{ basis.applicable_year }} · {{ basis.source }}{% if basis.source_url %} <a class="admin__link" href="{{ basis.source_url }}" target="_blank" rel="noopener noreferrer">Источник</a>{% endif %}</li>{% endfor %}
{% for record in article.catalog_records %}
<li>{{ record.name }} · {{ record.id }} · ISSN {{ record.issn or '—' }} / {{ record.eissn or '—' }} · {{ record.catalog }}
<ul>{% for metric in record.metrics %}<li>{{ metric.system }} · {{ metric.metric }} · {{ metric.category }}{% if metric.edition %} ({{ metric.edition }}){% endif %} · {{ metric.quartile }} · год метрики {{ metric.year }}{% if metric.release_year %}, выпуск {{ metric.release_year }}{% endif %} · {{ metric.source }}{% if metric.source_row %}, строка {{ metric.source_row }}{% endif %}{% if metric.source_pdf_page %}, страница {{ metric.source_pdf_page }}{% endif %}{% if metric.source_url %} <a class="admin__link" href="{{ metric.source_url }}" target="_blank" rel="noopener noreferrer">Источник</a>{% endif %}</li>{% endfor %}
{% for text in record.thematic %}<li>{{ text }}</li>{% endfor %}
{% for url in record.passport_urls %}{% if url %}<li><a class="admin__link" href="{{ url }}" target="_blank" rel="noopener noreferrer">Паспорт специальности</a></li>{% endif %}{% endfor %}</ul>
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ol>
<div class="council__candidate-body" data-council-content
data-articles-url="/admin/council/employees/{{ candidate.employee_id }}/articles?specialty={{ specialty|urlencode }}&amp;branch={{ branch|urlencode }}">
<p class="council__hint" role="status" data-articles-status>Публикации загрузятся при раскрытии карточки.</p>
<div data-articles-content><noscript><a class="admin__link" href="/admin/council/employees/{{ candidate.employee_id }}/articles?specialty={{ specialty|urlencode }}&amp;branch={{ branch|urlencode }}">Открыть публикации сотрудника</a></noscript></div>
</div>
</details>
{% endfor %}
@@ -0,0 +1,38 @@
<p><strong>{{ candidate.assessment_status }}</strong>. Текущая степень: {{ candidate.selected_degree or 'не установлена' }}; документальное подтверждение: {{ 'есть' if candidate.degree_confirmed else 'нет' }}.</p>
<p>Подтверждено: {{ candidate.confirmed_count }} · Предварительно: {{ candidate.total_count }} · К2: {{ candidate.k2_count }} · RSCI: {{ candidate.rsci_count }}</p>
{% if candidate.assessment_reasons %}<ul class="council__evidence" aria-label="Причины проверки">{% for reason in candidate.assessment_reasons %}{% if not reason.startswith("Подтверждено ") %}<li>{{ reason }}</li>{% endif %}{% endfor %}</ul>{% endif %}
{% if not candidate.articles %}<p class="council__hint">Доступных публикаций нет. Это не доказывает отсутствие работ сотрудника.</p>{% endif %}
{% if specialty %}<p class="council__hint">Публикаций по выбранной специальности: {{ candidate.specialty_count }}</p>{% endif %}
{% if candidate.profile_url %}<a class="admin__link" href="{{ candidate.profile_url }}" target="_blank" rel="noopener noreferrer">Профиль на сайте ВШЭ</a>{% endif %}
{% if candidate.ambiguous %}<p class="council__hint">Есть сотрудники с одинаковым ФИО. Публикации из данных ВШЭ не присвоены автоматически; показаны записи из личного кабинета этого сотрудника.</p>{% endif %}
<ol class="council__articles">
{% for article in candidate.articles %}
<li class="council__article" tabindex="0" data-council-article aria-label="{{ article.title }}. Нажмите, чтобы показать редактирование">
{% set employee_id = candidate.employee_id %}
{% include "council_edit_button.html" %}
<div class="council__article-heading">
<strong>{{ article.title }}</strong>
<span>{{ article.year or 'Год не указан' }}{% set field = 'year' %}{% set label = 'год публикации' %}{% include 'council_warning.html' %}</span>
</div>
<div class="council__article-meta">
{% for origin in article.origins %}<span class="council__source">{{ origin }}</span>{% endfor %}
<span>{{ article.display_type }}{% set field = 'type' %}{% set label = 'тип материала' %}{% include 'council_warning.html' %}</span>
{% if article.doi_url %}<a class="admin__link" href="{{ article.doi_url }}" target="_blank" rel="noopener noreferrer">DOI</a>{% endif %}
{% if article.url %}<a class="admin__link" href="{{ article.url }}" target="_blank" rel="noopener noreferrer">Публикация на сайте</a>{% endif %}
{% if article.rows %}<span>Строки выгрузки ВШЭ: {{ article.rows|join(', ') }}</span>{% endif %}
</div>
<p class="council__hint">Журнал: {{ article.journals|join(" / ") or "не указан" }}{% set field = 'journal' %}{% set label = 'журнал' %}{% include 'council_warning.html' %}</p>
<p class="council__hint">Квартиль: {{ article.edit_quartile or "не указан или неоднозначен" }}{% set field = 'quartile' %}{% set label = 'квартиль и основание зачёта' %}{% include 'council_warning.html' %}</p>
{% if specialty %}<p class="council__hint">Специальность: {{ specialty }} — {{ specialty_name }}{% set field = 'specialty' %}{% set label = 'специальность статьи' %}{% include 'council_warning.html' %}</p>{% endif %}
<ul class="council__evidence" aria-label="Источники сведений">
{% for basis in article.confirmed_bases %}<li>{{ basis.basis }} · {{ basis.system or 'издание' }} · {{ basis.category or '' }} · {{ basis.metric or '' }} · применимо к {{ basis.applicable_year }} · {{ basis.source }}{% if basis.source_url %} <a class="admin__link" href="{{ basis.source_url }}" target="_blank" rel="noopener noreferrer">Источник</a>{% endif %}</li>{% endfor %}
{% for record in article.catalog_records %}
<li>{{ record.name }} · {{ record.id }} · ISSN {{ record.issn or '—' }} / {{ record.eissn or '—' }} · {{ record.catalog }}
<ul>{% for metric in record.metrics %}<li>{{ metric.system }} · {{ metric.metric }} · {{ metric.category }}{% if metric.edition %} ({{ metric.edition }}){% endif %} · {{ metric.quartile }} · год метрики {{ metric.year }}{% if metric.release_year %}, выпуск {{ metric.release_year }}{% endif %} · {{ metric.source }}{% if metric.source_row %}, строка {{ metric.source_row }}{% endif %}{% if metric.source_pdf_page %}, страница {{ metric.source_pdf_page }}{% endif %}{% if metric.source_url %} <a class="admin__link" href="{{ metric.source_url }}" target="_blank" rel="noopener noreferrer">Источник</a>{% endif %}</li>{% endfor %}
{% for url in record.passport_urls %}{% if url %}<li><a class="admin__link" href="{{ url }}" target="_blank" rel="noopener noreferrer">Паспорт специальности</a></li>{% endif %}{% endfor %}</ul>
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ol>
+2 -2
View File
@@ -38,8 +38,8 @@
</form>
<datalist id="council-journals">{% for name in journal_names|default([]) %}<option value="{{ name }}">{% endfor %}</datalist>
{% else %}
<p>Для редактирования статей и квартилей войдите в админку.</p>
<a class="button" href="/admin/login">Войти в админку</a>
<p>Для редактирования статей и квартилей войдите в систему.</p>
<a class="button" href="/admin/login">Войти в систему</a>
{% endif %}
</div>
</dialog>
+4 -4
View File
@@ -18,16 +18,16 @@
<div class="council__message" role="alert"><h3>Не удалось загрузить публикации</h3><p>Попробуйте ещё раз позже.</p><a class="admin__link" href="{{ request.url.path }}?{{ request.url.query }}">Повторить загрузку</a></div>
{% else %}
<p class="council__hint" role="status">Найдено статей: {{ matched }}{% if matched %} · Показаны {{ offset + 1 }}–{{ [offset + limit, matched]|min }}{% endif %}</p>
{% if not can_edit %}<p class="council__hint">Просмотр доступен без входа. Для сохранения изменений <a class="admin__link" href="/admin/login">войдите в админку</a>.</p>{% endif %}
{% if not can_edit %}<p class="council__hint">Просмотр доступен без входа. Для сохранения изменений <a class="admin__link" href="/admin/login">войдите в систему</a>.</p>{% endif %}
<ol class="council__articles council__articles--editor" start="{{ offset + 1 }}">
{% for article in articles %}
<li class="council__article" tabindex="0" data-council-article aria-label="{{ article.title }}. Нажмите, чтобы показать редактирование">
{% set employee_id = article.employee_id %}{% include "council_edit_button.html" %}
<p class="council__hint">{{ article.employee_name }}</p>
<div class="council__article-heading"><strong>{{ article.title }}</strong><span>{{ article.year or 'Год не указан' }}</span></div>
<p class="council__hint">Журнал: {{ article.journals|join(' / ') or 'не указан' }} · Квартиль: {{ article.edit_quartile or 'не указан или неоднозначен' }}</p>
<div class="council__article-heading"><strong>{{ article.title }}</strong><span>{{ article.year or 'Год не указан' }}{% set field = 'year' %}{% set label = 'год публикации' %}{% include 'council_warning.html' %}</span></div>
<p class="council__hint">{{ article.display_type }}{% set field = 'type' %}{% set label = 'тип материала' %}{% include 'council_warning.html' %}</p>
<p class="council__hint">Журнал: {{ article.journals|join(' / ') or 'не указан' }}{% set field = 'journal' %}{% set label = 'журнал' %}{% include 'council_warning.html' %} · Квартиль: {{ article.edit_quartile or 'не указан или неоднозначен' }}{% set field = 'quartile' %}{% set label = 'квартиль и основание зачёта' %}{% include 'council_warning.html' %}</p>
<p class="council__hint">Специальности журнала: {{ article.edit_specialty_codes|join(", ") or "связь не установлена" }}{% if article.manual_specialties %} · ручная связь{% endif %}</p>
{% if article.manual_review %}<p class="council__hint">Ручная корректировка · требует подтверждения</p>{% endif %}
</li>
{% else %}<li class="council__message">Статьи не найдены. Попробуйте изменить фильтры.</li>{% endfor %}
</ol>
+10
View File
@@ -0,0 +1,10 @@
{% if article.warnings[field] %}
<span class="council__warning" data-warning>
{% set warning_id = 'warning-' ~ employee_id ~ '-' ~ article.edit_key ~ '-' ~ field %}
<button class="council__warning-button" type="button" aria-label="Уточнение: {{ label }}" aria-expanded="false" aria-describedby="{{ warning_id }}">
<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 6v8"/><circle cx="12" cy="18" r=".5" fill="currentColor"/></svg>
</button>
<span class="council__tooltip" role="tooltip" id="{{ warning_id }}" hidden>{{ article.warnings[field]|unique|join('. ') }}</span>
<noscript><span>{{ article.warnings[field]|unique|join('. ') }}</span></noscript>
</span>
{% endif %}
+6 -4
View File
@@ -30,12 +30,14 @@
<div class="progress-panel__header">
<h2 class="panel__title">Прогресс парсинга</h2>
<div class="progress-panel__actions">
<form method="post" action="/admin/crawl-now">
{% if current_user and current_user.role == 'admin' %}<form method="post" action="/admin/crawl-now">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="button" type="submit">Запустить парсинг</button>
</form>
<form method="post" action="/admin/dismissed/refresh">
</form>{% endif %}
{% if current_user and current_user.role == 'admin' %}<form method="post" action="/admin/dismissed/refresh">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="button button--secondary" type="submit">Проверить уволенных</button>
</form>
</form>{% endif %}
</div>
</div>
{% set run = counts.current_running_run or latest_run %}
+3 -2
View File
@@ -8,9 +8,10 @@
<span class="badge {% if employee_view.status == "dismissed" %}badge--dismissed{% endif %}">{{ employee_view.status_display }}</span>
</div>
<div class="employee-card__actions">
<form method="post" action="/admin/employees/{{ employee.id }}/refresh">
{% if current_user and current_user.role == 'admin' %}<form method="post" action="/admin/employees/{{ employee.id }}/refresh">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="button button--compact" type="submit">Обновить данные</button>
</form>
</form>{% endif %}
<a class="admin__link" href="{{ employee_view.canonical_url }}">{{ employee_view.canonical_url }}</a>
</div>
</div>
+5 -3
View File
@@ -9,13 +9,15 @@
<body class="admin">
<main class="admin__main">
<section class="panel">
<h1 class="panel__title">Вход в админку</h1>
<h1 class="panel__title">Вход в систему</h1>
{% if error %}<p>{{ error }}</p>{% endif %}
<form class="form" method="post" action="/admin/login">
<label class="form__label">Логин <input class="form__input" name="username" autocomplete="username"></label>
<label class="form__label">Пароль <input class="form__input" name="password" type="password" autocomplete="current-password"></label>
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<label class="form__label">Логин <input class="form__input" name="username" required maxlength="64" autocomplete="username"></label>
<label class="form__label">Пароль <input class="form__input" name="password" type="password" required maxlength="1024" autocomplete="current-password"></label>
<button class="button" type="submit">Войти</button>
</form>
<p>Если забыли пароль, обратитесь к администратору системы.</p>
</section>
</main>
<footer class="admin__footer">
+2 -1
View File
@@ -4,7 +4,8 @@
<section class="panel">
<div class="progress-panel__header">
<h2 class="panel__title">Запуски парсинга</h2>
<form method="post" action="/admin/runs"><button class="button" type="submit">Запустить парсинг</button></form>
{% if current_user and current_user.role == 'admin' %}<form method="post" action="/admin/runs">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="button" type="submit">Запустить парсинг</button></form>{% endif %}
</div>
{% set run = runs[0] if runs else none %}
{% if run %}
+27
View File
@@ -0,0 +1,27 @@
{% macro change_value(field, value) %}
{% if field == 'specialty_codes' %}{% if value is none or not value.manual %}по справочникам{% else %}{{ value.codes|join(', ') or 'связь исключена' }}{% endif %}
{% elif field == 'role' %}{{ {'admin': 'Администратор', 'user': 'Пользователь'}.get(value, 'не задано') }}
{% elif field == 'is_active' %}{{ 'включён' if value else 'отключён' }}
{% else %}{{ value if value else 'не указано' }}{% endif %}
{% endmacro %}
{% set action_labels = {'login': 'Вход в систему', 'card_edit': 'Редактирование статьи', 'password_change': 'Смена пароля', 'password_reset': 'Сброс пароля администратором', 'user_create': 'Создание пользователя', 'user_update': 'Изменение роли или доступа'} %}
{% set field_labels = {'title': 'Название статьи', 'journal': 'Журнал', 'quartile': 'Квартиль', 'specialty_codes': 'Специальности журнала', 'role': 'Роль', 'is_active': 'Доступ'} %}
<div class="users__table-wrap">
<table class="table users__history-table">
<thead><tr><th class="table__head" scope="col">Когда</th><th class="table__head" scope="col">Кто</th><th class="table__head" scope="col">Действие</th><th class="table__head" scope="col">Что изменено</th></tr></thead>
<tbody>{% for action in actions %}<tr class="table__row">
<td class="table__cell">{{ action.created_at|admin_datetime }}</td>
<td class="table__cell">{{ user_names.get(action.user_id, '—') }}</td>
<td class="table__cell">{{ action_labels.get(action.action, action.action) }}{% if action.target_user_id %}<br>{{ user_names.get(action.target_user_id, '') }}{% endif %}</td>
<td class="table__cell">{% if action.employee_name %}<a class="admin__link" href="/admin/council?q={{ action.employee_name|urlencode }}">{{ action.employee_name }}</a><br>{{ action.article_title }}{% if action.publication_year %} · {{ action.publication_year }}{% endif %}{% endif %}
{% for field, change in action.changes.items() %}<div class="users__change"><strong>{{ field_labels.get(field, field) }}:</strong> {{ change_value(field, change.before) }} → {{ change_value(field, change.after) }}</div>{% endfor %}
{% if not action.changes and not action.employee_name %}—{% endif %}
</td>
</tr>{% else %}<tr><td class="table__cell" colspan="4">Действий пока нет. Здесь появятся входы, смена пароля и редактирование карточек.</td></tr>{% endfor %}</tbody>
</table>
</div>
{% if history_total > history_limit %}<nav class="directory__pagination" aria-label="История действий">
{% if history_offset > 0 %}<a class="admin__link" href="?{% if selected_user|default(none) %}user_id={{ selected_user.id }}&amp;{% endif %}offset={{ history_offset - history_limit }}">Назад</a>{% endif %}
<span>{{ history_offset // history_limit + 1 }} / {{ (history_total + history_limit - 1) // history_limit }}</span>
{% if history_offset + history_limit < history_total %}<a class="admin__link" href="?{% if selected_user|default(none) %}user_id={{ selected_user.id }}&amp;{% endif %}offset={{ history_offset + history_limit }}">Далее</a>{% endif %}
</nav>{% endif %}
+48
View File
@@ -0,0 +1,48 @@
{% extends "base.html" %}
{% block title %}Пользователи · MIEM Employees{% endblock %}
{% block content %}
<section class="panel users">
<h2 class="panel__title">Управление пользователями</h2>
<p>Пользователь может просматривать данные и редактировать карточки. Запуск парсинга и управление пользователями доступны администратору.</p>
{% if error %}<p class="users__error" role="alert">{{ error }}</p>{% endif %}
{% if temporary %}<div class="users__temporary" role="status">
<p>Временный пароль для <strong>{{ temporary.username }}</strong>. Показывается только сейчас — передайте его пользователю. При входе потребуется смена пароля.</p>
<label class="form__label">Временный пароль<input class="form__input" type="text" value="{{ temporary.password }}" readonly autocomplete="off" data-temporary-password></label>
</div>{% endif %}
<details class="users__create" open>
<summary>Создать пользователя</summary>
<form class="form users__create-form" method="post" action="/admin/users">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<label class="form__label">Логин<input class="form__input" name="username" required minlength="3" maxlength="64" pattern="[a-zA-Z0-9][a-zA-Z0-9_.-]{2,63}" autocomplete="off"></label>
<label class="form__label">Имя<input class="form__input" name="full_name" maxlength="255" autocomplete="off"></label>
<label class="form__label">Роль<select class="form__input" name="role"><option value="user">Пользователь</option><option value="admin">Администратор</option></select></label>
<p class="users__hint">Логин: 3–64 латинских буквы, цифры, точки, дефисы или подчёркивания. Временный пароль из 8 символов создаётся автоматически.</p>
<button class="button" type="submit">Создать пользователя</button>
</form>
</details>
<div class="users__table-wrap"><table class="table">
<thead><tr>{% for title in ['Пользователь', 'Первый вход', 'Последний вход', 'Пароль изменён', 'Временный пароль выдан', 'Роль и доступ', 'Действия'] %}<th class="table__head" scope="col">{{ title }}</th>{% endfor %}</tr></thead>
<tbody>{% for user in users %}<tr class="table__row">
<td class="table__cell"><a class="admin__link" href="?user_id={{ user.id }}">{{ user.username }}</a>{% if user.full_name %}<br>{{ user.full_name }}{% endif %}{% if user.must_change_password %}<br>Требуется смена пароля{% endif %}{% if user.locked_until %}<br>Ограничение входа до {{ user.locked_until|admin_datetime }}{% endif %}</td>
<td class="table__cell">{{ user.first_login_at|admin_datetime if user.first_login_at else 'Ещё не входил' }}</td><td class="table__cell">{{ user.last_login_at|admin_datetime if user.last_login_at else 'Ещё не входил' }}</td>
<td class="table__cell">{{ user.password_changed_at|admin_datetime }}</td><td class="table__cell">{{ user.password_reset_at|admin_datetime }}</td>
<td class="table__cell">{% if user.id == current_user.id %}Администратор · ваша учётная запись{% else %}
<form class="users__controls" method="post" action="/admin/users/{{ user.id }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<label>Роль {{ user.username }}<select class="form__input" name="role"><option value="user"{% if user.role == 'user' %} selected{% endif %}>Пользователь</option><option value="admin"{% if user.role == 'admin' %} selected{% endif %}>Администратор</option></select></label>
<label>Доступ {{ user.username }}<select class="form__input" name="is_active"><option value="true"{% if user.is_active %} selected{% endif %}>Включён</option><option value="false"{% if not user.is_active %} selected{% endif %}>Отключён</option></select></label>
<button class="button button--secondary" type="submit">Сохранить доступ</button>
</form>{% endif %}
</td>
<td class="table__cell">{% if user.id != current_user.id %}<form method="post" action="/admin/users/{{ user.id }}/reset-password" data-password-reset>
<input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="button button--secondary" type="submit">Сбросить пароль {{ user.username }}</button>
</form>{% else %}<a class="admin__link" href="/admin/account">Сменить свой пароль</a>{% endif %}</td>
</tr>{% endfor %}</tbody>
</table></div>
</section>
<section class="panel users"><h2 class="panel__title">{% if selected_user %}Действия {{ selected_user.username }}{% else %}Последние действия пользователей{% endif %}</h2>
{% if selected_user %}<a class="admin__link" href="/admin/users">Показать всех пользователей</a>{% endif %}
{% include 'user_activity.html' %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/users.js?v={{ frontend_version }}" defer></script>{% endblock %}
+174
View File
@@ -0,0 +1,174 @@
import re
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import RedirectResponse
from sqlalchemy import desc, func, or_, select
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import Session
from app.admin import _render
from app.config import Settings, get_settings
from app.db import get_db
from app.models import SystemUser, UserAction, utcnow
from app.security import (SESSION_COOKIE, SESSION_SECONDS, check_csrf, hash_password,
require_admin, require_user, sign_session, temporary_password, verify_password)
router = APIRouter(prefix='/admin', dependencies=[Depends(check_csrf)])
def _history(db, user_id=None, offset=0):
query = select(UserAction)
if user_id is not None:
query = query.where(or_(UserAction.user_id == user_id, UserAction.target_user_id == user_id))
total = db.scalar(select(func.count()).select_from(query.subquery()))
offset = min(max(0, offset), ((total - 1) // 30) * 30) if total else 0
items = db.scalars(query.order_by(desc(UserAction.created_at), desc(UserAction.id)).offset(offset).limit(30)).all()
return {'actions': items, 'history_total': total, 'history_offset': offset, 'history_limit': 30}
def _users_page(request, db, *, user_id=None, offset=0, error=None, temporary=None, status=200):
users = db.scalars(select(SystemUser).order_by(SystemUser.username)).all()
selected = next((u for u in users if u.id == user_id), None)
if user_id is not None and selected is None:
raise HTTPException(404, 'Пользователь не найден')
response = _render(request, 'users.html', {'users': users, 'selected_user': selected,
'user_names': {u.id: u.username for u in users}, 'error': error, 'temporary': temporary,
**_history(db, user_id, offset)}, status_code=status)
response.headers['Cache-Control'] = 'no-store'
return response
def _lock_admin(request, db, settings):
# Serialize role/availability changes so concurrent admins cannot disable each other.
db.scalars(select(SystemUser).order_by(SystemUser.id).with_for_update()
.execution_options(populate_existing=True)).all()
return require_admin(request, settings, db)
@router.get('/users')
def users(request: Request, user_id: int | None = None, offset: int = 0,
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
require_admin(request, settings, db)
return _users_page(request, db, user_id=user_id, offset=offset)
@router.post('/users')
def create_user(request: Request, username: str = Form(..., max_length=64), full_name: str = Form('', max_length=255),
role: str = Form('user'), db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
actor = require_admin(request, settings, db)
username = username.strip().casefold()
if not re.fullmatch(r'[a-z0-9][a-z0-9_.-]{2,63}', username) or role not in {'admin', 'user'}:
return _users_page(request, db, error='Логин: 3–64 латинских буквы, цифры, точки, дефисы или подчёркивания. Выберите одну из двух ролей', status=422)
try:
actor = _lock_admin(request, db, settings)
password = temporary_password()
user = SystemUser(username=username, full_name=full_name.strip(), role=role,
password_hash=hash_password(password), password_reset_at=utcnow())
db.add(user)
db.flush()
db.add(UserAction(user_id=actor.id, action='user_create', target_user_id=user.id,
changes={'role': {'before': None, 'after': role}}))
db.commit()
except IntegrityError:
db.rollback()
return _users_page(request, db, error='Этот логин уже занят. Выберите другой', status=409)
except SQLAlchemyError:
db.rollback()
return _users_page(request, db, error='Не удалось создать пользователя. Попробуйте ещё раз', status=503)
return _users_page(request, db, temporary={'username': user.username, 'password': password})
@router.post('/users/{user_id}/reset-password')
def reset_password(user_id: int, request: Request, db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
actor = require_admin(request, settings, db)
try:
actor = _lock_admin(request, db, settings)
user = db.get(SystemUser, user_id)
if user is None:
raise HTTPException(404, 'Пользователь не найден')
if user.id == actor.id:
raise HTTPException(422, 'Свой пароль измените в личном кабинете')
password = temporary_password()
user.password_hash = hash_password(password)
user.must_change_password = True
user.password_reset_at = utcnow()
user.session_version += 1
user.failed_login_attempts = 0
user.locked_until = None
db.add(UserAction(user_id=actor.id, action='password_reset', target_user_id=user.id))
db.commit()
except SQLAlchemyError:
db.rollback()
return _users_page(request, db, error='Не удалось сбросить пароль. Попробуйте ещё раз', status=503)
return _users_page(request, db, temporary={'username': user.username, 'password': password})
@router.post('/users/{user_id}')
def update_user(user_id: int, request: Request, role: str = Form(...), is_active: str = Form(...),
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
actor = require_admin(request, settings, db)
if role not in {'admin', 'user'} or is_active not in {'true', 'false'}:
raise HTTPException(422, 'Выберите роль и состояние доступа')
try:
actor = _lock_admin(request, db, settings)
user = db.get(SystemUser, user_id)
if user is None:
raise HTTPException(404, 'Пользователь не найден')
if user.id == actor.id:
raise HTTPException(422, 'Собственную роль и доступ изменить нельзя')
changes = {}
for field, value in (('role', role), ('is_active', is_active == 'true')):
old = getattr(user, field)
if old != value:
changes[field] = {'before': old, 'after': value}
setattr(user, field, value)
if changes:
user.session_version += 1
db.add(UserAction(user_id=actor.id, action='user_update', target_user_id=user.id, changes=changes))
db.commit()
except SQLAlchemyError:
db.rollback()
return _users_page(request, db, error='Не удалось изменить доступ. Попробуйте ещё раз', status=503)
return RedirectResponse('/admin/users', status_code=303)
@router.get('/account')
def account(request: Request, offset: int = 0, db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
user = require_user(request, settings, db, allow_password_change=True)
return _account_page(request, db, user, offset=offset)
def _account_page(request, db, user, *, offset=0, error=None, error_field=None, status=200):
history = _history(db, user.id, offset)
ids = {a.user_id for a in history['actions']} | {a.target_user_id for a in history['actions'] if a.target_user_id is not None}
names = dict(db.execute(select(SystemUser.id, SystemUser.username).where(SystemUser.id.in_(ids))).all()) if ids else {}
return _render(request, 'account.html', {'account_user': user, 'user_names': names, 'error': error,
'error_field': error_field, 'password_changed': request.query_params.get('password_changed') == '1', **history}, status_code=status)
@router.post('/account/password')
def change_password(request: Request, current_password: str = Form(..., max_length=1024),
new_password: str = Form(..., max_length=128), confirmation: str = Form(..., max_length=128),
db: Session = Depends(get_db), settings: Settings = Depends(get_settings)):
user = require_user(request, settings, db, allow_password_change=True, lock=True)
if not verify_password(current_password, user.password_hash):
return _account_page(request, db, user, error='Текущий пароль неверен. Введите пароль, с которым вошли', error_field='current_password', status=422)
if len(new_password) < 15 or new_password == current_password:
return _account_page(request, db, user, error='Выберите новый пароль от 15 до 128 символов, отличающийся от текущего. Можно использовать фразу', error_field='new_password', status=422)
if new_password != confirmation:
return _account_page(request, db, user, error='Новые пароли не совпадают. Повторите ввод', error_field='confirmation', status=422)
try:
user.password_hash = hash_password(new_password)
user.must_change_password = False
user.password_changed_at = utcnow()
user.session_version += 1
user.failed_login_attempts = 0
user.locked_until = None
db.add(UserAction(user_id=user.id, action='password_change'))
db.commit()
except SQLAlchemyError:
db.rollback()
return _account_page(request, db, user, error='Не удалось сохранить пароль. Попробуйте ещё раз', status=503)
response = RedirectResponse('/admin/account?password_changed=1', status_code=303)
response.set_cookie(SESSION_COOKIE, sign_session(user.username, settings, user.session_version),
httponly=True, samesite='lax', max_age=SESSION_SECONDS, secure=request.url.scheme == 'https' or request.headers.get('x-forwarded-proto') == 'https')
return response
+3 -3
View File
@@ -1,3 +1,3 @@
APP_VERSION = "1.0.1"
FRONTEND_VERSION = "1.0.1"
BACKEND_VERSION = "1.0.1"
APP_VERSION = "1.2.1"
FRONTEND_VERSION = "1.2.1"
BACKEND_VERSION = "1.2.1"
+32
View File
@@ -0,0 +1,32 @@
CREATE TABLE IF NOT EXISTS system_users (
id SERIAL PRIMARY KEY,
username VARCHAR(64) NOT NULL UNIQUE,
full_name VARCHAR(255) NOT NULL DEFAULT '',
role VARCHAR(16) NOT NULL DEFAULT 'user' CONSTRAINT ck_system_users_role CHECK (role IN ('admin', 'user')),
is_active BOOLEAN NOT NULL DEFAULT TRUE,
password_hash TEXT NOT NULL,
must_change_password BOOLEAN NOT NULL DEFAULT TRUE,
session_version INTEGER NOT NULL DEFAULT 0,
first_login_at TIMESTAMPTZ,
last_login_at TIMESTAMPTZ,
password_changed_at TIMESTAMPTZ,
password_reset_at TIMESTAMPTZ,
failed_login_attempts INTEGER NOT NULL DEFAULT 0,
locked_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS user_actions (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES system_users(id),
action VARCHAR(32) NOT NULL,
target_user_id INTEGER REFERENCES system_users(id),
employee_id INTEGER,
employee_name TEXT,
publication_year INTEGER,
publication_key VARCHAR(64),
article_title TEXT,
changes JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS ix_user_actions_user_created ON user_actions(user_id, created_at);
CREATE INDEX IF NOT EXISTS ix_user_actions_target_created ON user_actions(target_user_id, created_at);
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "miem-workers"
version = "1.0.1"
version = "1.2.1"
description = "MIEM employees parser, admin API, and web admin"
requires-python = ">=3.11"
dependencies = [
+50 -8
View File
@@ -66,8 +66,15 @@ def main():
output = Path(".impeccable/review")
output.mkdir(parents=True, exist_ok=True)
requests = {"articles": 0, "fail": False}
def serve(route):
url = urlsplit(route.request.url)
if '/council/employees/' in url.path:
requests['articles'] += 1
if requests['fail']:
route.fulfill(status=503, body='Temporary failure')
return
response = client.get(url.path + ("?" + url.query if url.query else ""))
route.fulfill(status=response.status_code, body=response.content,
headers={key: value for key, value in response.headers.items()
@@ -81,20 +88,55 @@ def main():
errors = []
page.on("pageerror", lambda error: errors.append(str(error)))
page.goto("http://miem.test/admin/council")
expect(page.get_by_role("status")).to_have_text("Показаны 1–25 из 28")
expect(page.locator(".council__list-heading [role=status]")).to_have_text("Показаны 1–25 из 28")
assert "Без степени" not in page.content() and "Только звание" not in page.content()
expect(page.locator("#council-date")).to_have_count(0)
assert "Монографии" not in page.content()
page.get_by_role("button", name="Применить", exact=True).click()
expect(page.get_by_role("link", name="Вход в админку")).to_be_visible()
expect(page.get_by_role("link", name="Вход в систему")).to_be_visible()
page.get_by_role("link", name="Далее").click()
expect(page.get_by_role("status")).to_have_text("Показаны 26–28 из 28")
expect(page.locator(".council__list-heading [role=status]")).to_have_text("Показаны 26–28 из 28")
page.get_by_role("link", name="Назад").click()
summary = page.locator(".council__candidate-summary").first
assert requests['articles'] == 0
requests['fail'] = True
summary.focus()
page.keyboard.press("Enter")
expect(page.get_by_role('button', name='Повторить загрузку публикаций')).to_be_visible()
requests['fail'] = False
page.get_by_role('button', name='Повторить загрузку публикаций').click()
expect(page.locator(".council__source").filter(has_text="ЛК сотрудника ВШЭ").first).to_be_visible()
expect(page.get_by_text("Q1/Q2 и К1 не подтверждены доступными данными").first).to_be_visible()
before = requests['articles']
summary.click()
summary.click()
assert requests['articles'] == before
warning = page.get_by_role('button', name='Уточнение: тип материала').first
summary.focus()
warning.hover()
expect(summary).to_be_focused()
expect(page.get_by_role('tooltip')).to_be_visible()
page.keyboard.press('Escape')
expect(page.get_by_role('tooltip')).to_have_count(0)
expect(warning).to_have_attribute('aria-expanded', 'false')
assert warning.evaluate("button => button.matches(':hover')")
expect(summary).to_be_focused()
page.mouse.move(5, 5)
warning.hover()
expect(page.get_by_role('tooltip')).to_be_visible()
expect(page.get_by_role('tooltip')).to_contain_text('тип материала')
page.screenshot(path=str(output / 'warning-desktop.png'))
page.set_viewport_size({'width': 320, 'height': 844})
warning.focus()
page.keyboard.press('Enter')
expect(page.get_by_role('tooltip')).to_be_visible()
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
page.screenshot(path=str(output / 'warning-mobile.png'))
page.keyboard.press('Escape')
expect(page.get_by_role('tooltip')).to_have_count(0)
page.set_viewport_size({'width': 1440, 'height': 1000})
page.get_by_role("button", name="Уточнение: квартиль и основание зачёта").first.click()
expect(page.get_by_role("tooltip").first).to_contain_text("Нет подтверждённого основания")
page.keyboard.press("Escape")
assert page.locator(".council__candidate").first.evaluate("e => e.open")
page.screenshot(path=str(output / "desktop.png"), full_page=True)
page.screenshot(path=str(output / "sorting-desktop.png"), full_page=False)
@@ -131,7 +173,7 @@ def main():
assert workbook["Сотрудники"]["B2"].value == "Сотрудник 27"
page.get_by_label("Поиск по ФИО").fill("Сотрудник 27")
page.get_by_role("button", name="Применить", exact=True).click()
expect(page.get_by_role("status")).to_have_text("Показаны 1–1 из 1 · Всего в списке: 28")
expect(page.locator(".council__list-heading [role=status]")).to_have_text("Показаны 1–1 из 1 · Всего в списке: 28")
expect(page.get_by_label("Сортировать по")).to_have_value("full_name")
expect(page.get_by_label("Направление")).to_have_value("desc")
with page.expect_download() as pending_download:
@@ -142,16 +184,16 @@ def main():
page.get_by_role("button", name="Применить", exact=True).click()
expect(page.get_by_text("Сотрудники не найдены", exact=True)).to_be_visible()
page.get_by_role("link", name="Сбросить поиск").first.click()
expect(page.get_by_role("status")).to_have_text("Показаны 1–25 из 28")
expect(page.locator(".council__list-heading [role=status]")).to_have_text("Показаны 1–25 из 28")
expect(page.get_by_label("Сортировать по")).to_have_value("full_name")
expect(page.get_by_label("Направление")).to_have_value("desc")
page.get_by_label("Специальность ВАК").select_option("1.2.2")
page.get_by_role("button", name="Применить", exact=True).click()
expect(page.get_by_role("status")).to_have_text("Показаны 1–1 из 1 · Всего в списке: 28")
expect(page.locator(".council__list-heading [role=status]")).to_have_text("Показаны 1–1 из 1 · Всего в списке: 28")
expect(page.locator(".council__candidate-identity strong")).to_have_text("Сотрудник 27")
page.locator(".council__candidate-summary").click()
expect(page.get_by_text("Публикаций по выбранной специальности: 1", exact=True)).to_be_visible()
expect(page.get_by_text("По специальности 1.2.2:", exact=False)).to_be_visible()
expect(page.get_by_text("Специальность: 1.2.2", exact=False).first).to_be_visible()
for width in (1440, 768, 390, 320):
page.set_viewport_size({"width": width, "height": 900})
assert page.evaluate("document.documentElement.scrollWidth <= innerWidth"), width
+5 -5
View File
@@ -73,7 +73,7 @@ def main():
expect(pencil).to_be_visible()
pencil.click()
expect(page.get_by_role('dialog')).to_be_visible()
expect(page.get_by_role('link', name='Войти в админку', exact=True)).to_be_visible()
expect(page.get_by_role('link', name='Войти в систему', exact=True)).to_be_visible()
page.keyboard.press('Escape')
expect(pencil).to_be_focused()
client.cookies.set(SESSION_COOKIE, sign_session('admin', settings))
@@ -86,7 +86,7 @@ def main():
expect(page.get_by_label('Название статьи', exact=True)).to_have_value('Исследование передачи данных')
page.get_by_label('Название статьи', exact=True).fill('Уточнённое исследование')
page.get_by_label('Название журнала', exact=True).fill('Новый журнал')
page.get_by_label('Квартиль').select_option('Q1')
page.get_by_role('dialog').get_by_label('Квартиль').select_option('Q1')
page.screenshot(path=str(output / 'edit-desktop.png'))
page.set_viewport_size({'width': 320, 'height': 844})
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
@@ -112,12 +112,12 @@ def main():
window.screenshot(path=str(output / f'list-{width}.png'), full_page=True)
window.locator('[data-council-article] strong').click()
window.locator('[data-council-edit]').click()
window.get_by_label('Квартиль').select_option('Q2')
window.get_by_role('dialog').get_by_label('Квартиль').select_option('Q2')
window.locator('[data-edit-specialties] summary').click()
window.get_by_label('Использовать связь из справочников').uncheck()
window.locator('[name="specialty_codes"][value="1.2.2"]').check()
window.get_by_role('button', name='Сохранить', exact=True).click()
expect(window.get_by_text('Журнал: Новый журнал · Квартиль: Q2', exact=True)).to_be_visible()
expect(window.get_by_text('Журнал: Новый журнал · Квартиль: Q2', exact=False)).to_be_visible()
expect(window.get_by_text('Специальности журнала: 1.2.2 · ручная связь', exact=True)).to_be_visible()
# The original tab now carries a stale revision.
article.locator('strong').click()
@@ -127,7 +127,7 @@ def main():
page.keyboard.press('Escape')
page.reload()
page.locator('.council__candidate-summary').click()
expect(page.get_by_text('Журнал: Новый журнал · Квартиль: Q2', exact=True)).to_be_visible()
expect(page.get_by_text('Квартиль: Q2', exact=False)).to_be_visible()
page.get_by_label('Отрасль оценки').select_option('физико-математические')
page.get_by_role('button', name='Применить', exact=True).click()
expect(page.get_by_label('Отрасль оценки')).to_have_value('физико-математические')
+146
View File
@@ -0,0 +1,146 @@
"""Offline users/roles/password/audit browser scenario; synthetic SQLite data only."""
import os
from pathlib import Path
import sys
import socket
import threading
import time
import uvicorn
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from playwright.sync_api import expect, sync_playwright
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.config import Settings, get_settings
from app.db import Base, get_db
from app.main import app
from app.models import Employee, EmployeePublication, utcnow
from app.security import ensure_bootstrap_admin
from app.services import council
def main():
engine = create_engine('sqlite://', connect_args={'check_same_thread': False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
factory = sessionmaker(bind=engine)
settings = Settings(_env_file=None, admin_username='admin', admin_password='Browser initial admin', session_secret='browser-users-secret')
with factory() as db:
admin = ensure_bootstrap_admin(db, settings)
admin.first_login_at = utcnow()
employee = Employee(profile_key='browser-users', full_name='Сотрудник для проверки', canonical_url='https://www.hse.ru/staff/test',
current_data={'sections': [{'title': 'Учёные степени', 'items': ['Доктор технических наук']}]})
db.add(employee)
db.flush()
db.add(EmployeePublication(employee_id=employee.id, title='Статья для проверки', year=2024, publication_type='ARTICLE',
source_hash='browser-users', raw_data={'journal': 'Журнал для проверки'}))
db.commit()
def database():
with factory() as db:
yield db
original = council._articles_by_author
council._articles_by_author = lambda: {}
app.dependency_overrides[get_db] = database
app.dependency_overrides[get_settings] = lambda: settings
output = Path('.impeccable/review/users')
output.mkdir(parents=True, exist_ok=True)
listener = socket.socket()
listener.bind(('127.0.0.1', 0))
server = uvicorn.Server(uvicorn.Config(app, lifespan='off', access_log=False, log_level='critical'))
thread = threading.Thread(target=server.run, kwargs={'sockets': [listener]}, daemon=True)
thread.start()
for _ in range(1000):
if server.started:
break
time.sleep(.01)
assert server.started
base_url = f'http://127.0.0.1:{listener.getsockname()[1]}'
try:
with sync_playwright() as playwright:
browser = playwright.chromium.launch(executable_path=os.getenv('BROWSER_EXECUTABLE'))
context = browser.new_context(viewport={'width':1440,'height':1000})
page = context.new_page()
errors = []
page.on('pageerror', lambda error: errors.append(str(error)))
page.goto(base_url + '/admin/login')
page.get_by_label('Логин', exact=True).fill('admin')
page.get_by_label('Пароль', exact=True).fill('Browser initial admin')
page.get_by_role('button', name='Войти', exact=True).click()
expect(page.get_by_role('link', name='Пользователи', exact=True)).to_be_visible()
page.get_by_role('link', name='Пользователи', exact=True).click()
creation = page.locator('form[action="/admin/users"]')
creation.get_by_label('Логин', exact=True).fill('reader')
creation.get_by_label('Имя', exact=True).fill('Тестовый читатель')
creation.get_by_role('button', name='Создать пользователя', exact=True).click()
temporary = page.locator('[data-temporary-password]')
expect(temporary).to_be_visible()
password = temporary.input_value()
page.screenshot(path=str(output/'users-desktop.png'), mask=[temporary], full_page=True)
page.set_viewport_size({'width':320,'height':844})
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
page.screenshot(path=str(output/'users-mobile.png'), mask=[temporary], full_page=True)
page.get_by_role('button', name='Выйти', exact=True).click()
page.goto(base_url + '/admin/login')
page.get_by_label('Логин', exact=True).fill('reader')
page.get_by_label('Пароль', exact=True).fill(password)
page.get_by_role('button', name='Войти', exact=True).click()
modal = page.get_by_role('dialog', name='Смените временный пароль')
expect(modal).to_be_visible()
page.keyboard.press('Escape')
expect(modal).to_be_visible()
expect(modal.get_by_label('Текущий пароль', exact=True)).to_be_focused()
assert modal.evaluate('node => node.scrollWidth <= node.clientWidth')
page.screenshot(path=str(output/'required-mobile.png'))
page.set_viewport_size({'width':1440,'height':1000})
page.screenshot(path=str(output/'required-desktop.png'))
modal.get_by_label('Текущий пароль', exact=True).fill(password)
modal.get_by_label('Новый пароль', exact=True).fill('Reader personal passphrase 123')
modal.get_by_label('Повторите новый пароль', exact=True).fill('Reader personal passphrase 123')
modal.get_by_role('button', name='Сохранить новый пароль', exact=True).click()
expect(page.get_by_role('dialog')).to_have_count(0)
expect(page.get_by_text('Пароль изменён. Другие сессии завершены.', exact=True)).to_be_visible()
expect(page.get_by_role('link', name='Пользователи', exact=True)).to_have_count(0)
page.get_by_role('link', name='Обзор', exact=True).click()
expect(page.get_by_role('button', name='Запустить парсинг', exact=True)).to_have_count(0)
page.get_by_role('link', name='Диссертационный совет', exact=True).click()
page.locator('.council__candidate-summary').click()
article = page.locator('[data-council-article]')
article.focus()
page.keyboard.press('Enter')
page.keyboard.press('Enter')
editor = page.get_by_role('dialog', name='Редактирование статьи')
editor.get_by_label('Название статьи', exact=True).fill('Статья изменена читателем')
editor.get_by_role('button', name='Сохранить', exact=True).click()
expect(article.locator('strong')).to_have_text('Статья изменена читателем')
page.get_by_role('link', name='Личный кабинет', exact=True).click()
expect(page.get_by_text('Редактирование статьи', exact=True)).to_be_visible()
expect(page.get_by_text('Статья изменена читателем', exact=False)).to_be_visible()
page.screenshot(path=str(output/'account-desktop.png'), full_page=True)
page.set_viewport_size({'width':320,'height':844})
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
page.screenshot(path=str(output/'account-mobile.png'), full_page=True)
page.get_by_role('button', name='Выйти', exact=True).click()
page.goto(base_url + '/admin/login')
page.get_by_label('Логин', exact=True).fill('admin')
page.get_by_label('Пароль', exact=True).fill('Browser initial admin')
page.get_by_role('button', name='Войти', exact=True).click()
page.get_by_role('link', name='Пользователи', exact=True).click()
page.once('dialog', lambda dialog: dialog.accept())
page.get_by_role('button', name='Сбросить пароль reader', exact=True).click()
expect(page.locator('[data-temporary-password]')).to_be_visible()
page.locator('[data-temporary-password]').evaluate("input => input.value = '[скрыто]'")
expect(page.locator('.table__cell').filter(has_text='Требуется смена пароля')).to_be_visible()
assert not errors, errors
browser.close()
finally:
server.should_exit = True
thread.join(timeout=5)
listener.close()
council._articles_by_author = original
app.dependency_overrides.clear()
engine.dispose()
print(f'Users browser scenario passed; screenshots: {output}')
if __name__ == '__main__':
main()
+4 -3
View File
@@ -11,14 +11,14 @@ from app.config import Settings, get_settings
from app.db import Base, get_db
from app.main import app
from app.models import CrawlRun, CrawlRunEmployeeChange, Employee
from app.security import SESSION_COOKIE, sign_session
from app.security import SESSION_COOKIE, sign_session, _session_data
def test_health_returns_versions():
response = TestClient(app).get("/api/health")
assert response.status_code == 200
assert response.json()["backend_version"] == "1.0.1"
assert response.json()["backend_version"] == "1.2.1"
def test_api_employees_and_stats_require_admin_session():
@@ -127,7 +127,8 @@ def test_admin_refresh_employee_route_updates_only_requested_employee(monkeypatc
client = TestClient(app)
client.cookies.set(SESSION_COOKIE, sign_session("admin", settings))
response = client.post(f"/admin/employees/{employee_id}/refresh", follow_redirects=False)
csrf = _session_data(client.cookies.get(SESSION_COOKIE), settings)["csrf"]
response = client.post(f"/admin/employees/{employee_id}/refresh", headers={"X-CSRF-Token": csrf}, follow_redirects=False)
assert response.status_code == 303
assert response.headers["location"] == f"/admin/employees/{employee_id}?refresh_status=success"
+71 -5
View File
@@ -215,12 +215,16 @@ def test_public_page_data_minimization_and_safe_links(db_session, export):
assert "Иванов Иван Иванович" in response.text and "Доктор технических наук" in response.text
assert "Используется высшая обнаруженная степень; её документальное подтверждение проверяется отдельно." in response.text
assert "CSV по критериям" not in response.text and "ВСЕГО" in response.text and "Все публикации" in response.text
assert "Книга" in response.text and "Тип не указан" in response.text
assert "&lt;script&gt;" in response.text and "<script>" not in response.text
assert 'class="council__article"' not in response.text
fragment = client.get(f"/admin/council/employees/{person.id}/articles")
assert fragment.status_code == 200
assert "Книга" in fragment.text and "не указан тип материала" in fragment.text
assert "&lt;script&gt;" in fragment.text and "<script>" not in fragment.text
assert "javascript:" not in fragment.text and "private@example.org" not in fragment.text
assert "javascript:" not in response.text and "private@example.org" not in response.text
assert "/admin/employees/" not in response.text and "/admin/logout" not in response.text
assert "Backend 1.0.1 · Frontend 1.0.1" in response.text
assert "Вход в админку" in response.text
assert "Backend 1.2.1 · Frontend 1.2.1" in response.text
assert "Вход в систему" in response.text
assert client.get("/admin/directory", follow_redirects=False).status_code in (302, 303, 401, 403)
assert "Сотрудники не найдены" in client.get("/admin/council?q=missing").text
finally:
@@ -499,7 +503,7 @@ def test_specialty_page_pagination_search_and_export_agree(db_session, export):
assert response.status_code == 200
assert '<option value="1.2.2" selected>' in response.text
assert response.text.count('<option value="2.3.5"') == 1
assert "Публикаций по выбранной специальности: 1" in response.text
assert "Публикаций по выбранной специальности: 1" in client.get("/admin/council/employees/1/articles?specialty=1.2.2").text
assert "Не подходит" not in response.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
@@ -617,3 +621,65 @@ def test_xlsx_compact_total_current_degree_and_normalized_criteria(db_session, e
assert 'Q1 ИЛИ Q2 ИЛИ К1' in params['Всего']
assert 'источники указаны на листе' not in ' '.join(str(v) for v in params.values())
assert not any('Работ / По выбранной специальности' == key for key in params)
def test_council_lazy_loading_selects_only_matching_publications(db_session, export, monkeypatch):
from sqlalchemy import event
first = employee(db_session, name='Первый сотрудник', key='first')
second = employee(db_session, name='Второй сотрудник', key='second')
publication(db_session, first, title='Первая статья', kind='ARTICLE')
publication(db_session, second, title='Вторая статья', kind='ARTICLE')
db_session.commit()
parsed = []
original = council._database_article
def tracked(publication):
parsed.append(publication.employee_id)
return original(publication)
monkeypatch.setattr(council, '_database_article', tracked)
result = council.council_candidates(db_session, q='первый')
assert result['total'] == 2 and result['matched'] == 1
assert parsed == [first.id]
parsed.clear()
statements = []
def sql(connection, cursor, statement, parameters, context, executemany):
statements.append(statement)
event.listen(db_session.bind, 'before_cursor_execute', sql)
try:
result = council.council_candidates(db_session, q='нет совпадений')
assert result['total'] == 2 and result['matched'] == 0
assert not any('employee_publications' in statement for statement in statements)
finally:
event.remove(db_session.bind, 'before_cursor_execute', sql)
assert parsed == []
app.dependency_overrides[get_db] = lambda: db_session
try:
client = TestClient(app)
page = client.get('/admin/council')
assert 'data-articles-url' in page.text and 'class="council__article"' not in page.text
detail = client.get(f'/admin/council/employees/{first.id}/articles')
assert detail.status_code == 200
assert 'Первая статья' in detail.text and 'Вторая статья' not in detail.text
assert parsed == [first.id, second.id, first.id]
assert client.get('/admin/council/employees/99999/articles').status_code == 404
assert client.get(f'/admin/council/employees/{first.id}/articles?specialty=wrong').status_code == 422
finally:
app.dependency_overrides.clear()
def test_lazy_loading_preserves_global_duplicate_name_check(db_session, export):
export([row(author='Одно ФИО', title='Не присваивать автоматически')])
first = employee(db_session, name='Одно ФИО', key='first')
employee(db_session, name='Одно ФИО', key='second')
publication(db_session, first, title='Своя статья')
db_session.commit()
result = council.council_candidates(db_session, employee_id=first.id)
assert result['total'] == 2 and result['matched'] == 1
assert result['candidates'][0]['ambiguous']
assert [a['title'] for a in result['candidates'][0]['articles']] == ['Своя статья']
def test_plain_description_fast_path_and_html_entities():
from app.services.council_source import _description_journals
description = {'short': {'ru': ' Journal Name. 2024. № 1. ', 'en': '<b>Journal &amp; Name</b>. 2024.'},
'shortLeft': {'en': 'Journal &amp; Name. 2024.'}}
assert _description_journals(description) == ['Journal Name', 'Journal & Name', 'Journal & Name']
+18 -5
View File
@@ -373,7 +373,7 @@ def test_valid_snapshot_keeps_preliminary_metrics_when_other_is_broken(db_sessio
try:
response = TestClient(app).get("/admin/council")
assert response.status_code == 200 and "целостность каталога" in response.text
assert journal["name"] in response.text
assert journal["name"] in TestClient(app).get(f"/admin/council/employees/{employee.id}/articles").text
finally:
app.dependency_overrides.clear()
finally:
@@ -413,14 +413,16 @@ def test_automatic_quartile_identity_conflict_and_messages(db_session, proofs):
article = result(db_session)['articles'][0]
assert not article['confirmed']
assert len(article['messages']) == len(set(article['messages']))
issue = 'Журнал сохранённого квартиля и публикации расходятся — требуется перепроверка'
issue = article['warnings']['journal'][0]
assert 'Другой журнал' in issue and 'Текущий журнал' in issue
assert article['messages'].count(issue) == 1
app.dependency_overrides[get_db] = lambda: db_session
try:
response = TestClient(app).get('/admin/council')
response = TestClient(app).get(f'/admin/council/employees/{employee.id}/articles')
from bs4 import BeautifulSoup
card = BeautifulSoup(response.text, 'html.parser').select_one('li.council__article')
assert card.get_text().count(issue) == 1
assert sum(tip.get_text().count(issue) for tip in card.select('[role=tooltip]')) == 1
assert 'Зачёт в подтверждённое число' not in card.get_text()
assert 'Специальность для рассмотрения статьи не выбрана' not in card.get_text()
assert 'Пункт:' not in response.text and 'Минимум:' not in response.text
finally:
@@ -474,8 +476,19 @@ def test_automatic_quartile_categories_and_metrics_preserve_conflicts(db_session
assert candidate['q1_count'] == candidate['q2_count'] == candidate['total_count'] == 1
assert candidate['confirmed_count'] == int(expected)
article = candidate['articles'][0]
assert ('Подтверждённые основания источников расходятся' in article['confirmation_reasons']) == (not expected)
assert any(reason.startswith('Подтверждённые основания источников расходятся') for reason in article['confirmation_reasons']) == (not expected)
assert [(basis.get('category'), basis.get('metric'), basis.get('metric_year'), basis['source'], basis['source_url'])
for basis in article['automatic_quartile_bases']] == [
('Analysis', 'CiteScore', 2024, first['source'], first['source_url']),
(category, metric, 2024, second['source'], second['source_url'])]
def test_warning_display_does_not_turn_unknown_type_into_confirmed_article(db_session, proofs):
employee = person(db_session, ['Доктор технических наук'])
db_session.add(EmployeePublication(employee_id=employee.id, title='Missing kind', year=2024,
source_hash='missing', raw_data={'journal': 'Journal', 'csv_enrichment': {'Название журнала': 'Journal', 'Квартиль scopus': 'Q1'}}))
candidate = result(db_session)
article = candidate['articles'][0]
assert article['display_type'] == 'Статья' and article['types'] == []
assert article['warnings']['type'] and 'не указан тип материала' in article['warnings']['type'][0]
assert not article['confirmed'] and candidate['confirmed_count'] == 0
+3 -1
View File
@@ -61,7 +61,9 @@ def test_editor_shared_quartile_persistence_filter_and_export(editor, db_session
assert payload['title'] in response.text
assert 'Статьи не найдены' in client.get('/admin/council/publications?title=absent').text
main = client.get('/admin/council')
assert 'data-council-edit' in main.text and payload['title'] in main.text
assert 'data-council-edit' not in main.text and payload['title'] not in main.text
fragment = client.get(f"/admin/council/employees/{payload['employee_id']}/articles")
assert 'data-council-edit' in fragment.text and payload['title'] in fragment.text
from io import BytesIO
from openpyxl import load_workbook
workbook = load_workbook(BytesIO(client.get('/admin/council/export.xlsx').content))
+1 -1
View File
@@ -233,7 +233,7 @@ def test_crawler_doi_or_journal_change_excludes_preserved_quartile(new_doi, new_
article = _database_article(publication)
assert publication.quartiles == payload
assert article["quartiles"] == [] and article["quartile_issues"]
assert all("перепроверка" in issue for issue in article["quartile_issues"])
assert all("перепроверка" in issue or "Уточните журнал статьи" in issue for issue in article["quartile_issues"])
def test_updating_lookup_freezes_legacy_binding_instead_of_rebinding_old_entries():
+322
View File
@@ -0,0 +1,322 @@
import re
import os
from sqlalchemy import create_engine
from sqlalchemy.engine import make_url
from sqlalchemy.orm import sessionmaker
from app.db import Base
from datetime import timedelta
import pytest
from bs4 import BeautifulSoup
from fastapi.testclient import TestClient
from sqlalchemy import select
from app.config import Settings, get_settings
from app.db import get_db
from app.main import app
from app.models import SystemUser, UserAction, Employee, EmployeePublication, CouncilCorrections, utcnow
from app.security import (SESSION_COOKIE, _session_data, ensure_bootstrap_admin, hash_password,
sign_session, temporary_password, verify_password)
from app.services import council
@pytest.fixture()
def accounts(db_session, monkeypatch):
test_engine = None
native_url = os.getenv('USERS_TEST_DATABASE_URL')
if native_url:
assert make_url(native_url).database == 'miem_users_test', 'Use a disposable miem_users_test database only'
test_engine = create_engine(native_url)
Base.metadata.create_all(test_engine)
db_session = sessionmaker(bind=test_engine)()
settings = Settings(_env_file=None, admin_username='admin', admin_password='initial-admin-test', session_secret='users-test-secret')
admin = ensure_bootstrap_admin(db_session, settings)
user = SystemUser(username='reader', full_name='Тестовый пользователь', role='user',
password_hash=hash_password('Initial user password'), must_change_password=False,
first_login_at=utcnow())
db_session.add(user)
employee = Employee(profile_key='users:employee', canonical_url='https://www.hse.ru/staff/test', full_name='Тестовый сотрудник',
current_data={'sections': [{'title': 'Учёные степени', 'items': ['Доктор технических наук']}]})
db_session.add(employee)
db_session.flush()
db_session.add(EmployeePublication(employee_id=employee.id, title='Исходная статья', year=2024,
publication_type='ARTICLE', source_hash='users-publication', raw_data={'journal': 'Журнал'}))
db_session.commit()
monkeypatch.setattr(council, '_articles_by_author', lambda: {})
app.dependency_overrides[get_db] = lambda: db_session
app.dependency_overrides[get_settings] = lambda: settings
client = TestClient(app)
try:
yield client, db_session, settings, admin, user, employee
finally:
client.close()
app.dependency_overrides.clear()
if test_engine is not None:
db_session.close()
Base.metadata.drop_all(test_engine)
test_engine.dispose()
def act_as(client, user, settings):
client.cookies.set(SESSION_COOKIE, sign_session(user.username, settings, user.session_version))
csrf = _session_data(client.cookies.get(SESSION_COOKIE), settings)['csrf']
return {'X-CSRF-Token': csrf}
def login(client, username, password):
page = client.get('/admin/login')
csrf = BeautifulSoup(page.text, 'html.parser').select_one('[name=csrf_token]')['value']
return client.post('/admin/login', data={'username': username, 'password': password, 'csrf_token': csrf}, follow_redirects=False)
def test_password_hash_and_eight_character_generator():
for _ in range(100):
password = temporary_password()
assert len(password) == 8
assert all(re.search(pattern, password) for pattern in (r'[A-Z]', r'[a-z]', r'[0-9]', r'[!@#$%+_\-]'))
encoded = hash_password('Секретная фраза с пробелами')
assert verify_password('Секретная фраза с пробелами', encoded)
assert not verify_password('Другой пароль', encoded)
assert not verify_password('anything', 'broken hash')
assert hash_password('same password') != hash_password('same password')
def test_create_user_first_login_forces_password_change(accounts):
client, db, settings, admin, _, _ = accounts
headers = act_as(client, admin, settings)
response = client.post('/admin/users', data={'username': 'new.reader', 'full_name': 'Новый пользователь', 'role': 'user'}, headers=headers)
assert response.status_code == 200 and response.headers['cache-control'] == 'no-store'
password = BeautifulSoup(response.text, 'html.parser').select_one('[data-temporary-password]')['value']
user = db.scalar(select(SystemUser).where(SystemUser.username == 'new.reader'))
assert verify_password(password, user.password_hash) and user.must_change_password
assert password not in str(db.scalars(select(UserAction.changes)).all())
client.cookies.clear()
signed_in = login(client, user.username, password)
assert signed_in.status_code == 303 and signed_in.headers['location'] == '/admin/account'
db.refresh(user)
assert user.first_login_at and user.last_login_at and user.password_changed_at is None
first_login = user.first_login_at
assert 'data-required-password' in client.get('/admin/account').text
assert client.get('/admin/directory', follow_redirects=False).headers['location'] == '/admin/account'
assert client.get('/api/employees', follow_redirects=False).status_code == 403
old_token = client.cookies.get(SESSION_COOKIE)
csrf = _session_data(old_token, settings)['csrf']
changed = client.post('/admin/account/password', data={'current_password': password,
'new_password': 'A new personal passphrase', 'confirmation': 'A new personal passphrase'}, headers={'X-CSRF-Token': csrf}, follow_redirects=False)
assert changed.status_code == 303
db.refresh(user)
assert not user.must_change_password and user.password_changed_at and user.session_version == 1
assert user.first_login_at == first_login
assert 'data-required-password' not in client.get('/admin/account').text
assert client.get('/admin/directory').status_code == 200
assert client.get('/admin/users').status_code == 403
client.cookies.clear()
client.cookies.set(SESSION_COOKIE, old_token)
assert client.get('/api/employees', follow_redirects=False).status_code == 401
@pytest.mark.parametrize('path', ['/admin/crawl-now', '/admin/runs', '/admin/dismissed/refresh', '/admin/employees/1/refresh', '/api/crawl-runs'])
def test_regular_user_cannot_start_scraping(accounts, path):
client, db, settings, admin, user, _ = accounts
response = client.post(path, headers=act_as(client, user, settings), follow_redirects=False)
assert response.status_code == 403
assert 'Запустить парсинг' not in client.get('/admin').text
assert 'Обновить данные' not in client.get('/admin/employees/1').text
assert client.get('/api/stats').status_code == 200
def test_regular_user_edit_audit_and_personal_history_isolation(accounts):
client, db, settings, admin, user, employee = accounts
act_as(client, user, settings)
candidate = council.council_candidates(db)['candidates'][0]
article = candidate['articles'][0]
data = {'employee_id': employee.id, 'edit_key': article['edit_key'], 'revision': 0,
'title': 'Изменённая статья', 'journal': 'Новый журнал', 'quartile': 'Q2', 'specialty_codes': ['1.2.2']}
response = client.post('/admin/council/publications', json=data, headers={'X-Council-Edit': '1'})
assert response.status_code == 200
action = db.scalar(select(UserAction).where(UserAction.action == 'card_edit'))
assert action.user_id == user.id and action.employee_id == employee.id and action.publication_year == 2024
assert action.changes['title'] == {'before': 'Исходная статья', 'after': 'Изменённая статья'}
assert action.changes['quartile'] == {'before': '', 'after': 'Q2'}
assert action.changes['specialty_codes']['after']['codes'] == ['1.2.2']
db.add(UserAction(user_id=admin.id, action='card_edit', article_title='Чужое действие', changes={}))
db.commit()
profile = client.get(f'/admin/account?user_id={admin.id}')
assert 'Изменённая статья' in profile.text and 'Исходная статья' in profile.text
assert 'Чужое действие' not in profile.text
assert client.get(f'/admin/users?user_id={admin.id}').status_code == 403
assert client.post('/admin/council/publications', json=data, headers={'X-Council-Edit': '1'}).status_code == 409
assert db.scalars(select(UserAction).where(UserAction.user_id == user.id)).all() == [action]
def test_admin_reset_invalidates_sessions_and_preserves_password_change_date(accounts):
client, db, settings, admin, user, _ = accounts
user.password_changed_at = utcnow()
db.commit()
previous_changed = user.password_changed_at
old_token = sign_session(user.username, settings, user.session_version)
response = client.post(f'/admin/users/{user.id}/reset-password', headers=act_as(client, admin, settings))
assert response.status_code == 200
password = BeautifulSoup(response.text, 'html.parser').select_one('[data-temporary-password]')['value']
db.refresh(user)
assert user.must_change_password and user.password_reset_at and verify_password(password, user.password_hash)
assert user.password_changed_at == previous_changed
assert password not in client.get('/admin/users').text
client.cookies.clear()
client.cookies.set(SESSION_COOKIE, old_token)
assert client.get('/api/employees', follow_redirects=False).status_code == 401
assert login(client, user.username, password).headers['location'] == '/admin/account'
assert db.scalar(select(UserAction).where(UserAction.action == 'password_reset')).target_user_id == user.id
def test_role_changes_disable_and_protection_against_locking_out_self(accounts):
client, db, settings, admin, user, _ = accounts
old_token = sign_session(user.username, settings, user.session_version)
headers = act_as(client, admin, settings)
assert client.post(f'/admin/users/{admin.id}', data={'role': 'user', 'is_active': 'false'}, headers=headers).status_code == 422
assert client.post(f'/admin/users/{admin.id}/reset-password', headers=headers).status_code == 422
assert client.post(f'/admin/users/{user.id}', data={'role': 'admin', 'is_active': 'true'}, headers=headers, follow_redirects=False).status_code == 303
db.refresh(user)
assert user.role == 'admin'
client.cookies.clear()
client.cookies.set(SESSION_COOKIE, old_token)
assert client.get('/admin/users', follow_redirects=False).status_code == 303
headers = act_as(client, admin, settings)
assert client.post(f'/admin/users/{user.id}', data={'role': 'user', 'is_active': 'false'}, headers=headers, follow_redirects=False).status_code == 303
db.refresh(user)
client.cookies.clear()
assert login(client, user.username, 'Initial user password').status_code == 401
assert not user.is_active
def test_csrf_duplicate_user_validation_and_login_throttling(accounts):
client, db, settings, admin, user, _ = accounts
headers = act_as(client, admin, settings)
assert client.post('/admin/users', data={'username': 'unprotected'}).status_code == 403
assert client.post('/admin/account/password', data={'current_password': 'anything'}).status_code == 403
assert client.post('/admin/login', data={'username': user.username, 'password': 'anything'}).status_code == 403
for username, role, code in [('reader', 'user', 409), ('bad login', 'user', 422), ('newuser', 'superuser', 422)]:
assert client.post('/admin/users', data={'username': username, 'role': role}, headers=headers).status_code == code
client.cookies.clear()
for _ in range(5):
assert login(client, user.username, 'wrong password').status_code == 401
db.refresh(user)
assert user.locked_until and user.failed_login_attempts == 5
assert login(client, user.username, 'Initial user password').status_code == 401
user.locked_until = utcnow() - timedelta(minutes=1)
db.commit()
for attempt in range(1, 6):
assert login(client, user.username, 'wrong password').status_code == 401
db.refresh(user)
assert user.failed_login_attempts == attempt
assert bool(user.locked_until) == (attempt == 5)
assert login(client, user.username, 'Initial user password').status_code == 401
db.refresh(user)
assert user.failed_login_attempts == 5
user.locked_until = utcnow() - timedelta(minutes=1)
db.commit()
assert login(client, user.username, 'Initial user password').status_code == 303
db.refresh(user)
assert user.failed_login_attempts == 0 and user.locked_until is None
def test_bootstrap_admin_first_login_and_changed_password_no_env_fallback(accounts):
client, db, settings, admin, _, _ = accounts
assert login(client, admin.username, 'initial-admin-test').headers['location'] == '/admin/account'
csrf = _session_data(client.cookies.get(SESSION_COOKIE), settings)['csrf']
assert client.post('/admin/account/password', data={'current_password': 'initial-admin-test',
'new_password': 'New administrator passphrase', 'confirmation': 'New administrator passphrase'}, headers={'X-CSRF-Token': csrf}, follow_redirects=False).status_code == 303
client.cookies.clear()
assert login(client, admin.username, 'initial-admin-test').status_code == 401
assert login(client, admin.username, 'New administrator passphrase').status_code == 303
def test_cross_origin_and_session_expiry_fail_closed(accounts, monkeypatch):
import time
from app import security
client, db, settings, admin, user, _ = accounts
headers = act_as(client, admin, settings)
assert client.post('/admin/users', data={'username': 'attacker'}, headers={**headers, 'Origin': 'https://evil.example'}).status_code == 403
assert client.post('/admin/users', data={'username': 'attacker'}, headers={**headers, 'Origin': 'http://['}).status_code == 403
assert db.scalar(select(SystemUser).where(SystemUser.username == 'attacker')) is None
token = sign_session(user.username, settings, user.session_version)
now = int(time.time())
monkeypatch.setattr(security.time, 'time', lambda: now + security.SESSION_SECONDS + 1)
assert security.read_session(token, settings) is None
def test_password_errors_and_noop_card_edit_are_not_audited(accounts):
client, db, settings, _, user, employee = accounts
headers = act_as(client, user, settings)
before = user.password_hash
for current, new, confirmation in [('wrong', 'New valid personal password', 'New valid personal password'),
('Initial user password', 'short', 'short'),
('Initial user password', 'New valid personal password', 'Different valid password')]:
response = client.post('/admin/account/password', headers=headers,
data={'current_password': current, 'new_password': new, 'confirmation': confirmation})
assert response.status_code == 422 and user.password_hash == before
article = council.council_candidates(db)['candidates'][0]['articles'][0]
response = client.post('/admin/council/publications', headers={'X-Council-Edit': '1'}, json={
'employee_id': employee.id, 'edit_key': article['edit_key'], 'revision': 0, 'title': article['title'],
'journal': article['edit_journal'], 'quartile': article['edit_quartile'], 'specialty_codes': None})
assert response.status_code == 200
assert db.scalars(select(UserAction).where(UserAction.user_id == user.id)).all() == []
def test_logout_revokes_replayed_cookie(accounts):
client, db, settings, _, user, _ = accounts
headers = act_as(client, user, settings)
old_token = client.cookies.get(SESSION_COOKIE)
assert client.post('/admin/logout', headers=headers, follow_redirects=False).status_code == 303
client.cookies.set(SESSION_COOKIE, old_token)
assert client.get('/api/employees', follow_redirects=False).status_code == 401
def test_password_change_and_audit_rollback_atomically(accounts, monkeypatch):
from sqlalchemy.exc import OperationalError
client, db, settings, _, user, _ = accounts
headers = act_as(client, user, settings)
before = user.password_hash
def unavailable():
raise OperationalError('UPDATE', {}, Exception('private database details'))
monkeypatch.setattr(db, 'commit', unavailable)
response = client.post('/admin/account/password', data={'current_password': 'Initial user password',
'new_password': 'A different personal passphrase', 'confirmation': 'A different personal passphrase'}, headers=headers)
assert response.status_code == 503 and 'private database details' not in response.text
db.refresh(user)
assert user.password_hash == before and user.session_version == 0
assert db.scalar(select(UserAction).where(UserAction.action == 'password_change')) is None
def test_postgres_concurrent_admin_demotions_keep_an_admin(accounts):
from concurrent.futures import ThreadPoolExecutor
client, db, settings, admin, _, _ = accounts
if db.get_bind().dialect.name != 'postgresql':
pytest.skip('Requires the disposable PostgreSQL test database')
second = SystemUser(username='admin-two', role='admin', password_hash=hash_password('Second administrator passphrase'),
must_change_password=False, first_login_at=utcnow())
db.add(second)
db.commit()
factory = sessionmaker(bind=db.get_bind())
def sessions():
with factory() as session:
yield session
app.dependency_overrides[get_db] = sessions
clients = [TestClient(app), TestClient(app)]
actors = [admin, second]
targets = [second.id, admin.id]
def demote(index):
headers = act_as(clients[index], actors[index], settings)
response = clients[index].post(f'/admin/users/{targets[index]}',
data={'role': 'user', 'is_active': 'true'}, headers=headers, follow_redirects=False)
return response.status_code, response.headers.get('location')
try:
with ThreadPoolExecutor(max_workers=2) as executor:
responses = list(executor.map(demote, [0, 1]))
assert sum(location == '/admin/users' for status, location in responses) == 1
assert all(status in {303, 403} for status, location in responses)
remaining = db.scalars(select(SystemUser).where(SystemUser.role == 'admin', SystemUser.is_active.is_(True))).all()
assert len(remaining) == 1
finally:
for other in clients:
other.close()