class Clients(object): """ Работа с отображением объектов Клиент """ _cp_config = { 'auth.require': [member_of('users')] } @cherrypy.expose def index(self): tmpl = lookup.get_template("clients.html") session_context = cherrypy.session.get('session_context') session_context['back_ref'] = '/clients' session_context['menu'] = 'clients' session = rwObjects.Session() objs = session.query(rwObjects.Client).all() obj_keys = [] session.close() if objs: obj_keys = objs[0].get_attrs() f = objs[0].get_fields() return tmpl.render(obj=objs, keys=obj_keys, session_context=session_context, all_f=f[0], view_f=f[1]) else: return tmpl.render(obj=objs, keys=obj_keys, session_context=session_context, all_f={"": ""}, view_f=[""])
class Root: _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() restricted = RestrictedArea() @cherrypy.expose @require() def index(self): return """This page only requires a valid login.""" @cherrypy.expose def open(self): return """This page is open to everyone""" @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin") ) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
class RestrictedArea: # all methods in this controller (and subcontrollers) is # open only to members of the admin group _cp_config = {'auth.require': [member_of('admin')]} @cherrypy.expose def index(self): return """This is the admin only area."""
class Root: _cp_config = { 'tools.sessions.on': True, 'tools.auth.on': True } auth = AuthController() restricted = RestrictedArea() def generatelogoutbutton(self): return """<form method="post" action="/auth/logout"><input type="submit" value="log out" />""" @cherrypy.expose @require() def generate(self): return open("generate.html") @cherrypy.expose @require() def index(self): s = "<html><body>This page only requires a valid login. You are logged in as: " + cherrypy.request.login s += self.generatelogoutbutton() s += "<br><br>" s += "<a href=/auth/logout>Logout</a><br>" if cherrypy.request.login == 'joe': s += "<a href=/only_for_joe>Only For Joe</a><br>" if member_of("admin"): s += "<a href=/only_for_joe_admin>Only For Joe Admin</a><br>" s += "<a href=/generate>Generate Random String</a><br>" s += "<a href=/open>Open page</a><br>" s += "</body></html>" return s @cherrypy.expose def open(self): s = "This page is open to everyone. " return s @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin")) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
class Any_object(object): """ Работа любыми объектами """ _cp_config = { 'auth.require': [member_of('users')] } def _cp_dispatch(self, vpath): """ Обработка REST URL """ if len(vpath) == 1: cherrypy.request.params['uuid'] = vpath[0] print "Показываем объект : ", vpath return ShowObject() elif len(vpath) == 2 and vpath[1] == 'edit': cherrypy.request.params['uuid'] = vpath[0] print "Редактируем объект : ", vpath return EditObject() elif len(vpath) == 2 and vpath[1] == 'frame': cherrypy.request.params['uuid'] = vpath[0] print "Выводим данные объекта во фрейм : ", vpath return ShowObject() elif len(vpath) == 2 and vpath[1] == 'save': print "Сохраняем объект : ", vpath cherrypy.request.params['uuid'] = vpath[0] return SaveObject() elif len(vpath) == 2 and vpath[1] == 'addlink': cherrypy.request.params['uuid'] = vpath[0] print "Связываем объект : ", vpath return LinkObject() elif len(vpath) == 2 and vpath[1] == 'savelink': cherrypy.request.params['object_uuid'] = vpath[0] print "Сохраняем связь..." return LinkObject() elif len(vpath) == 0: print "Вывод переадресации : ", vpath return self return vpath @cherrypy.expose def index(self): print "Переадресация на : / " # print cherrypy.request.__dict__ raise cherrypy.HTTPRedirect("/")
def index(self): s = "<html><body>This page only requires a valid login. You are logged in as: " + cherrypy.request.login s += self.generatelogoutbutton() s += "<br><br>" s += "<a href=/auth/logout>Logout</a><br>" if cherrypy.request.login == 'joe': s += "<a href=/only_for_joe>Only For Joe</a><br>" if member_of("admin"): s += "<a href=/only_for_joe_admin>Only For Joe Admin</a><br>" s += "<a href=/generate>Generate Random String</a><br>" s += "<a href=/open>Open page</a><br>" s += "</body></html>" return s
class PcapVisualisationAdmin: _cp_config = {'auth.require': [member_of('admin')]} @cherrypy.expose def index(self): self.init() self.showMenu() # self.showChosenFile() return str(self.doc) def init(self): self.doc = dominate.document(title='Ahahaha') with self.doc.head: link(rel='stylesheet', href='css/style.css') link(rel='stylesheet', href='css/bootstrap.min.css') script(type='text/javascript', src='js/jquery.js') script(type='text/javascript', src="js/three.js") script(type='text/javascript', src="js/Projector.js") script(type='text/javascript', src="js/CanvasRenderer.js") script(type='text/javascript', src="js/OrbitControls.js") script(type='text/javascript', src='js/bootstrap.min.js') script(type='text/javascript', src='js/script.js') def showMenu(self): with self.doc.head: meta(charset="utf-8") meta( name="viewport", content= "width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" ) with nav(cls="navbar navbar-inverse"): with div(cls="container-fluid"): with div(cls="navbar-header"): a("HOME", cls="navbar-brand", href="/home") with ul(cls="nav navbar-nav"): with li(): a("Player", href="/") with li(): a("Statistics new Pcap", href="showStatistics") with li(): a("Statistics existing Pcap", href="searchStatistics") button("DANGER", cls="btn btn-danger navbar-btn")
class Root(object): script = "" _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() @cherrypy.expose #devolve a página incial def index(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/index.html', 'r').read() @cherrypy.expose def login(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/login.html', 'r').read() @cherrypy.expose def register(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/register.html', 'r').read() @cherrypy.expose def createUser(self, firstname_input, lastname_input, username_input, email_input, pwd_input): username = username_input firstname = firstname_input lastname = lastname_input password = pwd_input email = email_input print "username: "******" , password: "******" , email: " + email with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO users (username, firstname, lastname, password, email, groupname) VALUES (?,?,?,?,?,?)''', (username, firstname, lastname, password, email, 'user')) current_dir = os.path.dirname(os.path.abspath(__file__)) directory = current_dir + "/app/uploads/" + str(username) if not os.path.exists(directory): os.makedirs(directory) raise cherrypy.HTTPRedirect("/login") @cherrypy.expose @require(member_of("user")) def changeUser(self, newusername): username = cherrypy.request.login with sqlite3.connect('users.db') as cur: cur.execute( '''UPDATE users SET username = ? WHERE username LIKE ?''', ( newusername, username, )) return @cherrypy.expose @require(member_of("user")) def api(self): effects_ins = [ ("BGR2GRAY", "opencvfunction/BGR2GRAY"), ("canny", "opencvfunction/canny"), ("BGR2HSV", "opencvfunction/BGR2HSV"), ("BGR2HLS", "opencvfunction/BGR2HLS"), ("faceeyedetect", "opencvfunction/faceeyedetect"), ("eyedetect", "opencvfunction/eyedetect"), ("facedetect", "opencvfunction/facedetect"), ("blur", "opencvfunction/blur"), ("opening", "opencvfunction/opening"), ("gradient", "opencvfunction/gradient"), ("tophat", "opencvfunction/tophat"), ("blackhat", "opencvfunction/blackhat"), ("closing", "opencvfunction/closing"), ("erode", "opencvfunction/erode"), ("dilate", "opencvfunction/dilate"), ("simplethresholding", "opencvfunction/simplethresholding"), ("adaptivethresholding", "opencvfunction/adaptivethresholding"), ("medianblur", "opencvfunction/medianblur"), ("gaussianblur", "opencvfunction/gaussianblur"), ("resize", "opencvfunction/resize") ] with sqlite3.connect('users.db') as cur: c = cur.execute('''SELECT * FROM effects''') exist = c.fetchone() if exist is None: print "ADDING ELEMENTS TO DB" cur.executemany( '''INSERT INTO effects(effect_name,effect_filelocation) VALUES (?, ?)''', effects_ins) cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/api.html', 'r').read() @cherrypy.expose @require(member_of("user")) def info(self): username = cherrypy.request.login info = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT firstname, lastname FROM users WHERE username LIKE ?''', (username, )) info = c.fetchall() returnjson = '{"firstname" : "' + str( info[0][0]) + '", "lastname" : "' + str(info[0][1]) + '"}' returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @cherrypy.expose @require(member_of("user")) def getScriptCode(self, effect_name): info = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT effect_filelocation FROM effects WHERE effect_name LIKE ?''', (effect_name, )) info = c.fetchall() print info[0][0] with open(info[0][0]) as fout: contents = json.load(fout) print contents cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(contents) @cherrypy.expose @require(member_of("user")) def account(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/account_info.html', 'r').read() @cherrypy.expose @require(member_of("user")) def histPage(self): cherrypy.response.headers['Content-Type'] = 'text/html' return open('app/image_history.html', 'r').read() @cherrypy.expose @require(member_of("user")) def accountinfo(self): username = cherrypy.request.login info = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT email FROM users WHERE username LIKE ?''', (username, )) info = c.fetchall() returnjson = '{"email" : "' + str( info[0][0]) + '", "username" : "' + str(username) + '"}' returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @require(member_of("user")) @cherrypy.expose def getHistory(self): username = cherrypy.request.login infolist = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT filelocation, script, script_location, timest FROM images WHERE user LIKE ?''', (username, )) infolist = c.fetchall() returnjson = '[' for info in infolist: returnjson += '{"filelocation" : "' + str( info[0]) + '", "script" : ' + str( info[1]) + ', "script_location" : "' + str( info[2]) + '", "timestamp" : "' + str(info[3]) + '"},' returnjson = returnjson[:-1] returnjson += ']' print returnjson returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @require(member_of("user")) @cherrypy.expose def saveToHistory(self): username = cherrypy.request.login filename = os.path.basename(cherrypy.request.headers['x-filename']) info1 = cherrypy.request.headers['info'] info = json.loads(info1) directory = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads/" + str(username) if not os.path.exists(directory): os.makedirs(directory) destination = os.path.join(directory, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) altered_filename, hist_dest = createEffect(info, destination) script_dir = "/uploads/" + str(username) + '/' directory = "/uploads/" + str(username) + '/' + altered_filename script_name = scriptCreator(info, script_dir, altered_filename) script_dest = script_dir + script_name with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO images (filename, script, filelocation, user, script_location) VALUES (?,?,?,?,?)''', (altered_filename, str(info1), directory, str(username), script_dest)) return @require(member_of("user")) @cherrypy.expose def upload(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) info = cherrypy.request.headers['info'] info = json.loads(info) print "\ninfo -->: " + str(info['effect']) + "\n" current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) altered_filename, hist_dest = createEffect(info, destination) if altered_filename == None: returnjson = '{"altered_filename" : "ERROR", "hist_dest" : "The selected effect combination is not allowed"}' else: script_name = scriptCreator(info, "/scripts_upload", altered_filename) returnjson = '{"altered_filename" : "' + str( '/uploads/' + altered_filename) + '", "script_name" : "' + str( script_name) + '", "hist_dest" : "' + str(hist_dest) + '"}' print "\n" + returnjson + "\n" returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) @require(member_of("user")) @cherrypy.expose def uploadMatch(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) print "/app/uploads/" + filename return "/app/uploads/" + filename ######################################################################################### # New functions @require(member_of("user")) @cherrypy.expose def submitNewFunc(self): username = cherrypy.request.login filename = os.path.basename(cherrypy.request.headers['x-filename']) functionInputName = os.path.basename( cherrypy.request.headers['functionInputName']) functionInputNumbArgs = os.path.basename( cherrypy.request.headers['functionInputNumbArgs']) directory = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads/" + str(username) if not os.path.exists(directory): os.makedirs(directory) destination = os.path.join(directory, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) print "++++++++++++++++++++++++++++++++\n" print "filename: " + filename + "\tfunctionInputName: " + functionInputName + "\tfunctionInputNumbArgs: " + functionInputNumbArgs print "\ndestination: " + destination print "\n++++++++++++++++++++++++++++++++" with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO addedFunctions (func_name, numberofargs, functionfilelocation, user) VALUES (?,?,?,?)''', (functionInputName, functionInputNumbArgs, "/app/uploads/" + str(username) + "/" + filename, str(username))) return "/app/uploads/" + str(username) + "/" + filename ######################################################################################### # Load Added functions @require(member_of("user")) @cherrypy.expose def getAddedFunctions(self): username = cherrypy.request.login infolist = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT func_name, numberofargs, functionfilelocation FROM addedFunctions WHERE user LIKE ?''', (username, )) infolist = c.fetchall() print "infolist" print infolist if infolist == []: returnjson = '{"functionInputName" : "noaddedFunctions"}' returnmessage = json.loads(returnjson) print returnmessage cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) returnjson = '[' for info in infolist: returnjson += '{"functionInputName" : "' + info[ 0] + '", "functionInputNumbArgs" : ' + str( info[1]) + ', "functionfilelocation" : "' + info[2] + '"},' returnjson = returnjson[:-1] returnjson += ']' print returnjson returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) ######################################################################################### # Load custom scripts @require(member_of("user")) @cherrypy.expose def getCustomScriptList(self): username = cherrypy.request.login infolist = [] with sqlite3.connect('users.db') as cur: c = cur.execute( '''SELECT custom_name, effects FROM customScripts WHERE user LIKE ?''', (username, )) infolist = c.fetchall() print "infolist" print infolist if infolist == []: returnjson = '{"custom_name" : "nocustomScript"}' returnmessage = json.loads(returnjson) print returnmessage cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) returnjson = '[' for info in infolist: inf = json.loads(info[1]) returnjson += '{"custom_name" : "' + str( info[0]) + '", "effects" : ' + info[1] + '},' returnjson = returnjson[:-1] returnjson += ']' print returnjson returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage) ######################################################################################### # Creation of custom script @require(member_of("user")) @cherrypy.expose def createCustomScript(self, script_lines, name): username = cherrypy.request.login print "\nscript_lines" + script_lines + "\n" with open("custom_Script.txt", "w") as text_file: text_file.write(script_lines) info = scriptParser("custom_Script.txt") returninfo = json.dumps(info) print "\ninfo -->: " + str(info) + "\n" with sqlite3.connect('users.db') as cur: cur.execute( '''INSERT INTO customScripts (custom_name, effects, user) VALUES (?,?,?)''', (name, returninfo, str(username))) cherrypy.response.headers["Content-Type"] = "application/json" return returninfo ######################################################################################### # Script related functions @require(member_of("user")) @cherrypy.expose def getScriptFile(self): list_of_files = glob.glob('app/scripts_upload/*') latest_file = max(list_of_files, key=os.path.getctime) file = open(latest_file, "r") return file @require(member_of("user")) @cherrypy.expose def scriptUpload(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/scripts_upload" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) Root.script = destination print "SCRIPT ----->>>>>>>>>>>" + Root.script return ('/scripts_upload/' + filename) @require(member_of("user")) @cherrypy.expose def viewScript(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) print "FILE NAME ------->>>>>>>>>>>>> " + filename f = open('app/scripts_upload/' + filename, "r") contents = [] for line in f: contents.append(line) print contents return contents @require(member_of("user")) @cherrypy.expose def applyScript(self): filename = os.path.basename(cherrypy.request.headers['x-filename']) print "SCRIPT ----->>>> APPPPPPPPPLY >>>>>>>" + Root.script info = scriptParser(Root.script) returninfo = str(json.dumps(info['effect'])) print "\ninfo -->: " + str(info['effect']) + "\n" current_dir = os.path.dirname( os.path.abspath(__file__)) + "/app/uploads" destination = os.path.join(current_dir, filename) with open(destination, 'wb') as f: shutil.copyfileobj(cherrypy.request.body, f) altered_filename, hist_dest = createEffect(info, destination) if altered_filename == None: return else: returnjson = '{"altered_filename" : "' + str( '/uploads/' + altered_filename) + '", "script_info" : ' + str( returninfo) + ', "hist_dest" : "' + str(hist_dest) + '"}' print "\n\nRETURNJSON ----------- " + returnjson + "\n\n" returnmessage = json.loads(returnjson) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps(returnmessage)
class Case(object): """ """ _cp_config = { 'auth.require': [member_of('users')] } def _cp_dispatch(self, vpath): """ Обработка REST URL """ if len(vpath) == 1 and vpath[1] == 'add': cherrypy.request.params['uuid'] = vpath[0] print "Показываем объект : ", vpath return ShowObject() elif len(vpath) == 2 and vpath[1] == 'edit': cherrypy.request.params['uuid'] = vpath[0] print "Редактируем объект : ", vpath return EditObject() elif len(vpath) == 2 and vpath[1] == 'save': print "Сохраняем объект : ", vpath cherrypy.request.params['uuid'] = vpath[0] return SaveObject() elif len(vpath) == 2 and vpath[1] == 'addlink': cherrypy.request.params['uuid'] = vpath[0] print "Связываем объект : ", vpath return LinkObject() elif len(vpath) == 2 and vpath[1] == 'savelink': cherrypy.request.params['object_uuid'] = vpath[0] print "Сохраняем связь..." return LinkObject() elif len(vpath) == 2 and vpath[1] == 'use': cherrypy.request.params['case_uuid'] = vpath[0] print "Используем кейс..." return self elif len(vpath) == 0: print "Вывод переадресации : ", vpath return self return vpath @cherrypy.expose def add(self, uuid): tmpl = lookup.get_template("add_case.html") session_context = cherrypy.session.get('session_context') session = rwObjects.Session() try: do_object = rwObjects.get_by_uuid(uuid)[0] except Exception as e: return ShowError(str(e)) else: pass obj = rwObjects.Case() obj_keys = obj.get_attrs() f = obj.get_fields() session.close() return tmpl.render(obj=obj, keys=obj_keys, name=obj.NAME, session_context=session_context, all_f=f[0], create_f=f[3], do_object=do_object) @cherrypy.expose def use(self,case_uuid, for_uuid): tmpl = lookup.get_template("use_case.html") session_context = cherrypy.session.get('session_context') session = rwObjects.Session() # Получаем объекты try: obj = rwObjects.get_by_uuid(for_uuid)[0] case = rwObjects.get_by_uuid(case_uuid)[0] except Exception as e: return ShowError(str(e)) else: pass accounts = dict() obj_nbrs = G.neighbors(for_uuid) user_nbrs = G.neighbors(session_context['uuid']) # Создаем список аккаунтов пользователя через которые можно отправить ответ for i in user_nbrs: node = G.graph.node[i]['obj'] if node.__class__.__name__ == 'Account': print "Аккаунт объекта: %s" % node.login accounts[node.uuid] = node # Получаем аккаунт объекта через который можно отправить ответ for i in obj_nbrs: node = G.graph.node[i]['obj'] if node.__class__.__name__ == 'Account': print "Аккаунт пользователя: %s" % node.login obj_account = node soup = BeautifulSoup(obj.__dict__['raw_text_html'], from_encoding="utf8") body_old = str(soup.find('body').contents[0]) session.close() return tmpl.render(obj=obj, case=case, session_context=session_context, body_old=body_old, accounts=accounts, obj_account=obj_account) @cherrypy.expose def send(self, **kwargs): data = cherrypy.request.params session_context = cherrypy.session.get('session_context') print "Данные запроса:" for key in data.keys(): print "%s : %s" % (key,data[key]) # Передаем данные в функцию обрабатывающую отправку сообщений try: status = rwEmail.outgoing_message(data) except Exception as e: print "Case.send. Операция: rwEmail.outgoing_message(data). Ошибка: %s" % str(e) return ShowError(str(e)) print status if not status[0]: print status[0] print status[1] return ShowError(str(status[0])+status[1]) raise cherrypy.HTTPRedirect("/object/%s" % data['obj_uuid']) @cherrypy.expose def create_new(self, **kwargs): data = cherrypy.request.params session_context = cherrypy.session.get('session_context') url = session_context['back_ref'] print "Данные запроса: %s" % data session = rwObjects.Session() # Получаем по uuid создателя кейса try: source = rwObjects.get_by_uuid(session_context['uuid'])[0] except Exception as e: return ShowError("""Case.create_new. Операция: rwObjects.get_by_uuid(). Ошибка : %s""" % str(e)) else: pass # Создаем новый Case и проводим тренировку классификатора расстояний try: status, obj = rwObjects.create_new_object(session, "cases", data, source) except Exception as e: return ShowError("""Ktree.create_new. Операция: rwObjects.create_new_object(session, 'knowledge_tree', params, source). Ошибка : %s""" % str(e)) else: uuid = str(obj.uuid) rwLearn.train_neighbors(session, rwObjects.default_neighbors_classifier) print status # Линкуем новый Case с объектом из которого он был создан try: status = rwObjects.link_objects(session,obj.uuid,data['do_object_uuid']) except Exception as e: return ShowError("""Case.create_new. Операция: rwObjects.link_objects(session,obj.uuid, data['do_object_uuid']). Ошибка : %s""" % str(e)) else: print status[0] print status[1] if not status[0]: return ShowError(str(status[0]) + status[1]) # Линкуем новый Case с узлами Навигатора Знаний коорые были в связаны с объектм родителем do_obj = rwObjects.get_by_uuid(data['do_object_uuid'])[0] print do_obj.NAME print do_obj.__dict__['custom_category'] for cat in do_obj.__dict__['custom_category']: print cat.name try: status = rwObjects.link_objects(session,cat.uuid,obj.uuid) except Exception as e: return ShowError("""Case.create_new. Операция: rwObjects.link_objects(session,obj.uuid,cat). Ошибка : %s""" % str(e)) else: print status[0] print status[1] if not status[0]: return ShowError(str(status[0]) + status[1]) session.close() G.reload() raise cherrypy.HTTPRedirect("/object/%s/addlink" % uuid) @cherrypy.expose @require(any_of(member_of("admin"),member_of("expert"))) def train(self): session_context = cherrypy.session.get('session_context') try: rwLearn.train_neighbors(None, rwObjects.default_neighbors_classifier) except Exception as e: return ShowError("Обновить классификацию кейсов нельзя. " + str(e)) raise cherrypy.HTTPRedirect("/settings?menu=ktree")
class KTree(object): """ Работа с отображением Дерева Знаний """ _cp_config = { 'auth.require': [member_of('users')], 'tools.sessions.on': True } def _cp_dispatch(self, vpath): """ Обаработка REST URL """ if len(vpath) == 1: cherrypy.request.params['category_uuid'] = vpath[0] return ShowKTreeCategory() elif len(vpath) == 0: return self return vpath @cherrypy.expose def index(self): tmpl = lookup.get_template("ktree.html") session = rwObjects.Session() tree = rwObjects.KnowledgeTree() session_context = cherrypy.session.get('session_context') session_context['back_ref'] = '/ktree' session_context['menu'] = 'ktree' cherrypy.session['session_context'] = session_context G.reload() return tmpl.render(obj=tree, session=session, session_context=session_context) @cherrypy.expose def add(self, parent_id, name): tmpl = lookup.get_template("add_ktree.html") session_context = cherrypy.session.get('session_context') session_context['parent_id'] = parent_id session_context['parent_name'] = name session_context['type'] = "custom" session = rwObjects.Session() obj = rwObjects.KnowledgeTree() obj_keys = obj.get_attrs() f = obj.get_fields() experts = rwObjects.get_userlist_in_group(session, 'expert') return tmpl.render(obj=obj, keys=obj_keys, name="раздел Навигатора Знаний", session_context=session_context, all_f=f[0], create_f=f[3], experts=experts[1]) @cherrypy.expose def edit(self, uuid): print uuid tmpl = lookup.get_template("edit_ktree.html") session_context = cherrypy.session.get('session_context') session = rwObjects.Session() obj = rwObjects.get_by_uuid(uuid)[0] f = obj.get_fields() experts = rwObjects.get_userlist_in_group(session, 'expert') all_leafs = obj.get_all(session) # print "OBJ : %s" % obj # print "Status experts : %s" % experts[0] # print "Experts : %s" % experts[1] # print "All leafs : %s" % all_leafs session.close() return tmpl.render(obj=obj, experts=experts[1], all=all_leafs, session_context=session_context, all_f=f[0], edit_f=f[2]) @cherrypy.expose def save(self, **kwargs): data = cherrypy.request.params session_context = cherrypy.session.get('session_context') url = "/settings?menu=ktree" print "Данные из запроса : %s" % data print "\nКонтекст :" % session_context params = dict() try: params['parent_id'] = data['parent_id'] params['name'] = data['name'] params['description'] = data['description'] params['tags'] = data['tags'] params['expert'] = data['expert'] params['action'] = data['action'] except Exception as e: raise e else: pass """ Проверка параметров тут. """ session = rwObjects.Session() try: st = rwObjects.set_by_uuid(data['uuid'], data) except Exception as e: return ShowError("Функция Ktree.save операция rwObjects.set_by_uuid(data['uuid'],data)" + str(e)) else: print st[0] print st[1] session.close() raise cherrypy.HTTPRedirect(url) @cherrypy.expose def create_new(self, **kwargs): data = cherrypy.request.params session_context = cherrypy.session.get('session_context') url = session_context['back_ref'] print "Данные из запроса : " print data print "\nКонтекст :" print session_context print "Переадресация на show_object... ", url session = rwObjects.Session() try: rwObjects.KnowledgeTree.ktree_return_childs(session, data['parent_id']) except Exception as e: return ShowError("""Ktree.create_new. Операция: rwObjects.KnowledgeTree.ktree_return_childs(session, data['parent_id']). Ошибка : %s""" % str(e)) else: pass source = rwObjects.get_by_uuid(session_context['uuid'])[0] """ Создаем новый объект класса KnowledgeTree Для каждого нового типа необходимо добавить в create_new_object условия. Проверка параметров происходит там же, если чего-то не хватает то ловим Exception. """ try: status, obj = rwObjects.create_new_object(session, "knowledge_tree", data, source) except Exception as e: return ShowError("""Ktree.create_new. Операция: rwObjects.create_new_object(session, 'knowledge_tree', params, source). Ошибка : %s""" % str(e)) else: print status session.close() raise cherrypy.HTTPRedirect(url) @cherrypy.expose def classify(self): s = rwLearn.check_conditions_for_classify() if s[0]: session = rwObjects.Session() status = rwLearn.retrain_classifier(session, rwObjects.default_classifier) print status[0] print status[1] session.close() else: return ShowError(s[1]) session_context = cherrypy.session.get('session_context') raise cherrypy.HTTPRedirect(session_context['back_ref'])
class Timeline(object): """ Работа с отображением объектов Reference """ _cp_config = { 'auth.require': [member_of('users')] } def _cp_dispatch(self, vpath): """ Обаработка REST URL """ if len(vpath) == 1 and vpath[0] == 'create': cherrypy.request.params['view_type'] = vpath[0] return self elif len(vpath) == 1 and vpath[0] == 'links': cherrypy.request.params['view_type'] = vpath[0] return self elif len(vpath) == 0: cherrypy.request.params['view_type'] = 'all' return self return vpath @cherrypy.expose def reload(self): print "webapp.Timeline.reload - RELOAD graph..." G.reload() raise cherrypy.HTTPRedirect("/timeline") @cherrypy.expose def index(self, view_type=None, date=None): print "Тип отображения: %s" % view_type print "Дата %s" % date v = ["", "", ""] if view_type == "links": link = 0 v[2] = "active" elif view_type == "create": link = 1 v[1] = "active" else: link = 1 v[0] = "active" print v tmpl = lookup.get_template("timeline.html") session_context = cherrypy.session.get('session_context') session_context['back_ref'] = '/timeline' session_context['menu'] = 'timeline' cherrypy.session['session_context'] = session_context session = rwObjects.Session() try: events = session.query(rwObjects.Reference).filter(rwObjects.Reference.link == link). \ order_by(rwObjects.desc(rwObjects.Reference.timestamp)).all() obj_keys = events[0].get_attrs() fields = events[0].get_fields() except IndexError: obj_keys = rwObjects.rw_parent().get_attrs() fields = rwObjects.rw_parent().get_fields() except Exception as e: return ShowError(str(e)) actors = {} neighbors = G.neighbors(session_context['uuid']) for event in events: event.read(session) # print "Source UUID : %s" % event.source_uuid # print "Target UUID : %s" % event.target_uuid try: obj = rwObjects.get_by_uuid(event.source_uuid)[0] except Exception as e: print e[0] print e[1] return ShowError(str(e)) else: if event.source_uuid not in actors.keys(): actors[event.source_uuid] = obj print "Actor: %s" % actors[event.source_uuid].SHORT_VIEW_FIELDS try: obj = rwObjects.get_by_uuid(event.target_uuid)[0] except Exception as e: print e[0] print e[1] return ShowError(str(e)) else: if event.target_uuid not in actors.keys(): actors[event.target_uuid] = obj print "Actor: %s" % actors[event.target_uuid].SHORT_VIEW_FIELDS # print "events[0].get_fields() : %s" % fields # print "obj_keys : %s " % obj_keys print "All actors: %s" % actors.keys() print "Соседи: %s" % neighbors return tmpl.render(obj=events, keys=obj_keys, session_context=session_context, all_f=fields[0], view_f=fields[1], actors=actors, view_type=v, neighbors=neighbors)
class Employee(object): """ Работа с отображением объектов Employee """ _cp_config = { 'auth.require': [member_of('admin')] } def _cp_dispatch(self, vpath): """ Обаработка REST URL """ if len(vpath) == 1: cherrypy.request.params['uuid'] = vpath[0] return ShowObject() elif len(vpath) == 2 and vpath[1] == 'edit': cherrypy.request.params['uuid'] = vpath[0] return EditObject() elif len(vpath) == 2 and vpath[1] == 'add_account': cherrypy.request.params['employee_uuid'] = vpath[0] return () elif len(vpath) == 0: return self return vpath @cherrypy.expose def index(self): tmpl = lookup.get_template("employee.html") session_context = cherrypy.session.get('session_context') session_context['back_ref'] = '/employee' session = rwObjects.Session() users = session.query(rwObjects.Employee). \ filter_by(comp_id=session_context['comp_id']).all() obj_keys = users[0].get_attrs() f = users[0].get_fields() linked_objects = dict() for user in users: refs = session.query(rwObjects.Reference). \ filter(rwObjects.sqlalchemy.and_(rwObjects.Reference.source_uuid == user.uuid, rwObjects.Reference.target_type == "accounts", rwObjects.Reference.link == 0)).all() linked_objects[user.uuid] = [] for ref in refs: linked_objects[user.uuid].append(rwObjects.get_by_uuid(ref.target_uuid)[0]) session.close() return tmpl.render(obj=users, keys=obj_keys, session_context=session_context, view_f=f[1], all_f=f[0], linked=linked_objects) @cherrypy.expose def add(self): tmpl = lookup.get_template("add_employee.html") session_context = cherrypy.session.get('session_context') session = rwObjects.Session() obj = session.query(rwObjects.Employee). \ filter_by(uuid=session_context['uuid']).one() obj_keys = obj.get_attrs() f = obj.get_fields() return tmpl.render(obj=obj, keys=obj_keys, name=obj.NAME, session_context=session_context, all_f=f[0], create_f=f[3], access_groups=obj.ACCESS_GROUPS) @cherrypy.expose def create_new(self, **kwargs): data = cherrypy.request.params session_context = cherrypy.session.get('session_context') url = session_context['back_ref'] print "Данные запроса: %s" % data params = dict() try: params['login'] = data['login'] params['company_prefix'] = session_context['company_prefix'] params['name'] = data['name'] params['password'] = data['password'] params['surname'] = data['surname'] params['comp_id'] = session_context['comp_id'] params['groups'] = data['groups'] except KeyError as e: return ShowError("Функция Employee.create_new(). Ошибка KeyError: %s" % str(e)) else: pass # Проверяем что этот параметр список, иначе делаем из одного значения список if not isinstance(params['groups'], list): params['groups'] = [params['groups']] """ Проверка параметров тут. """ for k in params.keys(): if params[k] == "" or not params[k]: print "Параметр %s незаполнен." % k return ShowError("Параметр %s незаполнен." % k) source = rwObjects.get_by_uuid(session_context['uuid'])[0] print "Данные из запроса : " print params print "\nКонтекст :" print session_context print "Переадресация на show_object... ", url print source session = rwObjects.Session() try: status, obj = rwObjects.create_new_object(session, "employees", params, source) except Exception as e: return ShowError("Ошибка создания объекта. " + str(e)) else: pass if not status[0]: return ShowError(str(status[0]) + str(status[1])) """ Если возвращен объект, проводим привязку согласно бизнес логики. Если None, значит ошибка. """ if obj: """ Бизнес логика. Связываем нового пользователя с Компанией. """ company = rwObjects.get_company_by_id(params['comp_id']) ref = rwObjects.Reference(source_uuid=company.uuid, source_type=company.__tablename__, source_id=company.id, target_uuid=obj.uuid, target_type=obj.__tablename__, target_id=obj.id, link=0) ref.create(session) session.close() raise cherrypy.HTTPRedirect(url)
class Account(object): """ """ _cp_config = { 'auth.require': [member_of('users')] } @cherrypy.expose def index(self): raise cherrypy.HTTPRedirect("/") @cherrypy.expose def add(self, employee_uuid): """ Ожидает в параметрах UUID сотрудника к которому аккаунт будет привязан. """ tmpl = lookup.get_template("add.html") session_context = cherrypy.session.get('session_context') session_context['back_ref'] = "/settings?menu=accounts" session_context['employee_uuid'] = employee_uuid cherrypy.session['session_context'] = session_context obj = rwObjects.Account() obj_keys = obj.get_attrs() f = obj.get_fields() return tmpl.render(obj=obj, keys=obj_keys, name=obj.NAME, session_context=session_context, all_f=f[0], create_f=f[3], acc_type=rwObjects.rwChannel_type) @cherrypy.expose def create_new(self, **kwargs): data = cherrypy.request.params session_context = cherrypy.session.get('session_context') employee_uuid = session_context.pop('employee_uuid') print employee_uuid print "Данные из запроса : " print data print "\nКонтекст :" print session_context params = {} for p in data.keys(): params[p] = data[p] """ Проверка параметров тут. """ """ Извлекаем создателя и Создаем новый объект """ source = rwObjects.get_by_uuid(session_context['uuid'])[0] session = rwObjects.Session() try: print "Создаем новый аккаунт." status, obj = rwObjects.create_new_object(session, "accounts", params, source) except Exception as e: print e else: print status """ Если возвращен объект, выполняем бизнес логику. Если None, значит ошибка. """ if obj: """ Бизнес логика. Связываем новый аккаунт с его пользователем. Пользователь передается в session_context['employee_uuid'] """ print "Делаем линкование с пользователем при создании аккаунта." rwObjects.link_objects(session, employee_uuid, obj.uuid) session.close() cherrypy.session['session_context'] = session_context print "Переадресация на ", session_context['back_ref'] raise cherrypy.HTTPRedirect(session_context['back_ref'])
class Root(object): auth = AuthController() restricted = RestrictedArea() object = Any_object() employee = Employee() timeline = Timeline() clients = Clients() ktree = KTree() account = Account() cases = Case() @cherrypy.expose @require(member_of("users")) def index(self): tmpl = lookup.get_template("dashboard.html") c = get_session_context(cherrypy.request.login) params = cherrypy.request.headers rwQueue.msg_delivery_for_user.delay(str(c['uuid'])) G.reload() return tmpl.render(params=params, session_context=c, G=G) @cherrypy.expose @require(member_of("admin")) def autoclassify_all_notlinked_objects(self): try: rwLearn.autoclassify_all_notlinked_objects() except Exception as e: return ShowError("Обновить автоклассификацию нельзя. " + str(e)) else: pass raise cherrypy.HTTPRedirect("/settings?menu=ktree") @cherrypy.expose @require(member_of("users")) def settings(self, menu=None): session_context = cherrypy.session.get('session_context') if not menu or menu == "": tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/' session_context['menu'] = "settings" params = cherrypy.request.headers cherrypy.session['session_context'] = session_context return tmpl.render(params=params, session_context=session_context) elif menu == 'company': tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/settings' session_context['menu'] = "company" elif menu == 'employee' or menu == 'accounts': tmpl = lookup.get_template("employee.html") session = rwObjects.Session() # если пользователь с правами администратора, выбираем всех сотрудников if 'admin' in session_context['groups']: users = session.query(rwObjects.Employee). \ filter_by(comp_id=session_context['comp_id']).all() obj_keys = users[0].get_attrs() f = users[0].get_fields() session_context['back_ref'] = '/settings' session_context['menu'] = "employee" # если пользователь с обычными правами, только свой профиль else: users = [rwObjects.get_by_uuid(session_context['uuid'])[0]] obj_keys = users[0].get_attrs() f = users[0].get_fields() session_context['back_ref'] = '/settings' session_context['menu'] = "accounts" linked_objects = dict() for user in users: refs = session.query(rwObjects.Reference). \ filter(rwObjects.sqlalchemy.and_(rwObjects.Reference.source_uuid == user.uuid, rwObjects.Reference.target_type == "accounts", rwObjects.Reference.link == 0)).all() linked_objects[user.uuid] = [] for ref in refs: linked_objects[user.uuid].append(rwObjects.get_by_uuid(ref.target_uuid)[0]) session.close() cherrypy.session['session_context'] = session_context return tmpl.render(obj=users, keys=obj_keys, session_context=session_context, view_f=f[1], all_f=f[0], linked=linked_objects) elif menu == 'clients': tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/settings?menu=clients' elif menu == 'ktree': tmpl = lookup.get_template("ktree_settings.html") session = rwObjects.Session() tree = rwObjects.KnowledgeTree() session_context['back_ref'] = '/settings?menu=ktree' session_context['menu'] = "ktree_settings" return tmpl.render(obj=tree, session=session, session_context=session_context) else: print "меню без указания." tmpl = lookup.get_template("settings_dashboard.html") session_context['back_ref'] = '/settings' session_context['menu'] = "settings" params = cherrypy.request.headers return tmpl.render(params=params, session_context=session_context) @cherrypy.expose @require(member_of("users")) def help(self, menu=None): tmpl = lookup.get_template("help.html") session_context = cherrypy.session.get('session_context') return tmpl.render(session_context=session_context) @cherrypy.expose def open(self): return """This page is open to everyone""" @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin")) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""
class Root: _cp_config = {'tools.sessions.on': True, 'tools.auth.on': True} auth = AuthController() restricted = RestrictedArea() @cherrypy.expose @require() def index(self): return """ This page only requires a valid login. <a href="auth/logout">LOUGOUT</a> """ def get_postform(self, msg="post", from_page="/", username=None): wall1 = wall.wall(username) wall1.body = \ """<form method="post" action="/post"> <input type="hidden" name="from_page" value="%(from_page)s" /> %(msg)s<br /> Post: <input type="text" name="message" /> <br /> <input type="submit" value="Post" /> """ %locals() wall1.pull(username) return wall1.return_html() def post_to_database(self, message, username): con = mdb.connect('localhost', 'testuser', 'test623', 'testdb') with con: cur = con.cursor() query = "INSERT INTO Message(Username, Post) VALUES('%(username)s', '%(message)s')" % locals( ) cur.execute(query) return None return u"database error" @cherrypy.expose @require() def post(self, message=None, from_page="/"): username = cherrypy.session.get(SESSION_KEY) if message == None: return self.get_postform(from_page=from_page, username=username) error_msg = self.post_to_database(message, username) if error_msg: return self.get_postform(self, error_msg, from_page, username) else: raise cherrypy.HTTPRedirect("/post") @cherrypy.expose def gethint(self, q): print "hello" print q return "no suggestion" @cherrypy.expose def open(self): home_page = html_page.html_page("html_src/showhint") return home_page.get_html() @cherrypy.expose @require(name_is("joe")) def only_for_joe(self): return """Hello Joe - this page is available to you only""" # This is only available if the user name is joe _and_ he's in group admin @cherrypy.expose @require(name_is("joe")) @require(member_of("admin") ) # equivalent: @require(name_is("joe"), member_of("admin")) def only_for_joe_admin(self): return """Hello Joe Admin - this page is available to you only"""