agreement feature added to Ahenk. User must be accept agreement when first login on a Ahenk. Display and type of dm are getting on logging

This commit is contained in:
Volkan Şahin 2016-06-27 17:20:26 +03:00
parent b3299303a8
commit 4eb03dacde
3 changed files with 144 additions and 11 deletions

View file

@ -10,7 +10,6 @@ import sys
import threading import threading
import time import time
import json import json
from base.Scope import Scope from base.Scope import Scope
from base.command.commander import Commander from base.command.commander import Commander
from base.config.ConfigManager import ConfigManager from base.config.ConfigManager import ConfigManager
@ -27,6 +26,9 @@ from base.registration.Registration import Registration
from base.scheduler.scheduler_factory import SchedulerFactory from base.scheduler.scheduler_factory import SchedulerFactory
from base.system.system import System from base.system.system import System
from base.task.TaskManager import TaskManager from base.task.TaskManager import TaskManager
from base.agreement.agreement import Agreement
from base.util.util import Util
from multiprocessing import Process
ahenkdaemon = None ahenkdaemon = None
@ -155,7 +157,6 @@ class AhenkDeamon(BaseDaemon):
def run(self): def run(self):
print('Ahenk running...') print('Ahenk running...')
self.signal_number = 0
globalscope = Scope() globalscope = Scope()
globalscope.setInstance(globalscope) globalscope.setInstance(globalscope)
@ -197,6 +198,8 @@ class AhenkDeamon(BaseDaemon):
self.messenger = self.init_messenger() self.messenger = self.init_messenger()
self.logger.info('[AhenkDeamon] Messager was set') self.logger.info('[AhenkDeamon] Messager was set')
Agreement().agreement_contract_update()
self.init_message_response_queue() self.init_message_response_queue()
# if registration.is_ldap_registered() is False: # if registration.is_ldap_registered() is False:
@ -238,16 +241,58 @@ class AhenkDeamon(BaseDaemon):
self.logger.debug('[AhenkDeamon] Signal is :{}'.format(str(json_data['event']))) self.logger.debug('[AhenkDeamon] Signal is :{}'.format(str(json_data['event'])))
if 'login' == str(json_data['event']): if 'login' == str(json_data['event']):
self.logger.info('[AhenkDeamon] login event is handled for user: {}'.format(json_data['username'])) username = json_data['username']
login_message = message_manager.login_msg(json_data['username']) display = json_data['display']
desktop = json_data['desktop']
self.logger.info('[AhenkDeamon] login event is handled for user: {}'.format(username))
login_message = message_manager.login_msg(username)
messenger.send_direct_message(login_message) messenger.send_direct_message(login_message)
get_policy_message = message_manager.policy_request_msg(json_data['username'])
messenger.send_direct_message(get_policy_message) scope.getDbService().update('session', scope.getDbService().get_cols('session'), [username, display, desktop, Util.timestamp()])
agreement = Agreement()
agreement_choice = False
if agreement.check_agreement(username) is False:
self.logger.debug('[AhenkDeamon] User {} has not accepted agreement.'.format(username))
thread_ask = Process(target=agreement.ask, args=(username, display,))
thread_ask.start()
agreement_timeout = scope.getConfigurationManager().get('SESSION', 'agreement_timeout')
timeout = int(agreement_timeout) # sec
timer = time.time()
while 1:
if thread_ask.is_alive() is False:
self.logger.warning('[AhenkDeamon] {} was answered the question '.format(username))
if Agreement().check_agreement(username):
self.logger.warning('[AhenkDeamon] Choice of {} is YES'.format(username))
agreement_choice = True
break
else:
self.logger.warning('[AhenkDeamon] Choice of {} is NO'.format(username))
agreement_choice = False
break
if (time.time() - timer) > timeout:
if thread_ask.is_alive():
thread_ask.terminate()
Util.execute('pkill -9 -u {}'.format(username))
self.logger.warning('[AhenkDeamon] Session of {} was ended because of timeout of contract agreement'.format(username))
break
time.sleep(0.1)
else:
agreement_choice = True
if agreement_choice is True:
get_policy_message = message_manager.policy_request_msg(username)
messenger.send_direct_message(get_policy_message)
elif 'logout' == str(json_data['event']): elif 'logout' == str(json_data['event']):
self.logger.info('[AhenkDeamon] logout event is handled for user: {}'.format(str(json_data['username']))) username = json_data['username']
logout_message = message_manager.logout_msg(json_data['username']) self.logger.info('[AhenkDeamon] logout event is handled for user: {}'.format(username))
logout_message = message_manager.logout_msg(username)
messenger.send_direct_message(logout_message) messenger.send_direct_message(logout_message)
plugin_manager.process_safe_mode(str(json_data['username'])) plugin_manager.process_safe_mode(username)
elif 'send' == str(json_data['event']): elif 'send' == str(json_data['event']):
self.logger.info('[AhenkDeamon] Sending message over ahenkd command. Response Message: {}'.format(str(json_data['message']))) self.logger.info('[AhenkDeamon] Sending message over ahenkd command. Response Message: {}'.format(str(json_data['message'])))
message = str(json.dumps(json_data['message'])) message = str(json.dumps(json_data['message']))
@ -300,8 +345,6 @@ if __name__ == '__main__':
elif result is True: elif result is True:
if System.Ahenk.is_running() is True: if System.Ahenk.is_running() is True:
os.kill(int(System.Ahenk.get_pid_number()), signal.SIGALRM) os.kill(int(System.Ahenk.get_pid_number()), signal.SIGALRM)
except(KeyboardInterrupt, SystemExit): except(KeyboardInterrupt, SystemExit):
if System.Ahenk.is_running() is True: if System.Ahenk.is_running() is True:
print('Ahenk will be closed.') print('Ahenk will be closed.')

View file

@ -0,0 +1,70 @@
from base.Scope import Scope
from base.util.util import Util
class Agreement:
def __init__(self):
scope = Scope().getInstance()
self.logger = scope.getLogger()
self.message_manager = scope.getMessageManager()
self.messenger = scope.getMessenger()
self.db_service = scope.getDbService()
self.ask_path = '/opt/ahenk/base/agreement/ask.py'
self.logger.debug('[Agreement] Instance initialized.')
def agreement_contract_update(self):
self.messenger.send_direct_message(self.message_manager.agreement_request_msg())
self.logger.debug('[Agreement] Requested updated agreement contract from lider.')
def check_agreement(self, username):
self.logger.debug('[Agreement] Checking agreement for user {}.'.format(username))
contract_id = self.get_current_contract_id()
if contract_id is None:
self.logger.debug('[Agreement] There is no any contract in database.')
if self.db_service.select_one_result('agreement', 'id', " contract_id='{0}' and username='{1}' and choice='Y' ".format('-1', username)) is None:
return False
else:
return True
else:
if self.db_service.select_one_result('agreement', 'id', " contract_id='{0}' and username='{1}' and choice='Y' ".format(contract_id, username)) is None:
return False
else:
return True
def get_current_contract_id(self):
return self.db_service.select_one_result('contract', 'id', 'id =(select MAX(id) from contract)')
def ask(self, username, display):
result = self.db_service.select('contract', ['content', 'title', 'id'], 'id =(select MAX(id) from contract)')
# TODO sec read from conf file
if result is None or len(result) < 1:
content = 'Ahenk kurulu bu bilgisayarda ilk defa oturum açıyorsunuz. ' \
'Devam ederseniz Lider-Ahenk in bilgisayar üzeride yapacağı ' \
'tüm işlemlere onay vermiş sayılacaksınız. Kabul ediyor musunuz?' \
' \n({} saniye içinde olumlu cevaplandırmadığınız takdirde oturumunuz ' \
'sonlandırılacaktır.)'.format(10)
title = 'Ahenk Kurulu Bilgisayar Kullanım Anlaşması'
contract_id = '-1'
else:
content = result[0]
title = result[1]
contract_id = result[2]
command = 'export DISPLAY={0};python3 {1} \'{2}\' \'{3}\' '.format(display, self.ask_path, content, title)
result_code, p_out, p_err = Util.execute(command, as_user=username)
pout = str(p_out).replace('\n', '')
if pout != 'Error':
if pout == 'Y':
self.logger.debug('[Agreement] Agreement was accepted by {}.'.format(username))
self.db_service.update('agreement', self.db_service.get_cols('agreement'), [contract_id, username, Util.timestamp(), 'Y'])
elif pout == 'N':
self.db_service.update('agreement', self.db_service.get_cols('agreement'), [contract_id, username, Util.timestamp(), 'N'])
self.logger.debug('[Agreement] Agreement was ignored by {}. Session will be closed'.format(username))
Util.execute('pkill -9 -u {}'.format(username))
else:
self.logger.error('[Agreement] A problem occurred while executing ask.py. Error Message: {}'.format(str(pout)))
else:
self.logger.error('[Agreement] A problem occurred while executing ask.py (Probably argument fault). Error Message: {}'.format(str(pout)))

20
opt/ahenk/base/agreement/ask.py Normal file → Executable file
View file

@ -0,0 +1,20 @@
import sys
import easygui
def ask(content, title):
choice = easygui.ynbox(content, title, ('Evet', 'Hayır'))
if choice:
print('Y')
else:
print('N')
if __name__ == '__main__':
if len(sys.argv) == 3:
try:
ask(sys.argv[1], sys.argv[2])
except Exception as e:
print(str(e))
else:
print('Error')