Коммит 39783e51 создал по автору Леляев Петр Алексеевич's avatar Леляев Петр Алексеевич
Просмотр файлов

Добавлены ограничения polkit на конкретные действия

владелец 1eec83cb
......@@ -8,7 +8,7 @@ from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
from school_ringer_modules.config import config_path, icon_file, debug
from school_ringer_modules.system import user, run_command
from school_ringer_modules.system import user, run_command, authority_check
# Директория приложения
basedir = os.path.dirname(__file__)
......@@ -35,10 +35,14 @@ if __name__ == '__main__':
format=u'%(asctime)s %(filename)s [LINE:%(lineno)d] [%(funcName)s()] #%(levelname)-15s %(message)s',
level=logging.INFO,
)
ex = CallsSettings(app)
app.exec_()
logging.info(f'Приложение завершило работу')
if authority_check("ru.mos.os.school-ringer"):
ex = CallsSettings(app)
app.exec_()
logging.info(f'Приложение завершило работу')
except Exception as e:
error_box = QMessageBox.critical(QWidget(), "Ошибка", f'({e})')
logging.info(f'Root exception: ({e})')
sys.exit(app)
try:
sys.exit(app)
except Exception as e:
print(f'Приложение не было запущено. {e}')
......@@ -15,4 +15,16 @@
<annotate key="org.freedesktop.policykit.exec.path">/usr/sbin/school-ringer-gui</annotate>
<annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>
</action>
<action id="download_instructions">
<description>Download instructions for School Ringer GUI</description>
<message xml:lang="ru">Требуется авторизация для скачивания инструкции!</message>
<defaults>
<allow_any>auth_admin</allow_any>
<allow_inactive>auth_admin</allow_inactive>
<allow_active>auth_admin</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.exec.path">/usr/sbin/school-ringer-gui</annotate>
<annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>
</action>
</policyconfig>
......@@ -21,7 +21,8 @@ from school_ringer_modules.music_on_breaks import MusicPlayer
from school_ringer_modules.schedule_editor import ScheduleEditor
from school_ringer_modules.schedules_dataclasses import schedules
from school_ringer_modules.sound import default_sound
from school_ringer_modules.system import run_command, get_current_user_on_x
from school_ringer_modules.system import run_command, get_current_user_on_x, authority_check
import dbus
class UpdateLabels(QThread):
......@@ -277,15 +278,19 @@ class CallsSettings(QWidget):
run_command(f'py-ini-config set {config_path}/school-ringer.conf Main is_breaks_music_on false')
def download_instructions(self):
try:
current_user_on_x = get_current_user_on_x()
if current_user_on_x:
run_command(f'su - {current_user_on_x} -c "DISPLAY=:0 chromium-browser '
f'https://hub.mos.ru/mos/src/school-ringer/-/blob/master/instruction.pdf"')
else:
logging.info('Не найден пользователь с графической оболочкой. Невозможно открыть инструкцию')
except Exception as e:
logging.info(f'Возникло исключение: {e}. Невозможно открыть инструкцию.')
if not authority_check("download_instructions"):
print('Скачивание не удалось.')
else:
try:
current_user_on_x = get_current_user_on_x()
if current_user_on_x:
run_command(f'chromium-browser '
f'https://hub.mos.ru/mos/src/school-ringer/-/blob/master/instruction.pdf')
else:
logging.info('Не найден пользователь с графической оболочкой. Невозможно открыть инструкцию')
except Exception as e:
logging.info(f'Возникло исключение: {e}. Невозможно открыть инструкцию.')
def initUI(self) -> None:
"""
......
import logging
from subprocess import run
import dbus
def run_command(command: str) -> str:
"""
......@@ -29,3 +31,21 @@ def get_current_user_on_x():
except Exception as e:
logging.info('Не удалось получить текущего пользователя на X. Возвращаем None...')
return None
def authority_check(action_id="ru.mos.os.school-ringer"):
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, 'org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name': system_bus_name})
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation id
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
if result[0] == 0:
print('Авторизация не пройдена!')
return result[0]
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать