def update_cron_template(setting, value, opaque): try: if setting == 'cron-scheduler-template': init_job(value) except Exception as e: log.error(f'could not update cron-scheduler-template: {e}') return True
def item_edit(done=False, id=-1): try: common_details = tables.prepare_item_config_for_view( configuration, 'edit') if done: user = User.query.get(id) form = EditForm(request.form) if form.validate() and request.method == 'POST': form.populate_obj(user) db.session.commit() return redirect(url_for('user.show')) else: return render_template('user/user.html', form_details=form, common_details=common_details) else: chbx_id_list = request.form.getlist('chbx') if chbx_id_list: id = int(chbx_id_list[0]) # only the first one can be edited if id > -1: user = User.query.get(id) form = EditForm(obj=user, formdata=None) common_details['item_id'] = id else: return redirect(url_for('user.show')) return render_template('user/user.html', form_details=form, common_details=common_details) except Exception as e: log.error(u'Could not edit user {}'.format(e)) flash_plus(u'Kan gebruiker niet aanpassen', e) return redirect(url_for('user.show'))
def send_ack_message(**kwargs): try: registration = mregistration.get_first_registration(ack_sent=False, enabled=True) if registration: message_send_max_retries = msettings.get_configuration_setting('message-send-max-retries') if registration.ack_send_retry >= message_send_max_retries: mregistration.set_enabled(registration, False) return mregistration.update_registration(registration, ack_send_retry=registration.ack_send_retry + 1) flat = registration.ret_flat() data = json.loads(flat['data']) to_id = registration.student_id to_nbr_coaccount = data['nbr_coaccount'] timeslot = registration.timeslot.ret_formio() timeslot_string = mutils.datetime_to_dutch_datetime_string(timeslot['timeslot-date']) url = timeslot['timeslot-meeting-url'] message_subject = msettings.get_configuration_setting('register-message-ack-subject-template') message_content = msettings.get_configuration_setting('register-message-ack-content-template') message_subject = message_subject.replace('{{TAG-TIMESLOT}}', timeslot_string) message_content = message_content.replace('{{TAG-TIMESLOT}}', timeslot_string) message_content = message_content.replace('{{TAG-MEETING-URL}}', f'<a href="{url}" target="_blank">deze link</a>') log.info(f'{message_subject} to {to_id}/{to_nbr_coaccount}') ret = msmartschool.send_message(to_id, to_nbr_coaccount, message_subject, message_content) if ret: mregistration.set_ack_sent(registration, True) return ret return False except Exception as e: log.error(f'Could not send message {e}') return False
def get_default_values(data): try: timeslots = [] available_timeslots = mtimeslot.get_free_timeslots() for timeslot in available_timeslots: timeslots.append({ 'label': mutils.datetime_to_dutch_datetime_string(timeslot.date), 'value': timeslot.id }) template = json.loads(msettings.get_configuration_setting('register-template')) hidden_data = json.dumps({ 'student-id': data['id'], 'nbr-coaccount': data['nbr_coaccount'] }) formio_data = { 'student-name': f'{data["student_first_name"]} {data["student_last_name"]}', 'parent-name': f'{data["parent_first_name"]} {data["parent_last_name"]}', 'hidden-data': hidden_data } ret = { 'timeslots': timeslots, 'template': template, 'formio_data': formio_data } return RegisterResult(RegisterResult.Result.E_OK, ret) except Exception as e: log.error(f'Could not get default values {e}') return RegisterResult(RegisterResult.Result.E_ERROR)
def start_job(): try: cron_template = msettings.get_configuration_setting('cron-scheduler-template') init_job(cron_template) msettings.subscribe_handle_update_setting('cron-scheduler-template', update_cron_template, None) except Exception as e: log.error(f'could not start cron-scheduler: {e}')
def init_dataset(aconfig): ''' In: aconfig is an app config dictionary. SideEffect: assigns an object to theAnimals Returns: True is succeeds ''' global theAnimals dstore = aconfig.get('DATASTORE') if(dstore == 'RAM'): log.info('DATASTORE is RAM') theAnimals = DataSetRAM('animal', AnimalSchema) return True elif(dstore == 'CouchDB'): log.info('DATASTORE is CouchDB') url = aconfig.get('COUCHDB_URL') if not url: log.info('No COUCHDB_URL') return False log.info('COUCHDB_URL=%s', str(url)) theAnimals = DataSetCouchDB('animal', AnimalSchema, url) return True # no datastore that we would understand! log.error('Unknown DATASTORE %s', dstore) return False
def add(action_done=False): try: if action_done: absent_teacher_ids = request.form.getlist('my-select[]') replaced_by_teacher_id = request.form['replaced_by'] school = db_utils.school() academic_year = db_utils.academic_year() if absent_teacher_ids: for t_id in absent_teacher_ids: r = ReplacementTeacher( replacing_id=t_id, replaced_by_id=replaced_by_teacher_id, school=school, academic_year=academic_year) db.session.add(r) r.first_replacement_teacher = True db.session.commit() else: form = forms.AddForm() teachers = [(i, t, '') for i, t in db_teacher.db_teacher_list(select=True, full_name=True)] return render_template('settings/replacements/replacement.html', form=form, all_teachers=teachers, title='Voeg een vervanger toe', action='add', role='add', subject='settings.replacements') except Exception as e: log.error(u'Could not add replacement {}'.format(e)) utils.flash_plus(u'Kan vervanger niet toevoegen', e) db.session.rollback() return redirect(url_for('settings.replacements.show'))
def update_database_now(): try: mcron.start_job_now() except Exception as e: log.error(f'could not execute database update:{e}') return {'status': False, 'message': str(e)} return {'status': True, 'message': 'Database update ongoing...'}
def __init__(self, controller_uid): """ """ # # Basic WorkPage interface structure # ================================== # Top: ToolBar # Center: A (main) panel where the 'things happens' ;-) # Bottom: StatusBar # UIViewObject.__init__(self, controller_uid) UIM = UIManager() controller = UIM.get(controller_uid) parent_uid = UIM._getparentuid(controller.uid) parent_controller = UIM.get(parent_uid) parent_view = parent_controller.view.main_area_panel wx.Panel.__init__(self, parent_view) if controller.pos == -1: controller.pos = parent_controller.view.get_notebook_page_count() # result = parent_controller.insert_notebook_page( controller.pos, self, controller.title, True) # if not result: log.error('Page could not be inserted in MainWindow notebook.') # controller.subscribe(self._set_title, 'change.title') controller.subscribe(self._set_pos, 'change.pos') controller.subscribe(self._set_float_mode, 'change.float_mode') # Set notebook page name self._set_own_name()
def login(self, username, password): """ Validating username and password. """ client = self.connect() db = client.tjs collection = db.Users ts = datetime.now() try: hash_pass = collection.find_one({"UserName": username}, { "Password": 1, "_id": 0 }) if hash_pass is not None: db_hash = hash_pass["Password"] new_hash = bcrypt.hashpw(password.encode("utf-8"), db_hash) if db_hash == new_hash: log.error('[%s] %s %s %s %s', ts, "mongodb", "login", username, "OK") return 0 else: log.error('[%s] %s %s %s %s', ts, "mongodb", "login", username, "NOK") return 2 else: log.error('[%s] %s %s %s %s', ts, "mongodb", "login", username, "NOK") return 1 except Exception as e: log.error('[%s] %s %s %s', ts, "mongodb", "login", "EXCEPTION") log.error('%s', e) return e
def prepare_data_for_html(table): try: _filters_enabled, _filter_forms, _filtered_list, _total_count, _filtered_count = process_data(table) _filtered_dict = table['format_data'](_filtered_list) # order, if required, 2nd stage _template = table['template'] column_number = check_value_in_form('order[0][column]', request.values) column_number = int(column_number) if column_number: if 'row_detail' in table: column_number -= 1 if _template[column_number]['order_by'] and callable(_template[column_number]['order_by']): reverse = False if check_string_in_form('order[0][dir]', request.values) == 'desc' else True _filtered_dict = sorted(_filtered_dict, key=_template[column_number]['order_by'], reverse=reverse) except Exception as e: log.error('could not prepare data for html : {}'.format(e)) utils.flash_plus('Er is een fout opgetreden en de tabel kan niet getoond worden.', e) _total_count = _filtered_list = _filtered_count = 0 _filtered_dict = [] # prepare for json/ajax output = {} output['draw'] = str(int(request.values['draw'])) output['recordsTotal'] = str(_total_count) output['recordsFiltered'] = str(_filtered_count) output['data'] = _filtered_dict # add the (non-standard) flash-tag to display flash-messages via ajax fml = get_flashed_messages() if not not fml: output['flash'] = fml return jsonify(output)
def get_string_from_function(function_): if not callable(function_): msg = 'ERROR: Given input is not a function: {}.'.format( str(function_)) log.error(msg) raise Exception(msg) return function_.__module__ + '.' + function_.__name__
def register(): try: if 'version' in request.args: profile = json.loads(request.args['profile']) data = { 'student_first_name': profile['name'], 'student_last_name': profile['surname'], 'parent_first_name': profile['actualUserName'], 'parent_last_name': profile['actualUserSurname'], 'nbr_coaccount': profile['nrCoAccount'], 'id': profile['internalnumber'], } ret = prepare_registration_form(data) if ret.code == ret.Result.E_ERROR: return render_template('end_user/messages.html', type='error') return render_template( 'end_user/register.html', data=ret.result, registration_endpoint='end_user.register_save') else: redirect_uri = f'{flask_app.config["SMARTSCHOOL_OUATH_REDIRECT_URI"]}/register' return redirect( f'{flask_app.config["SMARTSCHOOL_OAUTH_SERVER"]}?app_uri={redirect_uri}' ) except Exception as e: log.error(f'could not register {request.args}: {e}') return render_template('end_user/messages.html', type='error', info=e)
def update_scripts_on_papercut_server(skip_ssh_connect=False): try: remote_script_path = msettings.get_configuration_setting( 'papercut-script-path').replace('\\\\', '/') scripts = msettings.get_configuration_setting('papercut-scripts') out = [] script_name = None if not skip_ssh_connect: url = msettings.get_configuration_setting('papercut-url') login = msettings.get_configuration_setting('papercut-login') password = msettings.get_configuration_setting('papercut-password') ssh_client.connect(url, username=login, password=password) transport = ssh_client.get_transport() sftp = sftp_client.SFTPClient.from_transport(transport) for line in scripts.split('\n'): if 'SCRIPT-START' in line: script_name = line.strip().split(' ')[-1] out = [] elif 'SCRIPT-STOP' in line: local_script_file = f'{PAPERCUT_LOCATION}/{script_name}' with open(local_script_file, "w") as f: f.writelines(out) sftp.put(local_script_file, script_name) else: out.append(f'{line}\n') sftp.close() if not skip_ssh_connect: ssh_client.close() except Exception as e: log.error('Could not update papercut scripts: {e}')
def action(): try: if utils.button_pressed('add'): d, h = Schedule.decode_dayhour(request.form['dayhour']) ts_d, ts_h = db_utils.time_to_timeslot(include_zero_hour=True) delta_d = ts_d - d if d * 10 + h > ts_d * 10 + ts_h: delta_d += 7 now = datetime.datetime.now() if db_setting.get_global_setting_sim_dayhour_state(): try: now = datetime.datetime.strptime(db_setting.get_global_setting_sim_dayhour(), '%d-%m-%Y %H:%M') except Exception as e: log.error('bad sim dayhour string : {}'.format(e)) date = (now - datetime.timedelta(days=delta_d)).strftime('%d-%m-%Y') students = [] for s in request.form.getlist('student_id'): student = Student.query.get(s) if student: students.append(student) form = RemarkForm() prime_data = {} prime_data['hour'] = h prime_data['date'] = date return render_template('remark/remark.html', subject='grade', action='add', form=form, students=students, prime_data=prime_data) except Exception as e: utils.flash_plus(u'Kan opmerking niet opslaan', e) log.error(u'Cannot save remarks {}'.format(e)) return redirect(url_for('grade.show'))
def login(self, username, password): """ Validating username and password for login. """ db = self.client.pycaptive.Users ts = datetime.now() try: hash_pass = db.find_one({"UserName": username}, { "Password": 1, "_id": 0 }) self.client.close() if hash_pass is not None: db_hash = hash_pass["Password"] new_hash = bcrypt.hashpw(password.encode("utf-8"), db_hash) if db_hash == new_hash: log.info('%s %s %s %s', "mongodb", "login", "OK", username) return 0 else: log.error('%s %s %s %s %s', "mongodb", "login", "NOK", username, "WRONG_PASS") return 2 else: log.error('%s %s %s %s %s', "mongodb", "login", "NOK", username, "NOT_FOUND") return 1 except Exception as e: log.critical('%s %s %s %s', "mongodb", "login", "EXCEPTION", username) log.critical('%s', e) return e
def get_rfids(): try: url = msettings.get_configuration_setting('papercut-server-url') port = msettings.get_configuration_setting('papercut-server-port') token = msettings.get_configuration_setting('papercut-auth-token') nbr_updated_rfid = 0 nbr_user_not_found = 0 with xmlrpc.client.ServerProxy( f'http://{url}:{port}/rpc/api/xmlrpc') as server: persons = mperson.get_persons(enabled=True, active=True) for person in persons: try: property = server.api.getUserProperty( token, person.ad_user_name, PROPERTY_RFID) if person.rfid_code != property.upper(): person.rfid_code = property.upper() nbr_updated_rfid += 1 except Exception as e: nbr_user_not_found += 1 log.info( f'get person rfid: person not found: {person.ad_user_name}, error: {e}' ) mperson.end_update_bulk_person() log.info( f'get rfids from papercut: nbr-persons/nbr-updated/nbr-not-found {len(persons)}/{nbr_updated_rfid}/{nbr_user_not_found}' ) return { 'status': True, 'message': f'RFIDs from papercut\nnbr: {len(persons)}\nupdated {nbr_updated_rfid}\nnot found {nbr_user_not_found}' } except Exception as e: log.error('get rfids: error {e}') return {'status': False, 'message': f'{e}'}
def del_conntrack(self, ip): """ Destroys established connections from conntrack table for a specified IP address. This action is complementary to del_rules() method, in order to insure that no connection is persisting between a PyCaptive client and a remote IP address. See del_rules() for more info. Parameters ---------- ip : string IP address provided via del_rules() method. Returns ------- integer if 0: rule successfully deleted else: error while processing command """ destroy_conn = [CONNTRACK, "-D", "--orig-src", ip] result = sp.call(destroy_conn, stderr=sp.DEVNULL, stdout=sp.DEVNULL) if result == 0: log.info('%s %s %s %s', "iptables", "del_conntrack", "OK", ip) else: log.error('%s %s %s %s', "iptables", "del_conntrack", "NOK", ip) return result
def get_node(self, node_uuid): node = self.nodes_map.get(node_uuid) if node is None: log.error("get_node - no node found with uuid: " + node_uuid) return node
def add_rule(self, ip): """ Allowing Internet access to an IP address Parameters ---------- ip : string IP address provided via client request to PyCaptive. Returns ------- integer if 0: rule successfully deleted else: error while processing command """ rule = [ IPTABLES, "-t", TABLE, "-I", CHAIN, "-i", LAN, "-s", ip, "-m", "comment", "--comment", COMMENT, "-j", JUMP ] try: result = sp.call(rule) if result == 0: log.info('%s %s %s %s', "iptables", "add_rule", "OK", ip) else: log.error('%s %s %s %s', "iptables", "add_rule", "NOK", ip) return result except Exception as e: log.critical('%s %s %s %s', "iptables", "add_rule", "EXCEPTION", ip) log.critical('%s', e) return e
def edit(action_done=False, id=-1): try: if action_done: user = User.query.get(id) form = EditForm(id=id) if form.validate_on_submit(): form.populate_obj(user) db.session.commit() return redirect(url_for('user.show')) else: return render_template('user/user.html', form=form, title='Wijzig een gebruiker', action='edit', role='edit', subject='user') else: chbx_id_list = request.form.getlist('chbx') if chbx_id_list: id = int(chbx_id_list[0]) # only the first one can be edited user = User.query.get(id) form = EditForm(obj=user, formdata=None) else: return redirect(url_for('user.show')) return render_template('user/user.html', form=form, title='Wijzig een gebruiker', action='edit', role='edit', subject='user') except Exception as e: log.error(u'Could not edit user {}'.format(e)) utils.flash_plus(u'Kan gebruiker niet aanpassen', e) return redirect(url_for('user.show'))
def save_generic(): try: db_setting.set_global_setting_help_url(request.form['txt-help-url']) except Exception as e: log.error(u'Cannot save help-website-url: {}'.format(e)) utils.flash_plus(u'Kan de help website URL niet bewaren', e) return redirect(url_for('settings.show_generic'))
def item_delete(): try: chbx_id_list = request.form.getlist('chbx') mregister.delete_registration(chbx_id_list) except Exception as e: log.error(u'Could not delete registration: {}'.format(e)) flash_plus('Could not delete registration', e) return redirect(url_for('registration.show'))
def get(self, token): try: history = History.query.filter( History.user_id == token.user_id).all() return {'all': history} except Exception as e: log.error(e) return {'state': 'fail', 'message': str(e)}, 500
def start_job_now(): try: init_job('now') time.sleep(1) cron_template = msettings.get_configuration_setting('cron-scheduler-template') init_job(cron_template) except Exception as e: log.error(f'could not start a cron job now: {e}')
def clear_database(): try: persons = mperson.get_persons() mperson.delete_persons(persons=persons) except Exception as e: log.error(f'could not clear database: {e}') return {'status': False, 'message': str(e)} log.info('database is cleared') return {'status': True, 'message': 'Database is cleared'}
def clear_update_and_new_flags(): try: persons = mperson.get_persons() for person in persons: mperson.update_flag(person, False) mperson.new_flag(person, False) mperson.end_update_bulk_person() except Exception as e: log.error(f'could not clear update and new flags:{e}')
def main(screen): try: app = Application(screen) app.run() return None, None except Exception as e: log.error("Unhandled Exception: {}".format(e)) log.error(traceback.format_exc()) return e, traceback.format_exc()
def trigger_settings(jds): try: setting = json.loads(jds) if setting['id'] == 'email-activity': enable_invite(setting['org'], setting['state']) except Exception as e: log.error(f'Could not trigger setting : {e}') return jsonify({'status': False}) return jsonify({'status': True})
def delete(id): myRes = MyResponse() try: db.session.query(User.id, User.user_code).filter(User.id == id).delete() myRes.status = ResState.HTTP_SUCCESS myRes.msg = "操作成功" except Exception as ex: log.error("delete user id is %d, error by %v", id, ex) return myRes.to_json()
def verify(email, verification_hash): logging_prefix = logger_prefix + "verify() - " log.info(logging_prefix + "Starting") email = unquote_plus(email) print(email) print(verification_hash) try: conn=get_mysql().cursor(DictCursor) conn.execute("SELECT id, email, name, company, justification FROM users WHERE verification_hash = %s", (verification_hash,)) r = conn.fetchone() if not r: log.error(logging_prefix + "User with email '{}' was not found".format(email)) flash("Your user was not found, try registering again",'danger') elif r['email'] == email: log.info(logging_prefix + "Successful validation of {}".format(email)) flash("Your email address have been verified, you will not be able to log in until you get approved by the Site Admin",'success') #update the database marking this user active user_id = r['id'] conn.execute("UPDATE users SET email_verified=1 WHERE id = %s", (user_id,)) get_mysql().commit() #id, email, name, company sendNewUserToApproveEmail(r['id'], r['email'],r['name'],r['company'],r['justification']) else: log.warning(logging_prefix + "Unsuccessful validation of {}".format(email)) flash("We were unable to verify your account",'danger') except Exception as e: error = "There was an error completing your request. Details: {}".format(e) flash(error,'danger') log.exception(logging_prefix + error) finally: conn.close() return redirect("/", code=307)