Some PEP8 conform changes, noteably line breaks and too long lines and indendantion

pull/3/head
Darksider3 5 years ago
parent 4079166167
commit 4d353e6804

@ -8,164 +8,171 @@ import re, configparser, logging, sqlite3
try: try:
cwd = environ.get('TILDE_CONF') cwd = environ.get('TILDE_CONF')
if cwd is None: if cwd is None:
cwd=getcwd()+"/applicationsconfig.ini" cwd=getcwd()+"/applicationsconfig.ini"
else: else:
if ospath.isfile(cwd) is False: if ospath.isfile(cwd) is False:
cwd=getcwd()+"/applicationsconfig.ini" cwd=getcwd()+"/applicationsconfig.ini"
# cwd is now either cwd/applicationsconfig or $TILDE_CONF # cwd is now either cwd/applicationsconfig or $TILDE_CONF
argparser = argparse.ArgumentParser(description='interactive registration formular for tilde platforms') argparser = argparse.ArgumentParser(description='interactive registration formular for tilde platforms')
argparser.add_argument('-c', '--config', default=cwd, type=str, help='Config file', required=False) argparser.add_argument('-c', '--config', default=cwd, type=str, help='Config file', required=False)
args = argparser.parse_args() args = argparser.parse_args()
CONF_FILE=args.config CONF_FILE = args.config
except: except:
logging.exception("Argumentparser-Exception: ") # intended broad, @TODO check them all for errors instead of everything in one
logging.exception("Argumentparser-Exception: ")
exit(0)
try: try:
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(CONF_FILE) config.read(CONF_FILE)
logging.basicConfig(format="%(asctime)s: %(message)s", filename=config['DEFAULT']['log_file'],level=int(config['LOG_LEVEL']['log_level'])) logging.basicConfig(format="%(asctime)s: %(message)s", filename=config['DEFAULT']['log_file'],
del(cwd) level=int(config['LOG_LEVEL']['log_level']))
REG_FILE=config['DEFAULT']['applications_db'] REG_FILE = config['DEFAULT']['applications_db']
except: except:
logging.exception("logging or configparser-Exception: ") # intended broad, @TODO check them all for errors instead of everything in one
logging.exception("logging or configparser-Exception: ")
exit(0)
VALID_SSH=False VALID_SSH = False
VALID_USER=False VALID_USER = False
def __createTable(cursor, connection): def __createTable(cursor, connection):
try: try:
cursor.execute( cursor.execute(
"CREATE TABLE IF NOT EXISTS applications(" \ "CREATE TABLE IF NOT EXISTS applications("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"\ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
"username TEXT NOT NULL, email TEXT NOT NULL,"\ "username TEXT NOT NULL, email TEXT NOT NULL,"
"name TEXT NOT NULL, pubkey TEXT NOT NULL,"\ "name TEXT NOT NULL, pubkey TEXT NOT NULL,"
"timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, status INTEGER NOT NULL DEFAULT 0);") "timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, status INTEGER NOT NULL DEFAULT 0);")
connection.commit() connection.commit()
except: except sqlite3.Error as e:
logging.exception("Couldn't create needed SQLite Table!") logging.exception("Couldn't create needed SQLite Table! Exception: %s" % e)
def addtotable(cursor, connection, username, name, email, pubkey): def addtotable(cursor, connection, username, name, email, pubkey):
try: try:
cursor.execute("INSERT INTO 'applications'(username, name, email, pubkey)VALUES("\ cursor.execute("INSERT INTO 'applications'(username, name, email, pubkey)VALUES("
"?,?,?,?)", [username, name, email, pubkey]) "?,?,?,?)", [username, name, email, pubkey])
connection.commit() connection.commit()
except: except sqlite3.Error as e:
logging.exception("Couldn't insert user into the db") logging.exception("Couldn't insert user into the db: %s" % e)
# check if sqlite file does exists or already and has our structure # check if sqlite file does exists or already and has our structure
def __checkSQLite(cursor, connection): def __checkSQLite(cursor, connection):
#SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'; # SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='applications'") cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='applications'")
res=cursor.fetchall() res = cursor.fetchall()
if res== []: if not res:
try: try:
__createTable(cursor, connection) __createTable(cursor, connection)
except: except sqlite3.Error as e:
logging.exception("couldn't create table on given database. Exception: ") logging.exception("couldn't create table on given database. Exception: %s" % e)
else: else:
pass pass
return True return True
def check_username(value): def check_username(value):
global VALID_USER global VALID_USER
if len(value) < 3: if len(value) < 3:
VALID_USER=False VALID_USER=False
return False
try:
from pwd import getpwnam
getpwnam(value)
VALID_USER = False
# intended broad
except Exception:
VALID_USER = True
return True
return False return False
try:
from pwd import getpwnam
getpwnam(value)
VALID_USER=False
except:
VALID_USER=True
return True
return False
# taken from https://github.com/hashbang/provisor/blob/master/provisor/utils.py, all belongs to them! ;) # taken from https://github.com/hashbang/provisor/blob/master/provisor/utils.py, all belongs to them! ;)
def validate_pubkey(value): def validate_pubkey(value):
global VALID_SSH global VALID_SSH
import base64 import base64
if len(value) > 8192 or len(value) < 80: if len(value) > 8192 or len(value) < 80:
VALID_SSH=False VALID_SSH=False
return False return False
value = value.replace("\"", "").replace("'", "").replace("\\\"", "") value = value.replace("\"", "").replace("'", "").replace("\\\"", "")
value = value.split(' ') value = value.split(' ')
types = [ 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', types = [ 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384',
'ecdsa-sha2-nistp521', 'ssh-rsa', 'ssh-dss', 'ssh-ed25519' ] 'ecdsa-sha2-nistp521', 'ssh-rsa', 'ssh-dss', 'ssh-ed25519' ]
if value[0] not in types: if value[0] not in types:
VALID_SSH=False VALID_SSH=False
return False return False
try: try:
base64.decodebytes(bytes(value[1], "utf-8")) base64.decodebytes(bytes(value[1], "utf-8"))
except TypeError: except TypeError:
VALID_SSH=False VALID_SSH=False
return False return False
VALID_SSH=True
return True
VALID_SSH=True
return True
def main(): def main():
print(" ▗▀▖ \n▗▖▖ ▐ ▌ ▌▛▀▖\n▘▝▗▖▜▀ ▌ ▌▌ ▌\n ▝▘▐ ▝▀▘▘ ▘") print(" ▗▀▖ \n▗▖▖ ▐ ▌ ▌▛▀▖\n▘▝▗▖▜▀ ▌ ▌▌ ▌\n ▝▘▐ ▝▀▘▘ ▘")
username = input("Welcome to the ~.fun user application form!\n\nWhat is your desired username? [a-z0-9] allowed:\n") username = input("Welcome to the ~.fun user application form!\n\nWhat is your desired username? [a-z0-9] allowed:\n")
while (not re.match("[a-z]+[a-z0-9]", username)) or (not check_username(username)): while (not re.match("[a-z]+[a-z0-9]", username)) or (not check_username(username)):
username = input("Invalid Username, maybe it exists already?\nValid characters are only a-z and 0-9.\nMake sure your username starts with a character and not a number." \ username = input("Invalid Username, maybe it exists already?\nValid characters are only a-z and 0-9."
"\nWhat is your desired username? [a-z0-9] allowed:\n") "\nMake sure your username starts with a character and not a number."
"\nWhat is your desired username? [a-z0-9] allowed:\n")
fullname = input("\nPlease enter your full name:\n") fullname = input("\nPlease enter your full name:\n")
while not re.match("\w+\s*\w*", username): while not re.match("\w+\s*\w*", username):
fullname = input("\nThat is not your real name.\nPlease enter your full name:\n") fullname = input("\nThat is not your real name.\nPlease enter your full name:\n")
email = input("\nPlease enter your email address:\n")
email = input("\nPlease enter your email address:\n") while not re.match("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):
while not re.match("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): email = input("\nThat is not a valid mail address.\nPlease enter your email address:\n")
email = input("\nThat is not a valid mail address.\nPlease enter your email address:\n")
pubkey = input("\nPlease paste your ssh public key:\n")
while (not re.match("ssh-(\w)+\s(\w+)(\s*)([a-zA-Z0-9@]*)", pubkey)) or (not validate_pubkey(pubkey)):
pubkey = input("\nPlease paste your ssh public key:\n") pubkey = input("\nPlease enter a valid public key. You can show it with ssh-keygen -f .ssh/id_rsa -y on your "
while (not re.match("ssh-(\w)+\s(\w+)(\s*)([a-zA-Z0-9@]*)", pubkey)) or (not validate_pubkey(pubkey)): "local machine.\nPlease enter your pubkey:\n")
pubkey = input("\nPlease enter a valid public key. You can show it with ssh-keygen -f .ssh/id_rsa -y on your local machine.\nPlease enter your pubkey:\n") validate_pubkey(pubkey)
validate_pubkey(pubkey)
print("\nUsername: {0!s}".format(username))
print("Full Name: {0!s}".format(fullname))
print("\nUsername: {0!s}".format(username)) print("Email: {0!s}".format(email))
print("Full Name: {0!s}".format(fullname)) print("Public {0!s}".format(pubkey))
print("Email: {0!s}".format(email))
print("Public {0!s}".format(pubkey)) validation = input("\nIs this information correct? [y/N]")
while not re.match("[yYnN\n]", validation):
print("Please answer y for yes or n for no")
validation = input("\nIs this information correct? [y/N]") validation = input("Is this information correct? [y/N]")
while not re.match("[yYnN\n]", validation): if re.match("[yY]", validation):
print("Please answer y for yes or n for no") print("Thank you for your application! We'll get in touch shortly. 🐧")
validation = input("Is this information correct? [y/N]") try:
if re.match("[yY]", validation): connection=sqlite3.connect(REG_FILE)
print("Thank you for your application! We'll get in touch shortly. 🐧") cursor=connection.cursor()
try: __checkSQLite(cursor, connection)
connection=sqlite3.connect(REG_FILE) addtotable(cursor, connection, username, fullname, email, pubkey)
cursor=connection.cursor() connection.commit()
__checkSQLite(cursor, connection) connection.close()
addtotable(cursor, connection, username, fullname, email, pubkey) except sqlite3.Error as e:
connection.commit() logging.exception("Database {0!s} couldnt be accessed or created. Exception: {0!s}".
connection.close() format(config['DEFAULT']['applications_db'], e))
except: if connection:
logging.exception("Database {0!s} couldnt be accessed or created. Exception:".format(config['DEFAULT']['applications_db'])) connection.close()
connection.close() exit(1)
exit(1)
pass return 0
return 0
if __name__ == "__main__": if __name__ == "__main__":
try: try:
main() main()
exit(0) exit(0)
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass

Loading…
Cancel
Save