def authenticate(self, uid, pwd, bcpass=None, oldpass=None): if not self._rw_userdb: logger.info("no attempt to authenticate, not enough privileges") return False #TODO: use identifiers selecter = SQL("SELECT bcpassword, password FROM userdb.users WHERE username = %s") cur = self._execute(selecter, [uid]) if cur.rowcount == 0: raise ValueError("User not present in database!") bcpass, oldpass = cur.fetchone() if bcpass: if bcpass == self.bchash(pwd, existing_hash = bcpass): return True else: for i in range(self.rmin, self.rmax + 1): if oldpass == self.hashpwd(pwd, str(i)): bcpass = self.bchash(pwd) if bcpass: logger.info("user " + uid + " logged in with old style password, trying to update") try: #TODO: use identifiers updater = SQL("UPDATE userdb.users SET (bcpassword) = (%s) WHERE username = %s") self._execute(updater, [bcpass, uid]) logger.info("password update for " + uid + " succeeded") except Exception: #if you can't update the password then likely someone is using a local install #log and continue logger.warning("password update for " + uid + " failed!") return True else: logger.warning("user " + uid + " logged in with old style password, but update was not possible") return False return False
def authenticate(self, pwd): """ checks if the given password for the user is valid. @return: True: OK, False: wrong password. """ if not 'password' in self._data and not 'bcpassword' in self._data: logger.warning("no password data in db for '%s'!" % self._uid) return False self._authenticated = userdb.authenticate(self._uid, pwd) return self._authenticated
def admin_check(bot, update): db = DBwrapper.get_instance() user = update.message.from_user if user.id in db.get_admins(): return func(bot, update) else: update.message.reply_text( 'You have not the needed permissions to do that!') logger.warning( "User {} ({}, @{}) tried to use admin function '{}'!".format( user.id, user.first_name, user.username, func.__name__))
def parse_and_send_sms(): from main import BOT_ID from main import logger try: bot = telegram.Bot(BOT_ID) users = User.select().where(User.history.is_null(False), User.is_active == True) parse_auto_ria(bot, users) except Exception as e: logger.warning('Task error: %s' % e) return True
def bchash(pwd, existing_hash = None): """ Generate a bcrypt based password hash. Intended to replace Schilly's original hashing algorithm """ try: import bcrypt if not existing_hash: existing_hash = unicode(bcrypt.gensalt()) return bcrypt.hashpw(pwd.encode('utf-8'), existing_hash.encode('utf-8')) except: logger.warning("Failed to return bchash, perhaps bcrypt is not installed"); return None
def bchash(self, pwd, existing_hash=None): """ Generate a bcrypt based password hash. Intended to replace Schilly's original hashing algorithm """ try: import bcrypt if not existing_hash: existing_hash = unicode(bcrypt.gensalt()) return bcrypt.hashpw(pwd.encode('utf-8'), existing_hash.encode('utf-8')) except Exception: logger.warning( "Failed to return bchash, perhaps bcrypt is not installed") return None
def authenticate(self, pwd): """ checks if the given password for the user is valid. @return: True: OK, False: wrong password. """ # from time import time # t1 = time() if not 'password' in self._data: logger.warning("no password data in db for '%s'!" % self._uid) return False for i in range(rmin, rmax + 1): if self._data['password'] == hashpwd(pwd, str(i)): # log "AUTHENTICATED after %s!!" % (time() - t1) self._authenticated = True break return self._authenticated
def __init__(self): database_path = os.path.join(self.dir_path, "pg4030_database.db") if not os.path.exists(database_path): logger.warning("File '" + database_path + "' does not exist! Trying to create one.") try: self.create_database(database_path) except Exception as ex: logger.error( "An error has occurred while creating the database!", ex) self.connection = sqlite3.connect(database_path) self.connection.text_factory = lambda x: str(x, 'utf-8', "ignore") self.cursor = self.connection.cursor()
def authenticate(self, uid, pwd, bcpass=None, oldpass=None): if not self._rw_userdb: logger.info("no attempt to authenticate, not enough privileges") return False #TODO: use identifiers selecter = SQL( "SELECT bcpassword, password FROM userdb.users WHERE username = %s" ) cur = self._execute(selecter, [uid]) if cur.rowcount == 0: raise ValueError("User not present in database!") bcpass, oldpass = cur.fetchone() if bcpass: if bcpass == self.bchash(pwd, existing_hash=bcpass): return True else: for i in range(self.rmin, self.rmax + 1): if oldpass == self.hashpwd(pwd, str(i)): bcpass = self.bchash(pwd) if bcpass: logger.info( "user " + uid + " logged in with old style password, trying to update" ) try: #TODO: use identifiers updater = SQL( "UPDATE userdb.users SET (bcpassword) = (%s) WHERE username = %s" ) self._execute(updater, [bcpass, uid]) logger.info("password update for " + uid + " succeeded") except Exception: #if you can't update the password then likely someone is using a local install #log and continue logger.warning("password update for " + uid + " failed!") return True else: logger.warning( "user " + uid + " logged in with old style password, but update was not possible" ) return False return False
def _run(self, ds): tmp_file_name, tmp_file_name_with_path = BackupJob.construct_filename( self.mongo_config.prefix, # need an array [self.mongo_config.database], self.mongo_config.suffix, self.base_config.tmp_folder, self.construct_dt(ds)) try: # dump mongo collection to file # mongodump --username xxx --password xxx --host xxx --db xxx --out xxx mongo_dump_command = "mongodump --host {} --username {} --password {} --db {} ".format( self.mongo_config.host, self.mongo_config.username, self.mongo_config.password, self.mongo_config.database, ) if self.mongo_config.password else "mongodump --host {} --db {}".format( self.mongo_config.host, self.mongo_config.database) command = "{} --gzip --archive={}".format(mongo_dump_command, tmp_file_name_with_path) logger.debug("running {}".format(command)) c = delegator.run(command) logger.warning("dumped back up file {}".format(tmp_file_name)) if c.return_code != 0: raise RuntimeError(c.std_err) # upload if not dry_run if not self.base_config.dry_run: self.uploader.upload(tmp_file_name, tmp_file_name_with_path) except (RuntimeError, AssertionError) as e: # log logger.error(e) finally: # delete if self.base_config.delete_tmp_file: BackupJob.safe_delete(tmp_file_name_with_path) else: logger.warning("tmp file deletion is off!")
def run(self): tmp_file_name, tmp_file_name_with_path = BackupJob.construct_filename( self.sql_config.prefix, # need an array [self.sql_config.database], self.sql_config.suffix, self.base_config.tmp_folder) try: # dump sql to file # mysqldump -h xxx -d xxx -u root | gzip --best | openssl des -salt -k xxxxxx sql_dump_command = "mysqldump -h{} -u{} -p{} {}".format( self.sql_config.host, self.sql_config.username, self.sql_config.password, self.sql_config.database ) if self.sql_config.password else "mysqldump -h {} -u {} {}".format( self.sql_config.host, self.sql_config.username, self.sql_config.database) command = "{} | gzip --best | openssl des -salt -k {} > {}".format( sql_dump_command, self.base_config.passphrase, tmp_file_name_with_path) logger.debug("running {}".format(command)) c = delegator.run(command) logger.warning("dumped back up file {}".format(tmp_file_name)) if c.return_code != 0: raise RuntimeError(c.std_err) # upload if not dry_run if not self.base_config.dry_run: self.uploader.upload(tmp_file_name, tmp_file_name_with_path, self.sql_config.expired) except (RuntimeError, AssertionError) as e: # log logger.error(e) finally: # delete if self.base_config.delete_tmp_file: BackupJob.safe_delete(tmp_file_name_with_path) else: logger.warning("tmp file deletion is off!")
def run(self): tmp_file_name, tmp_file_name_with_path = BackupJob.construct_filename( self.redis_config.prefix, # need an array ["redis"], self.redis_config.suffix, self.base_config.tmp_folder) rdb_tmp_file_name, rdb_tmp_file_name_with_path = BackupJob.construct_filename( self.redis_config.prefix, # need an array ["redis", "rdbdump"], "rdb", self.base_config.tmp_folder) try: command = "cp {} {}".format(self.redis_config.rdb_path, rdb_tmp_file_name_with_path) logger.debug("running {}".format(command)) c = delegator.run(command) if c.return_code != 0: raise RuntimeError(c.std_err) command = "gzip -9c {} | openssl des -salt -k {} > {}".format( rdb_tmp_file_name_with_path, self.base_config.passphrase, tmp_file_name_with_path) logger.debug("running {}".format(command)) c = delegator.run(command) if not self.base_config.dry_run: self.uploader.upload(tmp_file_name, tmp_file_name_with_path, self.redis_config.expired) except (RuntimeError, AssertionError) as e: # log logger.error(e) finally: # delete if self.base_config.delete_tmp_file: BackupJob.safe_delete(rdb_tmp_file_name_with_path) BackupJob.safe_delete(tmp_file_name_with_path) else: logger.warning("tmp file deletion is off!")
def upload(self, key, file, expire_days=30): """ key: filename file: file path expire_days: lifetime for the file """ bucket_name = self.bucket_name q = Auth(self.access_key, self.secret_key) # get upload token, expires in 10 minutes token = q.upload_token(bucket_name, key, 600) ret, info = put_file(token, key, file) assert ret['key'] == key assert ret['hash'] == etag(file) logger.warning("successfully uploaded {}".format(file)) bucket = BucketManager(q) ret, info = bucket.delete_after_days(bucket_name, key, str(expire_days))
def authenticate(self, pwd): """ checks if the given password for the user is valid. @return: True: OK, False: wrong password. """ # from time import time # t1 = time() if not 'password' in self._data and not 'bcpassword' in self._data: logger.warning("no password data in db for '%s'!" % self._uid) return False bcpass = self._data.get('bcpassword', None) if bcpass: if bcpass == bchash(pwd, existing_hash=bcpass): self._authenticated = True else: for i in range(rmin, rmax + 1): if self._data['password'] == hashpwd(pwd, str(i)): # log "AUTHENTICATED after %s!!" % (time() - t1) bcpass = bchash(pwd) if bcpass: logger.info( "user " + self._uid + " logged in with old style password, trying to update" ) try: self._data['bcpassword'] = bcpass get_users().update_one( {'_id': self._uid}, {'$set': { 'bcpassword': bcpass }}) logger.info("password update for " + self._uid + " succeeded") except: #if you can't update the password then likely someone is using a local install #log and continue logger.warning("password update for " + self._uid + " failed!") self._authenticated = True else: logger.warning( "user " + self._uid + " logged in with old style password, but update was not possible" ) self._authenticated = False break return self._authenticated
def authenticate(self, pwd): """ checks if the given password for the user is valid. @return: True: OK, False: wrong password. """ # from time import time # t1 = time() if not 'password' in self._data and not 'bcpassword' in self._data: logger.warning("no password data in db for '%s'!" % self._uid) return False bcpass = self._data.get('bcpassword', None) if bcpass: if bcpass == bchash(pwd, existing_hash = bcpass): self._authenticated = True else: for i in range(rmin, rmax + 1): if self._data['password'] == hashpwd(pwd, str(i)): # log "AUTHENTICATED after %s!!" % (time() - t1) bcpass = bchash(pwd) if bcpass: logger.info("user " + self._uid + " logged in with old style password, trying to update") try: self._data['bcpassword'] = bcpass get_users().update_one({'_id': self._uid}, {'$set':{'bcpassword':bcpass}}) logger.info("password update for " + self._uid + " succeeded") except: #if you can't update the password then likely someone is using a local install #log and continue logger.warning("password update for " + self._uid + " failed!") self._authenticated = True else: logger.warning("user " + self._uid + " logged in with old style password, but update was not possible") self._authenticated = False break return self._authenticated
def placeTower(self, t, x, y, new=False): """Positions tower and updates game state accordingly.""" grid = self.grid placed = False if t.price <= self.gold or self.debug: try: gx, gy = self.window.getGridPos(x, y) if (gx, gy) in grid.t_grid: placed = True except LookupError or ValueError as err: logger.debug("Available square not found: {0}".format(err)) if placed: new_g = gx, gy new_rg = self.window.getWindowPos(gx, gy) if not self.debug: self.gold -= t.price w_grid = grid.w_grid t.selected = False t.updatePos(new_rg[0], new_rg[1], new_g[0], new_g[1]) t.id = self.tower_count self.tower_count += 1 if new: self.towers.append(t) logger.debug("Towers: {0}".format(len(self.towers))) update = False if new_g in grid.path: update = True else: for p in grid.path: if new_g in get_diagonal( w_grid, p[0], p[1] ): update = True break elif new_g in get_neighbors( w_grid, p[0], p[1] ): update = True break if update: for m in self.mobs: if m not in self.pf_queue: if check_path(m, w_grid, new_g): self.pf_queue.append(m) if not grid.update(new="dry"): logger.warning("TOWER BLOCKING PATH") t.sell() logger.debug("New path for grid: {0}".format(update)) logger.debug( "Tower placed at [{0},{1}]".format(new_g[0], new_g[1]) ) elif t in self.towers: self.towers.remove(t) grid.update(new=False) else: self.active_tower = None self.mouse_drag_tower = None self.selected_mouse = None
if year_range == "Pre1918": rv["either"] = dict([(k, v - 1.34) for k, v in rv["default"].items() if type(v) == float]) rv["both"] = dict([(k, v - 0.87) for k, v in rv["default"].items() if type(v) == float]) if year_range == "Pre1949": rv["either"] = dict([(k, v - 0.35) for k, v in rv["default"].items() if type(v) == float]) rv["both"] = dict([(k, v - 0.87) for k, v in rv["default"].items() if type(v) == float]) if year_range == "Pre1964": rv["either"] = dict([(k, v - 0.81) for k, v in rv["default"].items() if type(v) == float]) rv["metadata"] = { "Wohnlage": self.area_rating, "Lärmbelastung": self.noise_impact, "Stadtgebiet": self.stadtgebiet } logger.info("RV: {}".format(rv)) return rv if __name__ == "__main__": logger.warning("Resetting database...") from main import create_app # db.create_all(app=create_app())
def error(bot, update, error): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, error)