feat: add council user role and restrict crawl runs

This commit is contained in:
codex committed 2026-11-12 09:35:26 +00:00
1 parent 59dcacbaff
commit 508aae4f8a
28 files changed
+217 -65

No files matched your search

+7
View File
@@ -81,6 +81,13 @@ def main():
filters.locator("summary").focus()
page.keyboard.press("Enter")
expect(page.get_by_label("ФИО или ссылка")).to_be_visible()
assert page.locator('.directory__filters :is(input, select)').evaluate_all("""controls =>
controls.every(control => {
control.focus();
const style = getComputedStyle(control);
return style.outlineWidth === '2px' && style.outlineOffset === '0px';
})
""")
for width in (1920, 1440, 1180, 1024, 921, 920, 768, 621, 620, 390, 320):
page.set_viewport_size({"width": width, "height": 844})
assert page.locator("main").evaluate("""main => {
+6 -2
View File
@@ -71,6 +71,7 @@ def main():
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('combobox', name='Роль', exact=True).select_option('council')
creation.get_by_role('button', name='Создать пользователя', exact=True).click()
temporary = page.locator('[data-temporary-password]')
expect(temporary).to_be_visible()
@@ -80,6 +81,7 @@ def main():
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')
page.screenshot(path=str(output/'users-mobile.png'), mask=[temporary], full_page=True)
creation.get_by_label('Логин', exact=True).fill('nojs.reader')
creation.get_by_role('combobox', name='Роль', exact=True).select_option('user')
creation.get_by_role('button', name='Создать пользователя', exact=True).click()
nojs_password = page.locator('[data-temporary-password]').input_value()
page.get_by_role('button', name='Выйти', exact=True).click()
@@ -242,13 +244,15 @@ def main():
nojs_page.get_by_label('Повторите новый пароль', exact=True).fill('No JS personal passphrase 123')
nojs_page.get_by_role('button', name='Сохранить новый пароль', exact=True).click()
nojs_page.get_by_role('link', name='Открыть подсказки', exact=True).click()
expect(nojs_page.locator('[data-guide-step]')).to_have_count(6)
expect(nojs_page.locator('[data-guide-step]')).to_have_count(2)
expect(nojs_page.get_by_text('Повышение квалификации', exact=True)).to_be_visible()
expect(nojs_page.get_by_role('heading', name='Проверьте строку публикации')).to_be_visible()
expect(nojs_page.get_by_role('link', name='Диссертационный совет', exact=True)).to_have_count(0)
expect(nojs_page.get_by_role('link', name='Запуски', exact=True)).to_have_count(0)
nojs_page.get_by_role('button', name='Завершить подсказки', exact=True).click()
expect(nojs_page.get_by_role('link', name='Открыть подсказки', exact=True)).to_have_count(0)
no_js.close()
expect(page.get_by_role('link', name='Пользователи', exact=True)).to_have_count(0)
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()
+3 -1
View File
@@ -6,7 +6,9 @@ from jinja2 import Environment, FileSystemLoader
def test_base_navigation_is_russian_and_has_no_legacy_employees_link():
template = Environment(loader=FileSystemLoader("app/templates")).get_template("base.html").render(
request=SimpleNamespace(url=SimpleNamespace(path="/admin"))
request=SimpleNamespace(url=SimpleNamespace(path="/admin")),
current_user=SimpleNamespace(role="admin", must_change_password=True),
council_access=True,
)
assert "Обзор" in template
+1 -1
View File
@@ -18,7 +18,7 @@ def test_health_returns_versions():
response = TestClient(app).get("/api/health")
assert response.status_code == 200
assert response.json()["backend_version"] == "1.7.3"
assert response.json()["backend_version"] == "2.0.0"
def test_api_employees_and_stats_require_admin_session():
+1 -1
View File
@@ -230,7 +230,7 @@ def test_public_page_data_minimization_and_safe_links(db_session, export):
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.7.3 · Frontend 1.7.3" in response.text
assert "Backend 2.0.0 · Frontend 2.0.0" 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
+27
View File
@@ -1,6 +1,12 @@
from pathlib import Path
import sqlite3
from sqlalchemy import create_engine, inspect, text
from sqlalchemy.dialects.sqlite import dialect
from sqlalchemy.schema import CreateTable
from app.db import _ensure_runtime_schema
from app.models import SystemUser
def test_runtime_schema_adds_skipped_count_to_existing_crawl_runs_table(monkeypatch):
@@ -142,3 +148,24 @@ def test_runtime_schema_adds_profile_verification_fields(monkeypatch):
columns = {column["name"] for column in inspector.get_columns("employees")}
assert {"profile_unavailable_streak", "last_profile_check_at", "has_academic_degree"}.issubset(columns)
assert "employee_profile_urls" in inspector.get_table_names()
def test_sqlite_council_role_migration_preserves_users_and_history():
original = str(CreateTable(SystemUser.__table__).compile(dialect=dialect())).replace(", 'council'", "")
with sqlite3.connect(":memory:") as connection:
connection.execute(original)
connection.execute("CREATE TABLE user_actions (user_id INTEGER REFERENCES system_users(id))")
connection.execute("""
INSERT INTO system_users
(id, username, full_name, role, is_active, password_hash, must_change_password,
session_version, failed_login_attempts, created_at)
VALUES (17, 'reader', '', 'user', 1, 'fixture', 0, 4, 0, '2026-11-12')
""")
connection.execute("INSERT INTO user_actions VALUES (17)")
before = connection.execute("SELECT * FROM system_users").fetchall()
migration = Path("migrations/sqlite/014_system_user_council_role.sql").read_text(encoding="utf-8")
connection.executescript(migration)
assert connection.execute("SELECT * FROM system_users").fetchall() == before
assert connection.execute("SELECT * FROM user_actions").fetchall() == [(17,)]
connection.execute("UPDATE system_users SET role = 'council' WHERE id = 17")
assert connection.execute("SELECT role FROM system_users").fetchone() == ("council",)
+38 -6
View File
@@ -126,13 +126,19 @@ def test_regular_user_cannot_start_scraping(accounts, path):
assert client.get('/api/stats').status_code == 200
def test_regular_user_edit_audit_and_personal_history_isolation(accounts):
def test_council_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']}
act_as(client, user, settings)
assert client.post('/admin/council/publications', json=data, headers={'X-Council-Edit': '1'}).status_code == 403
assert client.post(f'/admin/users/{user.id}', data={'role': 'council', 'is_active': 'true'},
headers=act_as(client, admin, settings), follow_redirects=False).status_code == 303
db.refresh(user)
assert user.role == 'council' and user.session_version == 1
act_as(client, user, settings)
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'))
@@ -150,6 +156,29 @@ def test_regular_user_edit_audit_and_personal_history_isolation(accounts):
assert db.scalars(select(UserAction).where(UserAction.user_id == user.id)).all() == [action]
@pytest.mark.parametrize('role', ['user', 'council', 'admin'])
def test_navigation_and_run_access_match_role(accounts, role):
client, db, settings, _, user, _ = accounts
user.role = role
db.commit()
act_as(client, user, settings)
dashboard = BeautifulSoup(client.get('/admin').text, 'html.parser')
links = {link['href'] for link in dashboard.select('nav a[href]')}
assert {'/admin', '/admin/directory', '/admin/account', '/admin/guide'} <= links
assert ('/admin/council' in links) == (role != 'user')
assert ('/admin/runs' in links) == (role == 'admin')
assert ('/admin/users' in links) == (role == 'admin')
assert bool(dashboard.select('[data-progress-panel]')) == (role == 'admin')
assert ('latest_run' in client.get('/api/stats').json()) == (role == 'admin')
for path in ('/admin/runs', '/api/crawl-runs', '/api/crawl-runs/latest', '/api/crawl-runs/1'):
assert client.get(path).status_code == (200 if role == 'admin' else 403)
assert client.get('/admin/runs/1', follow_redirects=False).status_code == (303 if role == 'admin' else 403)
client.cookies.clear()
assert client.get('/admin/directory', follow_redirects=False).headers['location'] == '/admin/login'
assert client.get('/admin/council').status_code == 200
assert client.get('/docs').status_code == 404
def test_admin_reset_invalidates_sessions_and_preserves_password_change_date(accounts):
client, db, settings, admin, user, _ = accounts
user.password_changed_at = utcnow()
@@ -248,6 +277,8 @@ def test_cross_origin_and_session_expiry_fail_closed(accounts, monkeypatch):
def test_password_errors_and_noop_card_edit_are_not_audited(accounts):
client, db, settings, _, user, employee = accounts
user.role = 'council'
db.commit()
headers = act_as(client, user, settings)
before = user.password_hash
for current, new, confirmation in [('wrong', 'New valid personal password', 'New valid personal password'),
@@ -290,7 +321,7 @@ def test_password_change_and_audit_rollback_atomically(accounts, monkeypatch):
assert db.scalar(select(UserAction).where(UserAction.action == 'guide_start')) is None
@pytest.mark.parametrize('role', ['user', 'admin'])
@pytest.mark.parametrize('role', ['user', 'council', 'admin'])
def test_guide_first_password_dismissal_and_repeat_change(accounts, role):
client, db, settings, _, user, _ = accounts
user.role = role
@@ -306,11 +337,12 @@ def test_guide_first_password_dismissal_and_repeat_change(accounts, role):
assert page.headers['Cache-Control'] == 'no-store'
guide = client.get('/admin/guide')
parsed = BeautifulSoup(guide.text, 'html.parser')
assert len(parsed.select('[data-guide-step]')) == 6
assert len(parsed.select('[data-guide-step]')) == (2 if role == 'user' else 6)
assert not parsed.select('[data-guide]')
assert 'Прочитайте показатели сотрудника' in guide.text and 'Проверьте строку публикации' in guide.text
assert ('Прочитайте показатели сотрудника' in guide.text) == (role != 'user')
assert ('Проверьте строку публикации' in guide.text) == (role != 'user')
assert ('управлять доступом' in guide.text) == (role == 'admin')
assert 'не ограничивает «ВСЕГО»' in guide.text
assert ('не ограничивает «ВСЕГО»' in guide.text) == (role != 'user')
csrf = BeautifulSoup(page.text, 'html.parser').select_one('[data-guide]')['data-guide-csrf']
assert client.post('/admin/guide/dismiss', headers={'X-CSRF-Token': 'wrong'}, follow_redirects=False).status_code == 403
assert 'data-guide-pending="true"' in client.get('/admin/directory').text