class update_init_event_handler(pytavia_event_handler.pytavia_event_handler): mgdDB = database.get_db_conn(config.mainDB) def __init__(self, params): pytavia_event_handler.pytavia_event_handler.__init__(self, params) # end def """ This is where we write the code to handle the event that comes in when the database is updated """ def event_switch(self, event): pytavia_event_handler.pytavia_event_handler.event_switch(self, event)
class customer_evt_handler(pytavia_event_handler.pytavia_event_handler): mgdDB = database.get_db_conn( config.mainDB ) def __init__(self, params): pytavia_event_handler.pytavia_event_handler.__init__(self,params) # end def def process_customer_check(self, event): print ("do some action here") # end def def event_switch(self, event): pytavia_event_handler.pytavia_event_handler.event_switch( self, event) try: event_action = event.get("action") if event_action == "INSERT": self.process_customer_check( event ) sys.stdout.flush() # end if except: print( traceback.format_exc() )
import json import io import boto3 import urllib sys.path.append("pytavia_modules/security") from pytavia_core import config from pytavia_core import database from flask import Flask from flask import redirect from flask import make_response app = Flask(__name__, config.G_STATIC_URL_PATH) app.secret_key = config.G_FLASK_SECRET wmsDB = database.get_db_conn(config.mainDB) def store_file(params): response = { "message_id": "", "message_action": "ADD_WASABI_FILE_SUCCESS", "message_code": "1", "message_desc": "", "message_data": {}, } bucket = params["bucket"] file_data = params["file_data"] file_name = params["file_name"] s3 = boto3.client('s3',
class authentication: #set connection to mongo dbsample = database.get_db_conn(config.mainDB) #construct def __init__(self, params): pass #end #================================================== #Public Function #================================================== def register(self, params): #validation required_param = ['name', 'username', 'password'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status' : False, 'message' : validation['message']} #end try: #get info user params['salt'] = self._generate_salt() info_user = self._get_user_by_username(params['username']) #is valid username? if (info_user is not None): return {'status' : False, 'message' : 'Username already taken'} #endif #save data user user_add = database.new(self.dbsample, 't_user') user_add.put('name', params['name']) user_add.put('username', params['username']) user_add.put('salt', params['salt']) user_add.put('password', self._generate_password(params['salt'], params['password'])) user_add.insert() #return return {'status' : True, 'message' : 'Username successfully inserted'} except: return {'status' : False, 'message' : 'Something went wrong, be hold...'} #endtry #end def login(self, params): #validation required_param = ['username', 'password'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status' : False, 'message' : validation['message']} #end try: #get info user info_user = self._get_user_by_username(params['username']) #is already login? if (info_user is not None and info_user['session'] != ''): return {'status' : True, 'message' : 'The floor is yours', 'session' : info_user['session']} #endif #is valid user? if (info_user is None): return {'status' : False, 'message' : 'You shall not pass'} #endif #is correct password? if (info_user['password'] != self._generate_password(info_user['salt'], params['password'])): return {'status' : False, 'message' : 'You shall not pass'} #endif #update data user session = self._generate_session() query = {'username': params['username']} new_values = {'$set': { 'session': session}} myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['dbsample'] mycol = mydb['t_user'] mycol.update_one(query, new_values) #return return {'status' : True, 'message' : 'The floor is yours', 'session' : session} except: return {'status' : False, 'message' : 'Something went wrong, be hold...'} #endtry #end def logout(self, params): #validation required_param = ['session'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status' : False, 'message' : validation['message']} #end try: #get info user info_user = self._get_user_by_session(params['session']) #is valid user signin? if (info_user is not None): #update data user query = {'session': info_user['session']} new_values = {'$set': { 'session': ''}} myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['dbsample'] mycol = mydb['t_user'] mycol.update_one(query, new_values) #endif #return return {'status' : True, 'message' : 'See you next time'} except: return {'status' : False, 'message' : 'Something went wrong, be hold...'} #endtry #end #================================================== #Private Function #================================================== def _validation_params(self, required_param, params): #checking required_param for field in required_param: if (len(params[field]) == 0): return {'status' : False, 'message' : 'Field [' + field + '] is required'} #endif #endfor #end def _get_user_by_username(self, username): info_user = self.dbsample.t_user.find_one({'username': username}) info_user = json.loads(json_util.dumps(info_user)) return info_user #end def _get_user_by_session(self, session): info_user = self.dbsample.t_user.find_one({'session': session}) info_user = json.loads(json_util.dumps(info_user)) return info_user #end def _generate_salt(self): letters = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(letters) for i in range(5)) #end def _generate_password(self, salt, password): return hashlib.sha256(str(password + salt + password).encode('utf-8')).hexdigest() #end def _generate_session(self): return hashlib.sha256(str(datetime.datetime.now()).encode('utf-8')).hexdigest() #end
class thread: #set connection to mongo dbsample = database.get_db_conn(config.mainDB) #construct def __init__(self, params): pass #end #================================================== #Public Function #================================================== def thread_add(self, params): #validation required_param = ['title', 'content', 'session'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status': False, 'message': validation['message']} #end try: #get info user info_user = self._get_user_by_session(params['session']) if (info_user is None): return {'status': False, 'message': 'You shall not pass'} #endif #save data thread thread_add = database.new(self.dbsample, 't_thread') thread_add.put('title', params['title']) thread_add.put('content', params['content']) thread_add.put('creator', info_user['pkey']) thread_add.insert() #return return {'status': True, 'message': 'Thread successfully created'} except: return { 'status': False, 'message': 'Something went wrong, be hold...' } #endtry #end def thread_view(self, params): #validation required_param = ['id_thread'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status': False, 'message': validation['message']} #end try: #get info thread info_thread = self._get_thread_by_id(params['id_thread']) if (info_thread is None): return { 'status': False, 'message': 'You seek the wrong thread' } #endif #return return { 'status': True, 'message': 'Thread successfully created', 'data': info_thread } except: return { 'status': False, 'message': 'Something went wrong, be hold...' } #endtry #end def thread_edit(self, params): #validation required_param = ['id_thread', 'session'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status': False, 'message': validation['message']} #end try: #get info user info_user = self._get_user_by_session(params['session']) if (info_user is None): return {'status': False, 'message': 'You shall not pass'} #endif #get info thread info_thread = self._get_thread_by_id(params['id_thread']) if (info_thread is None): return { 'status': False, 'message': 'You seek the wrong thread' } #endif #is thread creator? if (info_user['pkey'] != info_thread['creator']): return { 'status': False, 'message': 'Only creator can modify thread' } #endif #update data user title = info_thread['title'] if (len(params['title']) == 0) else params['title'] content = info_thread['content'] if (len(params['content']) == 0) else params['content'] query = {'_id': ObjectId(params['id_thread'])} new_values = {'$set': {'title': title, 'content': content}} myclient = pymongo.MongoClient('mongodb://localhost:27017/') mydb = myclient['dbsample'] mycol = mydb['t_thread'] mycol.update_one(query, new_values) #return return {'status': True, 'message': 'Thread successfully updated'} except: return { 'status': False, 'message': 'Something went wrong, be hold...' } #endtry #end def thread_delete(self, params): #validation required_param = ['id_thread', 'session'] validation = self._validation_params(required_param, params) if (validation is not None): return {'status': False, 'message': validation['message']} #end try: #get info user info_user = self._get_user_by_session(params['session']) if (info_user is None): return {'status': False, 'message': 'You shall not pass'} #endif #get info thread info_thread = self._get_thread_by_id(params['id_thread']) if (info_thread is None): return { 'status': False, 'message': 'You seek the wrong thread' } #endif #delete data thread thread_delete = database.new(self.dbsample, 't_thread') thread_delete.delete({'_id': ObjectId(params['id_thread'])}) #return return {'status': True, 'message': 'Thread successfully deleted'} except: return { 'status': False, 'message': 'Something went wrong, be hold...' } #endtry #end #================================================== #Private Function #================================================== def _validation_params(self, required_param, params): #checking required_param for field in required_param: if (len(params[field]) == 0): return { 'status': False, 'message': 'Field [' + field + '] is required' } #endif #endfor #end def _get_user_by_session(self, session): info_user = self.dbsample.t_user.find_one({'session': session}) info_user = json.loads(json_util.dumps(info_user)) return info_user #end def _get_thread_by_id(self, id_thread): info_thread = self.dbsample.t_thread.find_one( {'_id': ObjectId(id_thread)}) info_thread = json.loads(json_util.dumps(info_thread)) return info_thread #end
class generic_proc: mgdDB = database.get_db_conn(config.mainDB) db_handle = database.get_database(config.mainDB) def __init__(self, app): self.webapp = app # end def def archive(self, params): try: collection = params["collection"] db_readable_name = database.get_readable_name(collection) process_name = "ARCHIVE_" + db_readable_name.upper().replace( " ", "_") proc_success_status = process_name + "_SUCCESS" proc_failed_status = process_name + "_FAILED" response = helper.response_msg( status=proc_success_status, desc="Archiving {} record successful.".format( db_readable_name), data={}) ##### PAYLOAD ##### pkey = params["pkey"] ##### VALIDATION ##### record = validation.find_one(response, self.db_handle, collection, {"pkey": pkey}) if record == None: return response ##### DB OPERATION ##### timestamp, timestamp_str = utils._get_current_timestamp() bulk_action = bulk_db_action.bulk_db_action({ "db_handle": self.db_handle, "app": self.webapp }) bulk_action.deep_update(collection, {"pkey": pkey}, { "$set": { "archived_timestamp": timestamp, "archived_timestamp_str": timestamp_str } }) bulk_action.execute({}) ##### RESPONSE ##### record["archived_timestamp"] = timestamp record["archived_timestamp_str"] = timestamp_str response.put("status_code", config.G_STATUS['SUCCESS']['CODE']) response.put("data", record) except: self.webapp.logger.debug(traceback.format_exc()) response.put("status_code", config.G_STATUS['UNEXPECTED_ERROR']['CODE']) response.put("status", proc_failed_status) response.put("desc", config.G_STATUS['UNEXPECTED_ERROR']['DESC']) # end try return response # end def def restore(self, params): try: collection = params["collection"] db_readable_name = database.get_readable_name(collection) process_name = "RESTORE_" + db_readable_name.upper().replace( " ", "_") proc_success_status = process_name + "_SUCCESS" proc_failed_status = process_name + "_FAILED" response = helper.response_msg( status=proc_success_status, desc="Restoring {} record successful.".format( db_readable_name), data={}) ##### PAYLOAD ##### pkey = params["pkey"] ##### VALIDATION ##### record = validation.find_one(response, self.db_handle, collection, {"pkey": pkey}) if record == None: return response ##### DB OPERATION ##### timestamp, timestamp_str = utils._get_current_timestamp() bulk_action = bulk_db_action.bulk_db_action({ "db_handle": self.db_handle, "app": self.webapp }) bulk_action.deep_update(collection, {"pkey": pkey}, { "$set": { "archived_timestamp": "", "archived_timestamp_str": "" } }) bulk_action.execute({}) ##### RESPONSE ##### record["archived_timestamp"] = "" record["archived_timestamp_str"] = "" response.put("status_code", config.G_STATUS['SUCCESS']['CODE']) response.put("data", record) except: self.webapp.logger.debug(traceback.format_exc()) response.put("status_code", config.G_STATUS['UNEXPECTED_ERROR']['CODE']) response.put("status", proc_failed_status) response.put("desc", config.G_STATUS['UNEXPECTED_ERROR']['DESC']) # end try return response # end def def add_two_way_reference(self, params, return_record=False): try: main_collection = params["main"]["collection"] sub_collection = params["sub"]["collection"] main_db_readable_name = database.get_readable_name(main_collection) sub_db_readable_name = database.get_readable_name(sub_collection) main_process_name = utils._to_process_name(main_db_readable_name) sub_process_name = utils._to_process_name(sub_db_readable_name) process_name = "ADD_REFERENCE_BETWEEN_{}_AND_{}".format( main_process_name, sub_process_name) proc_success_status = process_name + "_SUCCESS" proc_failed_status = process_name + "_FAILED" response = helper.response_msg( status=proc_success_status, desc="Adding reference between {} and {} successful.".format( main_db_readable_name, sub_db_readable_name), data={}) ##### PAYLOAD ##### main_record_pkey = params["main"]["pkey"] sub_record_pkey = params["sub"]["pkey"] ##### VALIDATION ##### main_rec = validation.find_one(response, self.db_handle, main_collection, {"pkey": main_record_pkey}) if main_rec == None: return response # ----------------------- # fk_sub_collection_key = utils._db_name_to_fk_name(sub_collection) reference_found, reference = validation.no_reference( response, main_rec, fk_sub_collection_key, sub_record_pkey) if reference_found: return response # ----------------------- # sub_rec = validation.find_one(response, self.db_handle, sub_collection, {"pkey": sub_record_pkey}) if sub_rec == None: return response # ----------------------- # fk_main_collection_key = utils._db_name_to_fk_name(main_collection) reference_found, reference = validation.no_reference( response, sub_rec, fk_main_collection_key, main_record_pkey) if reference_found: return response ##### DB OPERATION ##### bulk_action = bulk_db_action.bulk_db_action({ "db_handle": self.db_handle, "app": self.webapp }) bulk_action.two_way_reference( { "collection": main_collection, "record": main_rec }, { "collection": sub_collection, "record": sub_rec }) bulk_action.execute({}) ##### RESPONSE ##### main_response_name = utils._db_name_to_response_name( main_collection) sub_response_name = utils._db_name_to_response_name(sub_collection) if return_record: # get updated records main_rec = validation.find_one(response, self.db_handle, main_collection, {"pkey": main_record_pkey}) sub_rec = validation.find_one(response, self.db_handle, sub_collection, {"pkey": sub_record_pkey}) else: main_rec = main_record_pkey sub_rec = sub_record_pkey response.put("status_code", config.G_STATUS['SUCCESS']['CODE']) response.put("data", { main_response_name: main_rec, sub_response_name: sub_rec, }) except: self.webapp.logger.debug(traceback.format_exc()) response.put("status_code", config.G_STATUS['UNEXPECTED_ERROR']['CODE']) response.put("status", proc_failed_status) response.put("desc", config.G_STATUS['UNEXPECTED_ERROR']['DESC']) # end try return response # end def def remove_two_way_reference(self, params, return_record=False): try: main_collection = params["main"]["collection"] sub_collection = params["sub"]["collection"] main_db_readable_name = database.get_readable_name(main_collection) sub_db_readable_name = database.get_readable_name(sub_collection) main_process_name = utils._to_process_name(main_db_readable_name) sub_process_name = utils._to_process_name(sub_db_readable_name) process_name = "REMOVE_REFERENCE_BETWEEN_{}_AND_{}".format( main_process_name, sub_process_name) proc_success_status = process_name + "_SUCCESS" proc_failed_status = process_name + "_FAILED" response = helper.response_msg( status=proc_success_status, desc="Removing reference between {} and {} successful.".format( main_db_readable_name, sub_db_readable_name), data={}) ##### PAYLOAD ##### main_record_pkey = params["main"]["pkey"] sub_record_pkey = params["sub"]["pkey"] ##### VALIDATION ##### main_rec = validation.find_one(response, self.db_handle, main_collection, {"pkey": main_record_pkey}) if main_rec == None: return response # ----------------------- # fk_sub_collection_key = utils._db_name_to_fk_name(sub_collection) reference_found, reference = validation.find_reference( response, main_rec, fk_sub_collection_key, sub_record_pkey) if not reference_found: return response # ----------------------- # sub_rec = validation.find_one(response, self.db_handle, sub_collection, {"pkey": sub_record_pkey}) if sub_rec == None: return response # ----------------------- # fk_main_collection_key = utils._db_name_to_fk_name(main_collection) reference_found, reference = validation.find_reference( response, sub_rec, fk_main_collection_key, main_record_pkey) if not reference_found: return response ##### DB OPERATION ##### bulk_action = bulk_db_action.bulk_db_action({ "db_handle": self.db_handle, "app": self.webapp }) bulk_action.remove_two_way_reference( { "collection": main_collection, "record": main_rec }, { "collection": sub_collection, "record": sub_rec }) bulk_action.execute({}) ##### RESPONSE ##### main_response_name = utils._db_name_to_response_name( main_collection) sub_response_name = utils._db_name_to_response_name(sub_collection) if return_record: # get updated records main_rec = validation.find_one(response, self.db_handle, main_collection, {"pkey": main_record_pkey}) sub_rec = validation.find_one(response, self.db_handle, sub_collection, {"pkey": sub_record_pkey}) else: main_rec = main_record_pkey sub_rec = sub_record_pkey response.put("status_code", config.G_STATUS['SUCCESS']['CODE']) response.put("data", { main_response_name: main_rec, sub_response_name: sub_rec, }) except: self.webapp.logger.debug(traceback.format_exc()) response.put("status_code", config.G_STATUS['UNEXPECTED_ERROR']['CODE']) response.put("status", proc_failed_status) response.put("desc", config.G_STATUS['UNEXPECTED_ERROR']['DESC']) # end try return response
class customer_evt_handler(pytavia_event_handler.pytavia_event_handler): mgdDB = database.get_db_conn(config.mainDB) def __init__(self, params): pytavia_event_handler.pytavia_event_handler.__init__(self, params) # end def def process_dukcapil(self, params): app_user_rec = params["app_user_rec"] fk_workflow_item_id = params["fk_workflow_item_id"] nik_ktp_identity = app_user_rec["nik"] dukcapil_resp = dukcapil.dukcapil().process({"nik": nik_ktp_identity}) msg_status = dukcapil_resp.get("status") msg_desc = dukcapil_resp.get("desc") if msg_status != "DUKCAPIL_GET_DATA_SUCCESS": print("[process_dukcapil] - FAILED " + msg_desc) return # end if now_time = int(time.time() * 1000) fk_user_id = app_user_rec["fk_user_id"] fk_app_id = app_user_rec["fk_app_id"] fk_app_user_id = app_user_rec["pkey"] mdl_app_sys_log = database.new(self.mgdDB, "db_application_sys_log") mdl_app_sys_log.put("fk_app_id", fk_app_id) mdl_app_sys_log.put("fk_user_id", fk_user_id) mdl_app_sys_log.put("fk_app_user_id", fk_app_user_id) mdl_app_sys_log.put("status_timestamp", now_time) mdl_app_sys_log.put("status", "DUKCAPIL_SUCCESS") mdl_app_sys_log.put("updated_by", "SLIK") db_handle = database.get_database(config.mainDB) bulk_multi = bulk_db_multi.bulk_db_multi({ "db_handle": db_handle, "app": None }) bulk_multi.add_action( bulk_db_multi.ACTION_UPDATE, "db_queue_workflow_process_item", {"pkey": fk_workflow_item_id}, {"$set": { "is_done": "TRUE", "completed_time": now_time }}) bulk_multi.add_action(bulk_db_multi.ACTION_INSERT, mdl_app_sys_log) bulk_multi.execute({}) # end def def process_slik(self, params): print("[process_slik] - ") print(params) # end def def process_customer_check(self, event): print(event.json()) record_id = event.get("rid") process_item_rec = self.mgdDB.db_queue_workflow_process.find_one( {"_id": record_id}) fk_process_workflow_id = process_item_rec["pkey"] fk_app_user_id = process_item_rec["fk_app_user_id"] workflow_process_task_view = self.mgdDB.db_queue_workflow_process_item.find( { "fk_process_workflow_id": fk_process_workflow_id, "is_done": "FALSE" }) for workflow_process_task_rec in workflow_process_task_view: fk_workflow_item_id = workflow_process_task_rec["pkey"] workflow_task_name = workflow_process_task_rec["task_name"] app_user_rec = self.mgdDB.db_application_user.find_one( {"pkey": fk_app_user_id}) if workflow_task_name == "SLIK": self.process_slik({ "app_user_rec": app_user_rec, "fk_workflow_item_id": fk_workflow_item_id }) elif workflow_task_name == "DUKCAPIL": self.process_dukcapil({ "app_user_rec": app_user_rec, "fk_workflow_item_id": fk_workflow_item_id }) # end if # end for """ Count the done workflow items vs the total number of workflow items. if the numbers match means all the tasks are completed and we can update the workflow to be ready for scoring """ completed_task_count = self.mgdDB.db_queue_workflow_process_item.find({ "fk_process_workflow_id": fk_process_workflow_id, "is_done": "TRUE" }) all_task_count = self.mgdDB.db_queue_workflow_process_item.find({ "fk_process_workflow_id": fk_process_workflow_id, }) if completed_task_count == all_task_count: self.mgdDB.db_queue_workflow_process.update( {"pkey": fk_process_workflow_id}, {"$set": { "workflow_status": "SCORING_READY" }}) # end if # end def def event_switch(self, event): pytavia_event_handler.pytavia_event_handler.event_switch(self, event) try: event_action = event.get("action") if event_action == "INSERT": self.process_customer_check(event) sys.stdout.flush() # end if except: print(traceback.format_exc())
class error_init_event_handler: mgdDB = database.get_db_conn(config.mainDB) def __init__(self, params): pass