def delete(table,uid): sql = "delete from %s where id = %s" % (table,uid) try: res = cur.execute(sql) WriteLog("sql").info("delete:%s" % sql) result = {'code':0,'msg':'delete success'} except: result = {'code':1,'msg':'delete false'} WriteLog("sql").error("Execute %s error : %s" % (sql,traceback.format_exc())) return result
def insert(table,field,data): sql = "insert into %s (%s) values (%s)" % (table,','.join(field),','.join(['"%s"' % data[x] for x in field])) try: res = cur.execute(sql) WriteLog("sql").info("insert:%s" % sql) result = {'code':0,'msg':'insert ok'} except: result = {'code':1,'msg':'insert fail'} WriteLog("sql").error("Execute %s error : %s" % (sql,traceback.format_exc())) return result
def updateuser(table,field,data): conditions = ["%s='%s'" % (k,data[k]) for k in field] print conditions sql = "update %s set %s where id = %s" % (table,','.join(conditions),data['id']) try: res = cur.execute(sql) WriteLog("sql").info("updateuser:%s" % sql) result = {'code':0,'msg':'update success'} except: result = {'code':1,'msg':'update false'} WriteLog("sql").error("Execute %s error : %s" % (sql,traceback.format_exc())) return result
def listall(table,field): sql = "select %s from %s" % (','.join(field),table) try: cur.execute(sql) res = cur.fetchall() WriteLog("sql").info("listall:%s" % sql) user = [{k:row[i] for i,k in enumerate(field)} for row in res] result = {'code':0,'msg':user} except: result = {'code':1,'msg':'data is null'} WriteLog("sql").error("Execute %s error : %s" % (sql,traceback.format_exc())) return result
def getone(table,field,data): if data.has_key('name'): sql = 'select %s from %s where name = "%s"' % (','.join(field),table,data['name']) else: sql = 'select %s from %s where id = "%s"' % (','.join(field),table,data['id']) try: cur.execute(sql) res = cur.fetchone() WriteLog("sql").info("getone:%s" % sql) user = {k:res[i] for i,k in enumerate(field)} result = {'code':0,'msg':user} except: result = {'code':1,'msg':'data is null'} WriteLog("sql").error("Execute %s error : %s" % (sql,traceback.format_exc())) return result
def SendMessage(self, text, bytestring=False): user_text = self.frame.pluginhandler.OutgoingPrivateChatEvent( self.user, text) if user_text is None: return (u, text) = user_text my_username = self.frame.np.config.sections["server"]["login"] if text[:4] == "/me ": line = "* %s %s" % (my_username, text[4:]) usertag = tag = self.tag_me else: if text == CTCP_VERSION: line = "CTCP VERSION" else: line = text tag = self.tag_local usertag = self.tag_my_username line = "[%s] %s" % (my_username, line) timestamp_format = self.frame.np.config.sections["logging"][ "private_timestamp"] AppendLine(self.ChatScroll, line, tag, timestamp_format=timestamp_format, username=my_username, usertag=usertag) if self.Log.get_active(): WriteLog( self.frame.np.config.sections["logging"]["privatelogsdir"], self.user, line) if bytestring: payload = text else: payload = ToBeEncoded(self.frame.AutoReplace(text), self.encoding) if self.PeerPrivateMessages.get_active(): # not in the soulseek protocol self.frame.np.ProcessRequestToPeer( self.user, slskmessages.PMessageUser(None, my_username, payload)) else: self.frame.np.queue.put( slskmessages.MessageUser(self.user, payload))
def get_auth_token(): username = request.json.get('username') password = request.json.get('password') user = User.query.filter_by(username=username).first() if not user or not user.verify_password(password): return jsonify({'code': 400, 'msg': '请求失败'}) g.user = user WriteLog('api').info('user is login') token = g.user.generate_auth_token() return jsonify({ 'code': 200, 'msg': '登录成功', 'token': token.decode('ascii') })
def login(): if request.method == 'POST': data = {k: v[0] for k, v in dict(request.form).items()} field = ['name', 'password', 'role', 'status'] result = getone('users', field, data) if result['code'] == 0: if result['msg']['password'] == data['password']: WriteLog("login").info("%s login success" % data['name']) session['name'] = data['name'] session['role'] = result['msg']['role'] return json.dumps(result) else: result['code'] = 1 result['msg'] = '密码错误!' return json.dumps(result) else: result['msg'] = "用户名不存在!" return json.dumps(result) return render_template('login.html')
def main(): writeLog = WriteLog("main.log") writeLog.start() sys.stdout = writeLog sys.stderr = writeLog Xh()
def ShowMessage(self, text, status=None, timestamp=None): if text[:4] == "/me ": line = "* %s %s" % (self.user, self.frame.CensorChat(text[4:])) speech = line[2:] tag = self.tag_me else: line = "[%s] %s" % (self.user, self.frame.CensorChat(text)) speech = self.frame.CensorChat(text) tag = self.tag_remote timestamp_format = self.frame.np.config.sections["logging"][ "private_timestamp"] if status and not self.offlinemessage: AppendLine( self.ChatScroll, _("* Message(s) sent while you were offline. Timestamps are reported by the server and can be off." ), self.tag_hilite, timestamp_format=timestamp_format) self.offlinemessage = 1 if not status and self.offlinemessage: self.offlinemessage = False if status: # The timestamps from the server are off by a lot, so we'll only use them when this is an offline message # Also, they are in UTC so we need to correct them if daylight: timestamp -= (3600 * daylight) else: timestamp += altzone AppendLine(self.ChatScroll, line, self.tag_hilite, timestamp=timestamp, timestamp_format=timestamp_format, username=self.user, usertag=self.tag_username) else: AppendLine(self.ChatScroll, line, tag, timestamp_format=timestamp_format, username=self.user, usertag=self.tag_username) if self.Log.get_active(): WriteLog( self.frame.np.config.sections["logging"]["privatelogsdir"], self.user, line) autoreply = self.frame.np.config.sections["server"]["autoreply"] if self.frame.away and not self.autoreplied and autoreply: self.SendMessage(u"[Auto-Message] %s" % autoreply) self.autoreplied = 1 self.frame.Notifications.new_tts( self.frame.np.config.sections["ui"]["speechprivate"] % { "user": self.frame.Notifications.tts_clean(self.user), "message": self.frame.Notifications.tts_clean(speech) })
def GpgParse(filePath): # { # $filePath ; parses file and stores gpg response in cache # PgpParse { # $filePath = path to file containing the text # if not filePath or not os.path.isfile(filePath) or os.path.isdir(filePath): # { WriteLog('GpgParse: warning: $filePath missing, non-existent, or a directory'); return '' # } if not filePath or not os.path.isfile(filePath) or os.path.isdir(filePath) match = re.findall('([a-zA-Z0-9\.\/]+)', filePath) if match: # { filePath = match[0] # } if match else: # { WriteLog('GpgParse: warning: sanity check failed on $filePath, returning') return '' # } else WriteLog('GpgParse(' + filePath + ')') fileHash = GetFileHash(filePath) if not fileHash or not IsItem(fileHash): # { WriteLog('GpgParse: warning: sanity check failed on $fileHash$ returned by GetFileHash($filePath$), returning') return '' # } if not fileHash or not IsItem(fileHash) CACHEPATH = GetDir('cache'); cachePathStderr = CACHEPATH + "/gpg_stderr" match = re.search('^([a-zA-Z0-9_\/.]+)$', cachePathStderr) if match: # { cachePathStderr = match[0] WriteLog('GpgParse: $cachePathStderr sanity check passed: ' + cachePathStderr) # } if match else: # { WriteLog('GpgParse: warning: sanity check failed, $cachePathStderr = ' + cachePathStderr) return '' # } else pubKeyFlag = 0 encryptedFlag = 0 signedFlag = 0 if not os.path.isfile(cachePathStderr + os.sep + fileHash + '.txt'): # { # no gpg stderr output saved # we've not yet run gpg on this file WriteLog('GpgParse: found stderr output: ' + cachePathStderr + os.sep + fileHash + '.txt') fileContents = GetFile(filePath) #gpg_strings gpgPubkey = '-----BEGIN PGP PUBLIC KEY BLOCK-----' gpgSigned = '-----BEGIN PGP SIGNED MESSAGE-----' gpgEncrypted = '-----BEGIN PGP MESSAGE-----' # gpg_prepare # this is the base gpg command # these flags help prevent stalling due to password prompts gpgCommand = 'gpg --pinentry-mode=loopback --batch ' # basic message classification covering only three cases, exclusively if fileContents.index(gpgPubkey) > -1: #gpg_pubkey WriteLog('GpgParse: found $gpgPubkey') gpgCommand += '--import --ignore-time-conflict --ignore-valid-from ' pubKeyFlag = 1 elif fileContents.index(gpgSigned) > -1: #gpg_signed WriteLog('GpgParse: found $gpgSigned') gpgCommand += '--verify -o - ' signedFlag = 1 elif fileContents.index(gpgEncrypted) > -1: #gpg_encrypted WriteLog('GpgParse: found $gpgEncrypted') gpgCommand += '-o - --decrypt ' encryptedFlag = 1 else: WriteLog('GpgParse: did not find any relevant strings, returning') return '' match = re.search('^([0-9a-f]+)$', fileHash) if match: #todo not sure if this is needed, since $fileHash is checked above fileHash = match[0]; else: WriteLog('GpgParse: sanity check failed, $fileHash = ' + fileHash) return '' #gpg_command_pipe messageCachePath = GetFileMessageCachePath(filePath) + '_gpg' gpgCommand += filePath # file we're parsing gpgCommand += ">" + messageCachePath # capture stdout gpgCommand += "2>" + cachePathStderr + os.sep + fileHash + ".txt " # capture stdeerr WriteLog('GpgParse: ' + fileHash + '; $gpgCommand = ' + gpgCommand) os.system(gpgCommand) # } if not os.path.isfile(cachePathStderr + os.sep + fileHash + '.txt') gpgStderrOutput = GetCache('gpg_stderr' + os.sep + fileHash + '.txt') if gpgStderrOutput is None: # { WriteLog('GpgParse: warning: GetCache(gpg_stderr/$fileHash.txt) returned undefined!') gpgStderrOutput = '' # } if gpgStderrOutput is None if gpgStderrOutput: # { WriteLog('GpgParse: ' + fileHash + '; $gpgStderrOutput = ' + gpgStderrOutput) WriteLog('GpgParse: ' + fileHash + '; $pubKeyFlag = ' + pubKeyFlag) if pubKeyFlag: # { gpgKeyPub = '' match = re.search('([0-9A-F]{16})', gpgStderrOutput) if match: # { # username allowed characters chars filter is here gpgKeyPub = match[0]; DBAddItemAttribute(fileHash, 'gpg_id', gpgKeyPub) match = re.search('"([ a-zA-Z0-9<>&\@.()_]+)"', gpgStderrOutput) if match: # { # we found something which looks like a name aliasReturned = match[0] aliasReturned = re.sub('\<(.+\@.+?)\>', '', aliasReturned) # if has something which looks like an email, remove it if gpgKeyPub and aliasReturned: # { # gpg_naive_regex_pubkey message = GetTemplate('message/user_reg.template') message = re.sub('\$name', aliasReturned, message) message = re.sub('\'$fingerprint', gpgKeyPub, message) DBAddVoteRecord(fileHash, GetTime(), 'pubkey', gpgKeyPub, fileHash) # sub DBAddVoteRecord { # $fileHash, $ballotTime, $voteValue, $signedBy, $ballotHash ; Adds a new vote (tag) record to an item based on vote/ token DBAddItemAttribute(fileHash, 'gpg_alias', aliasReturned) # # DBAddKeyAlias($authorKey, $tokenFound{'param'}, $fileHash); # DBAddKeyAlias('flush'); # gpg author alias shim DBAddKeyAlias(gpgKeyPub, aliasReturned, fileHash) DBAddKeyAlias('flush') ExpireAvatarCache(gpgKeyPub) # does fresh lookup, no cache PutFileMessage(fileHash, message) # } if gpgKeyPub and aliasReturned else: # { pass # } else # } if match else: # { WriteLog('GpgParse: warning: alias not found in pubkey mode') #DBAddItemAttribute($fileHash, 'gpg_alias', '???'); #$message =~ s/\$name/???/g; # } else return gpgKeyPub # } if match # } if pubKeyFlag elif signedFlag: # { gpgKeySigned = '' #gpg_naive_regex_signed match = re.search('([0-9A-F]{16})', gpgStderrOutput) if match: # { gpgKeySigned = match[0]; DBAddItemAttribute(fileHash, 'gpg_id', gpgKeySigned) # } if match match = re.findall('Signature made (.+)', gpgStderrOutput) if match: # { # gpgDateEpoch = #todo convert to epoch time WriteLog('GpgParse: ' + fileHash + '; found signature made token from gpg') signTimestamp = match[0] signTimestamp = signTimestamp.strip() p = subprocess.Popen('date --date="' + signTimestamp + '" +%s', shell=True, stdout=subprocess.PIPE) signTimestampEpoch, _ = p.communicate() signTimestampEpoch = signTimestampEpoch.strip() WriteLog('GpgParse: $signTimestamp = ' + signTimestamp + '; $signTimestampEpoch = ' + signTimestampEpoch) DBAddItemAttribute(fileHash, 'gpg_timestamp', signTimestampEpoch) # } if match return gpgKeySigned # } elif signedFlag elif encryptedFlag: # { #gpg_naive_regex_encrypted DBAddItemAttribute(fileHash, 'gpg_encrypted', 1) PutFileMessage(fileHash, '(Encrypted message)') WriteLog('GpgParse: $encryptedFlag was true, setting message accordingly') return 1 # } elif encryptedFlag else: # { # not a pubkey, just take whatever pgp output for us WriteLog('GpgParse: fallthrough, nothing gpg-worthy found...') return '' # } # } $gpgStderrOutput else: # { # for some reason gpg didn't output anything, so just put the original message # $returnValues{'message'} = GetFile("$cachePathMessage/$fileHash.txt"); #WriteLog('GpgParse: warning: ' + fileHash + '; $gpgStderrOutput was false!'); return '' # } else return ''
PutFileMessage(fileHash, '(Encrypted message)') WriteLog('GpgParse: $encryptedFlag was true, setting message accordingly') return 1 # } elif encryptedFlag else: # { # not a pubkey, just take whatever pgp output for us WriteLog('GpgParse: fallthrough, nothing gpg-worthy found...') return '' # } # } $gpgStderrOutput else: # { # for some reason gpg didn't output anything, so just put the original message # $returnValues{'message'} = GetFile("$cachePathMessage/$fileHash.txt"); #WriteLog('GpgParse: warning: ' + fileHash + '; $gpgStderrOutput was false!'); return '' # } else return '' # } def GpgParse(filePath) for arg in sys.argv[1:]: { # WriteLog('index.pl: $arg1 = ' + arg) if arg and os.path.isfile(arg): # { print(GpgParse(arg)) print() # } if arg and os.path.isfile(arg) # } for arg in sys.argv[1:] exit(1)