def response_message(self,request): try: in_key = self.settings['in-key'] out_key = self.settings['out-key'] openid = self.parameters['FromUserName'] ghid = self.parameters['ToUserName'] content = self.parameters['Content'] dao = MenuDao() state = dao.query_current_status(ghid,openid) # 或得当前用户状态 # 判断用户第一次输入 if content == '菜单': # 一级菜单 dao.create_status(ghid,openid,'菜单a') # 新建菜单,设置状态 result = dao.query_all_menu() # 菜单列表 if result is not None: return all_mp_menu %(openid,ghid,int(mktime(localtime())),self.response(result)) elif (content=='1') or (content=='2'): # 二级菜单 statea = dao.query_current_status(ghid,openid) if statea == '菜单a': dao.create_status(ghid,openid,'菜单b') # 改变状态 result = dao.query_bottom_menu(content) #进入二级菜单 if result is not None: return bottom_menu %(self.parameters['FromUserName'],self.parameters['ToUserName'],int(mktime(localtime())),self.response(result)) elif content=='3': # 返回一级菜单 stateb = dao.query_current_status(ghid,openid) if stateb == '菜单b': dao.create_status(ghid,openid,'菜单a') result = dao.query_all_menu() if result is not None: return all_mp_menu %(self.parameters['FromUserName'],self.parameters['ToUserName'],int(mktime(localtime())),self.response(result)) else: return textTmpl %(self.parameters['FromUserName'],self.parameters['ToUserName'],int(mktime(localtime())),u'您的输入有误!') except: import traceback log(traceback.format_exc())
def get(self): db.log(self.request.remote_ip, "web_root_access") file = "html/" + ("instructor-dashboard.html" if isInstructorVlan(self.request.remote_ip) else "student-dashboard.html") with open(file, 'rb') as f: data = f.read() self.write(data) self.finish()
def post(self): studyid = self.get_current_study() email = self.get_argument('email', None) username = self.get_argument('username', None) password = self.get_argument('password', None) if email is None or username is None or password is None or email.strip() == '' or username.strip() == '' or password.strip() == '': self.redirect(self.reverse_url('index')) email = email.lower().strip() self.set_secure_cookie("form_email", email) self.set_secure_cookie("form_username", username) domain = email[email.find('@')+1:] #if domain in ['exchange.com', 'hotmail.com', 'live.com']: emailType = db.EmailType.HOTMAIL #else: emailType = db.EmailType.EXCHANGE emailType = db.EmailType.EXCHANGE authid = db.insertAuthRequest(username, email, password, emailType, studyid) self.set_authid(authid) # only add if there is no other task in the queue for the same person if not db.hasTask(email, studyid): db.pushTask(email, studyid, authid=authid) print 'Pushtask with', studyid db.log(email=email, ip=self.request.remote_ip, module="AuthEWS", msg='Added a fetching task') self.redirect(self.reverse_url('auth'))
def response_message(self, request): import traceback try: import urllib2 from hashlib import sha1 url = self.settings['url'] token = self.settings['token'] timestamp = request.arguments.get('timestamp')[0] nonce = request.arguments.get('nonce')[0] signature = sha1((''.join( sorted([token, timestamp, nonce]) ))).hexdigest() signature_query_str = '&'.join([ 'timestamp=%s' % timestamp, 'nonce=%s' % nonce, 'signature=%s' % signature, ]) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) request = urllib2.Request('%s%s%s' % (url, ('?' if '?' not in url else '&'), signature_query_str)) # log('%s%s%s' % (url, ('?' if '?' not in url else '&'), signature_query_str)) # log(self.request.body) response = opener.open(request, self.request.body) return log(response.read()) except: log(traceback.format_exc())
def packetHandler(pkt): pprint.pprint(pkt) global start if pkt.haslayer(Dot11Beacon): radioTap = pkt.getlayer(Dot11) temp = radioTap.getlayer(Dot11Elt) if temp: if temp.info == xtics['essid']: # essid bssid = radioTap.addr2 # bssid channel = str(func.get_channel(temp.payload.payload.info)) # channel # detection rogue xtics['bssid'] = xtics['bssid'].lower() if (xtics['channel'] == channel) and (xtics['bssid'] == bssid): #print('authorized AP') pass else: if xtics['channel'] != channel: xtics['entropy'] -= (-(1.0/14) * math.log(1.0/14, 2)) if xtics['bssid'] != bssid: xtics['entropy'] -= (-(1.0/14) * math.log(1.0/14, 2)) # checking entropy value if xtics['entropy'] < entropy: execution_time = time.time() - start # log data => aps, exec, memory, entropy db.log(0, execution_time, func.get_usage(), xtics['entropy'], 2, distance) xtics['entropy'] = entropy sys.exit(0) start = time.time()
def open(self): print("instructor view connected") db.log(self.request.remote_ip, "instructor_ws_connected") # return error and close if not from instructor vlan if not noCheckInstructorVlan and not isInstructorVlan(self.request.remote_ip): try: self.write_message(json.dumps({ "type": "error", "code": "not_instructor_vlan", "msg": "Cannot access Instructor Dashboard from this VLAN." })) self.close() except: pass _instructorWss.append(self) sendAllPlayersAndDevicesToInstructor() sendToInstructor("internet", { "enabled": _internetEnabled }) sendToInstructor("connected", {}) if _autoSaveExists and _autoSaveChoiceSelected == False: sendToInstructor("promptLoadAutoSave", {}) else: if _game: sendToInstructor("started", {}) sendGameStateToAll()
def startGame(teamConfig, otherConfig, saveFileName): global _players, _teams, _game, _internetEnabled print("startGame", teamConfig) # playerCount = msg["playerCount"] # piCount = msg["piCount"] #teamConfig = msg["teams"] #otherConfig = msg["otherConfig"] _teams = [] # create game # _game = TicTacToe(_teams, _players, _devices) _game = Rings(_teams, _players, _devices) if saveFileName is not None: _game.level = levels._levels[0] restoreGameState(saveFileName) _game.setup(levels._levels[0], _game.teamConfig, _game.otherConfig, sendGameStateToAll, True) else: _game.setup(levels._levels[0], teamConfig, otherConfig, sendGameStateToAll, False) # TODO config all devices setDns() db.log("game", "game_started", {"teams": teamConfig}) sendToAll("started", {}) sendChat(None, "Server", "notification", "Game started!!!") sendGameStateToAll()
def response_message(self, request): import traceback try: import urllib2 from hashlib import sha1 url = self.settings['url'] token = self.settings['token'] timestamp = request.arguments.get('timestamp')[0] nonce = request.arguments.get('nonce')[0] signature = sha1((''.join(sorted([token, timestamp, nonce])))).hexdigest() signature_query_str = '&'.join([ 'timestamp=%s' % timestamp, 'nonce=%s' % nonce, 'signature=%s' % signature, ]) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) request = urllib2.Request( '%s%s%s' % (url, ('?' if '?' not in url else '&'), signature_query_str)) # log('%s%s%s' % (url, ('?' if '?' not in url else '&'), signature_query_str)) # log(self.request.body) response = opener.open(request, self.request.body) return log(response.read()) except: log(traceback.format_exc())
def on_close(self): print("pi disconnected") db.log(self.request.remote_ip, "pi_ws_disconnected") if self.device: self.device.ws = None sendToInstructor("device", self.device.toJSON()) if self.device.player: sendToInstructor("player", self.device.player.toJSON())
def processed(*args, **kwargs): try: return f(*args, **kwargs) except Exception: error_id = new_id(32) db.log("api_uncaught_exception", traceback=format_exc(), error_id=error_id) return {"status": 2, "error_id": error_id}
def post(self, token): try: # log('\n'.join(['%s: %s' % (k, v) for k, v in self.request.headers.iteritems()])) # log('\n'.join(['%s: %s' % (k, v) for k, v in self.request.arguments.iteritems()])) plg = create_plugin_by_message(token, self.request) self.write( plg.response_message(self.request) if plg is not None else '') except: import traceback log(traceback.format_exc())
def apply_template(in_address, in_word): try: print("apply") address_count = count_address_word(in_address, in_word) print("address") log(in_address, in_word, address_count) print("log") return template('templates/super5_template', address=in_address, word=in_word, number=address_count) except Exception as e: print("except", e) return template('templates/super5_template', address='none', word='none', number=0)
def get(self): try: openid = self.get_secure_cookie('openid') ghid = self.get_secure_cookie('ghid') dao = WallDao() dao.set_spec_fan_join(ghid, openid) self.set_header('Content-Type', 'text/plain; charset=utf-8') f = dao.get_spec_fan_state(ghid, openid) self.write(str(f)) except: import traceback log(traceback.format_exc())
def protected(*args, **kwargs): token = request.headers.get("X-Token") if token: user_id = db.token_to_user_id(token) if user_id: g.user_id = user_id return f(*args, **kwargs) else: db.log("invalid_token") return {"status": 4, "message": "会话已失效"} else: db.log("no_token") return {"status": 3, "message": "需要登录"}
def on_message(self, message): print("kali received: ", self.player.name if self.player else 'no player', message) # db.log(self.player.name if self.player else self.ip, "kali_msg", argStr = message) try: msg = json.loads(message) if msg["type"] == "login": ip = msg["ip"] if ip == None or len(ip) == 0: ip = self.request.remote_ip self.ip = ip self.player = findPlayerByIpVlan(ip) if self.player: db.log(self.request.remote_ip, "kali_login", {"srcIP": ip, "player": self.player.name}) self.player.kaliWs = self sendToInstructor("player", self.player.toJSON()) else: db.log(self.request.remote_ip, "kali_login", {"srcIP": ip}) _unclaimedKalis.append(self) self.write_message(json.dumps({"type":"login", "result":"ok"})) autoSaveGameState() except Exception as e: print("kali msg error: " + str(e)) traceback.print_exc() db.log(self.request.remote_ip, "kali_msg_error", argStr = message) db.log("app", "error", argStr = traceback.format_exc())
def log_function(handler): status = handler.get_status() if status >= 400: if status >= 500: event = "web_error_server" else: event = "web_error_access" info = { "status": status, "method": handler.request.method, "url": handler.request.uri, "remoteIP": handler.request.remote_ip } db.log(handler.request.remote_ip, event, info) print("WEB ERROR: " + json.dumps(info, indent=4))
def register(): if request.method == "GET": return render_template("register.html") else: try: if not require_fields("username", "password", "email"): raise AppError("必填项未填") db.new_user(request.form["email"], request.form["username"], request.form["password"]) return redirect("/") except AppError as e: db.log("register_failure", username=request.form.get("username"), email=request.form.get("email")) return render_template("register.html", errors=(e.message, ))
def login(): if request.method == "GET": return render_template("login.html", url=url_for("login", next=request.args.get("next", "/"))) else: try: if not require_fields("username", "password"): raise AppError("必填项未填") session["user"] = db.check_password(request.form["username"], request.form["password"]) target = request.args.get("next", "/") return redirect(target) except AppError as e: db.log("login_failure", username=request.form.get("username")) return render_template("login.html", errors=(e.message, ))
def sendChat(player, fromStr, to, msg): data = { "type": "chat", "from": player.name if player else fromStr, "msg": msg } db.log(data["from"], "chat", {"to": to, "msg": msg}) wss = [] if to == "everyone" or to == "notification": data["to"] = "Everyone" if to == "everyone" else "__notification__" if player != None: wss += _instructorWss for p in _players.values(): if p != player and p.viewWs: wss.append(p.viewWs) elif to == "instructor": data["to"] = "me" wss += _instructorWss elif to == "team": if player.team: data["to"] = "My Team" for p in player.team.players: if p != player and p.viewWs: wss.append(p.viewWs) elif to.startswith("team:"): name = to.split(":")[1] data["to"] = "My Team" for team in _teams: if team.name == name: for p in team.players: if p.viewWs: wss.append(p.viewWs) else: p = _players[to] data["to"] = "me" if p.viewWs: wss.append(p.viewWs) data = json.dumps(data) for ws in wss: try: ws.write_message(data) except: pass
def packetHandler(pkt): #pprint.pprint(pkt) global start if pkt.haslayer(Dot11Beacon): radioTap = pkt.getlayer(Dot11) temp = radioTap.getlayer(Dot11Elt) if temp: if temp.info == xtics['essid']: # essid bssid = radioTap.addr2 # bssid channel = str(func.get_channel( temp.payload.payload.info)) # channel #print(pkt.show()) #hexdump(pkt) #pkt.psdump('packetFormat') #sys.exit() # detection rogue xtics['bssid'] = xtics['bssid'].lower() if (xtics['channel'] == channel) and (xtics['bssid'] == bssid): #print('authorized AP') pass else: if xtics['channel'] != channel: xtics['entropy'] -= func.lossEntropy() if xtics['bssid'] != bssid: xtics['entropy'] -= func.lossEntropy() # checking entropy value if xtics['entropy'] < entropy: #print('Rogue detected') #print(bssid + '\t' + channel) execution_time = time.time() - start #print(execution_time) #print('[2] ' + str(start)) # log data => aps, exec, memory, entropy db.log(0, execution_time, func.get_usage(), xtics['entropy']) #get_usage() #print('\n') xtics['entropy'] = entropy start = time.time()
def get(self): email = self.current_user studyid = self.get_current_study() if email: self.clear_cookie("email") if email == '*****@*****.**' or studyid: if studyid: self.clear_cookie("studyid") self.redirect('/') return if self.get_argument('delete', False): db.deleteData(email, studyid) db.log(email=email, ip=self.request.remote_ip, module="Logout", msg="logged out and deleted data") self.redirect(self.reverse_url('logout_delete')) else: db.log(email=email, ip=self.request.remote_ip, module="Logout", msg="logged out and saved data") self.redirect(self.reverse_url('logout_save')) # don't logout from google for the web app else: self.redirect('/')
def post(self): from db import log import xml.etree.ElementTree as ET import urllib2 try: root = ET.fromstring(self.request.body) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) request = urllib2.Request(root.find('url').text) if root.find('method').text.upper() == 'GET': response = opener.open(request) elif root.find('method').text.upper() == 'POST': response = opener.open(request, root.find('data').text.encode('utf-8')) self.write(response.read()) except: import traceback log(traceback.format_exc()) self.write_error(500)
def on_message(self, message): print("pi received: ", self.device.id if self.device else 'no device', message) # db.log(self.device.player.name if self.device.player else self.device.ip, "pi_msg", argStr = message) global _devices try: msg = json.loads(message) if msg["type"] == "login": id = msg["deviceId"] ip = msg["ip"] if ip == None or len(ip) == 0: ip = self.request.remote_ip if ip in _devices: self.device = _devices[ip] self.device.id = id self.device.ip = ip else: self.device = Device(ip, id) _devices[ip] = self.device self.device.ws = self if self.device.player == None: self.device.player = findPlayerByIpVlan(ip) if self.device.player: self.device.player.device = self.device self.device.name = self.device.player.name + "'s Pi" db.log(self.request.remote_ip, "pi_login", { "srcIP": ip, "player": self.device.player.name }) sendToInstructor("player", self.device.player.toJSON()) else: db.log(self.request.remote_ip, "pi_login", {"srcIP": ip}) sendToInstructor("device", self.device.toJSON()) self.write_message( json.dumps({ "type": "login", "result": "ok" })) elif msg["type"] == "event": event = msg["event"] args = msg["args"] _game.deviceEvent(self.device, event, args) except Exception as e: print("pi msg error: " + str(e)) traceback.print_exc() db.log(self.request.remote_ip, "pi_msg_error", argStr=message) db.log("app", "error", argStr=traceback.format_exc())
def response_message(self, request): try: in_key = self.settings['in-key'] out_key = self.settings['out-key'] openid = self.parameters['FromUserName'] ghid = self.parameters['ToUserName'] content = self.parameters['Content'] dao = MenuDao() state = dao.query_current_status(ghid, openid) # 或得当前用户状态 # 判断用户第一次输入 if content == '菜单': # 一级菜单 dao.create_status(ghid, openid, '菜单a') # 新建菜单,设置状态 result = dao.query_all_menu() # 菜单列表 if result is not None: return all_mp_menu % (openid, ghid, int(mktime( localtime())), self.response(result)) elif (content == '1') or (content == '2'): # 二级菜单 statea = dao.query_current_status(ghid, openid) if statea == '菜单a': dao.create_status(ghid, openid, '菜单b') # 改变状态 result = dao.query_bottom_menu(content) #进入二级菜单 if result is not None: return bottom_menu % (self.parameters['FromUserName'], self.parameters['ToUserName'], int(mktime(localtime())), self.response(result)) elif content == '3': # 返回一级菜单 stateb = dao.query_current_status(ghid, openid) if stateb == '菜单b': dao.create_status(ghid, openid, '菜单a') result = dao.query_all_menu() if result is not None: return all_mp_menu % (self.parameters['FromUserName'], self.parameters['ToUserName'], int(mktime(localtime())), self.response(result)) else: return textTmpl % (self.parameters['FromUserName'], self.parameters['ToUserName'], int(mktime(localtime())), u'您的输入有误!') except: import traceback log(traceback.format_exc())
def takeMission(self, player, missionId): teamData = self.teamData[player.team] mission = teamData.missions[missionId] db.log(player.name, "take_mission", mission.toJSON()) # if the mission is already started by another player, just send state data if mission.player != None: mission.sendStateDataToPlayer(player) return False try: # don't allow multiple missions by the same player at the same time if "mission" in player.data: if player.data["mission"] == mission: mission.sendStateDataToPlayer(player) return False elif player.data["mission"] != None: player.viewWs.write_message(json.dumps({ "type": "error", "msg": "Cannot work on multiple missions at the same time." })) return False if mission.player != None: player.viewWs.write_message(json.dumps({ "type": "error", "msg": "Mission is taken." })) return False if not mission.unlocked or teamData.currentRing != mission.model["level"]: player.viewWs.write_message(json.dumps({ "type": "error", "msg": "Mission is locked." })) return False except: pass player.data["mission"] = mission mission.player = player self.gotoState(mission, "start") return True
def get(self, token): try: from hashlib import sha1 signature = sha1((''.join( sorted([ token, self.get_argument('timestamp'), self.get_argument('nonce') ])))).hexdigest() #log(signature) #log(params['signature'][0]) if signature == self.get_argument('signature'): # 验证成功 dao = MPSiteDao() if dao.access(token): self.write(self.get_argument('echostr')) else: self.send_error(500) except: import traceback log(traceback.format_exc())
def post(self): email = self.current_user try: if self.get_argument('b64', False): b64 = self.get_argument('b64') png = base64.decodestring(b64) if not os.path.exists('static/snapshots/'): os.mkdir("static/snapshots/") while True: filename = 'static/snapshots/' + str(uuid.uuid4()) + '.png' if not os.path.exists(filename): break f = open(filename, "w") f.write(png) f.close() # send email unless the user is logging out self.write({'success':True ,'url': "https://" + self.request.host + '/' + filename}) else: self.write({'success':False}) except: self.write({'success':False}) db.log(email=email, ip=self.request.remote_ip, module="Snapshot", msg=traceback.format_exc(), level=logging.ERROR)
def response_message(self, request): from db import log from orm import getSession ghid = self.parameters['ToUserName'] openid = self.parameters['FromUserName'] locs = getSession().query(MpLocation).join(MpSite).filter( MpSite.ghid == ghid).order_by(MpLocation.priority) prefix = '%s://%s' % (request.protocol, request.host) url = self.settings['url'] articles = [] for loc in locs: article = {} reply_url = '%s%sdlon=%f&dlat=%f&slon=%s&slat=%s' % ( url, '?' if '?' not in url else '&', loc.lon, loc.lat, self.parameters['Location_X'], self.parameters['Location_Y']) article['Title'] = loc.name article['Description'] = loc.address article['PicUrl'] = loc.thumb article['Url'] = reply_url articles.append(article) return log(articles_reply(prefix, openid, ghid, articles))
def get(self): try: redirect_uri = self.request.protocol + "://" + self.request.host + "/" + client_info['web']['redirect_uris'][0] flow = flow_from_clientsecrets('client_secrets.json', scope=client_info['web']['scope'], redirect_uri=redirect_uri) code = self.get_argument("code", None) if code is None: db.log(email=None, ip=self.request.remote_ip, module="AuthorizerReturned", msg='rejected immersion') self.redirect(self.reverse_url('index')) return studyid = self.get_current_study() credentials = flow.step2_exchange(code) uri = "https://www.googleapis.com/oauth2/v2/userinfo/?alt=json" # user info uri userinfo = self.get_api_response(credentials, uri) email = userinfo['email'] # we practically have the email now # store refresh token state = db.getState(email, studyid) if state is None: state = {'email': email, 'userinfo' : userinfo, 'lastuid': 0, 'version': -1} # new user if studyid: state['studyid'] = studyid # backward compatibility, store userinfo again anyway state['userinfo'] = userinfo # always store the new credentials state['credentials'] = credentials.to_json() db.storeState(email, studyid, state) # we store a secure cookie to remember that user is logged in self.set_secure_cookie("email", email) # only add if there is no other task in the queue for the same person if not db.hasTask(email, studyid): db.pushTask(email, studyid) print 'Pushtask with', studyid db.log(email=email, ip=self.request.remote_ip, module="AuthorizerReturned", msg='Added a fetching task') self.redirect(self.reverse_url('viz')) except: db.log(email=None, ip=self.request.remote_ip, module="AuthorizerReturned", msg=traceback.format_exc(), level=logging.ERROR) self.redirect(self.reverse_url('busy'))
def viewEvent(self, player, event, args): mission = player.data["mission"] if mission and mission.state: if event in mission.state["events"]: if event == "flag": if args in mission.state["events"][event]: db.log(player.name, "correct_flag_submitted", {"mission": mission.id, "flag": args}) self.gotoState(mission, mission.state["events"][event][args]) else: db.log(player.name, "incorrect_flag_submitted", {"mission": mission.id, "flag": args}) try: player.viewWs.write_message(json.dumps({ "type": "incorrectFlag" })) except: pass elif event == "quiz": db.log(player.name, "quiz_submitted", {"mission": mission.id, "answers": args}) answers = mission.state["events"][event]["answers"] nextState = mission.state["events"][event]["nextState"] mission.quizAnswers[mission.state["name"]] = args self.gotoState(mission, nextState)
if mention_name != '@familiarlilt': mentioned = True for m in mentions: if mention.user.id == m['user_id']: # if mention is already in mentioned, or the first word in mention text isn't lilt mentioned = True if mentioned == False: # if user hasn't been mentioned, append it to mentions mentions.append({ 'screen_name': mention.user.screen_name, 'user_id': mention.user.id, 'text': mention.text, 'tweet_id': mention.id }) # get debug tweets if debug == True: db.log(rec, 'Debugging...') debug_mentions = [] d = 1 while db.select('screen_name', 'debug', 'tweet_id', str(d)) != None: debug_mentions.append({ 'screen_name': db.select('screen_name', 'debug', 'tweet_id', str(d)), 'user_id': int(db.select('user_id', 'debug', 'tweet_id', str(d))), 'text': db.select('tweet', 'debug', 'tweet_id', str(d)), 'tweet_id': ''.join(random.choice(string.digits) for _ in range(18)) }) d += 1 # go through mentions from Twitter using Tweepy, gets the latest tweet from all players for mention in debug_mentions: try: mentioned = False mention_name = (mention['text']).split(' ',1)[0].lower()
feeds = parseFeeds(feeds) feeds = downloadArticlesInFeeds(feeds) newArticles = [] for feed in feeds: newArticles.extend(feed.articles) newArticles = parseArticles(newArticles) validArticles = [article for article in newArticles if article.isValid()] duplicateArticlesC = [article.save() for article in validArticles].count(True) for feed in feeds: print '%s => +%d' % (feed.url, len(feed.articles)) feed.save() i += batchSize newArticlesCount += len(newArticles) duplicateArticlesCount += duplicateArticlesC validArticlesCount += len(validArticles) feedsCount += len(feeds) endTime = datetime.utcnow() runTime = round((endTime - startTime).total_seconds(), 2) db.log({ 'startTime': startTime, 'runTime': runTime, 'ip': ip.get_ip_address(), 'feeds': feedsCount, 'newArticles': newArticlesCount, 'duplicateArticles': duplicateArticlesCount, 'validArticles': validArticlesCount }) print("--- %s seconds ---" % runTime)
def open(self): print("kali connected") db.log(self.request.remote_ip, "kali_ws_connected") self.player = None
def open(self): print("pi connected") db.log(self.request.remote_ip, "pi_ws_connected") self.device = None
def on_close(self): print("kali disconnected") db.log(self.request.remote_ip, "kali_ws_disconnected") if self.player: self.player.kaliWs = None sendToInstructor("player", self.player.toJSON())