Actually we allow currently strange things, this fixes it on the usernames

feature-admin-split
Darksider3 5 years ago
parent d517db3b2a
commit 283143104d

@ -49,9 +49,11 @@ class Backup:
@staticmethod @staticmethod
def ImportFromFile(fname: str = CFG.args.file, db: str = CFG.REG_FILE, userids: tuple = tuple([])): def ImportFromFile(fname: str = CFG.args.file, db: str = CFG.REG_FILE, userids: tuple = tuple([])):
if not os.path.isfile(fname): if not os.path.isfile(fname):
return None # @TODO maybe some better output here print(f"File {fname} don't exist")
return None
if not os.path.isfile(db): if not os.path.isfile(db):
return None # @TODO maybe some better output here print(f"The database file {db} don't exist")
return None
if userids: if userids:
pass # empty tuple means everything pass # empty tuple means everything
# noinspection PyBroadException # noinspection PyBroadException
@ -64,34 +66,43 @@ class Backup:
reader = csv.DictReader(f) # @TODO csv.Sniffer to compare? When yes, give force-accept option reader = csv.DictReader(f) # @TODO csv.Sniffer to compare? When yes, give force-accept option
for row in reader: for row in reader:
# if any of this fails move on to the next user, just print a relatively helpful message lel # if any of this fails move on to the next user, just print a relatively helpful message lel
if not lib.validator.checkUsernameLength(row["username"]):
print(f"The username {row['username']} is either too long(>16) or short(<3).")
continue
if not lib.validator.checkUsernameCharacters(row["username"]): if not lib.validator.checkUsernameCharacters(row["username"]):
print(f"The username contains unsupported characters or starts with a number: " print(f"The username contains unsupported characters or starts with a number: "
f"{row['username']}") f"{row['username']}")
continue continue
if not lib.validator.checkUsernameLength(row["username"]):
print(f"The username {row['username']} is either too long(>16) or short(<3).")
continue
if not lib.validator.checkSSHKey(row["pubkey"]): if not lib.validator.checkSSHKey(row["pubkey"]):
print(f"Following SSH-Key isn't valid: {row['pubkey']}") print(f"Following SSH-Key isn't valid: {row['pubkey']}")
continue continue
if lib.validator.checkUserExists(row["username"]):
print(f"The user '{row['username']}' already exists.")
continue
if not lib.validator.checkEmail(row["email"]): if not lib.validator.checkEmail(row["email"]):
print(f"The E-Mail address {row['email']} is not valid.") print(f"The E-Mail address {row['email']} is not valid.")
continue continue
if lib.validator.checkUserExists(row["username"]):
print(f"The user '{row['username']}' already exists.")
continue
if row["status"] == "1": if row["status"] == "1":
try: try:
sysctl.register(row["username"]) # @TODO exception lib.UserExceptions.UserExistsAlready sysctl.register(row["username"])
sysctl.lock_user_pw(row["username"]) # @TODO exception lib.UserExceptions.UnknownReturnCode sysctl.lock_user_pw(row["username"])
sysctl.add_to_usergroup(row["username"]) # @TODO exception lib.UnknownReturnCode sysctl.add_to_usergroup(row["username"])
sysctl.make_ssh_usable(row["username"], row["pubkey"]) # @TODO exception sysctl.make_ssh_usable(row["username"], row["pubkey"])
print(row['username'], "====> Registered.") print(row['username'], "====> Registered.")
except Exception as e: except lib.UserExceptions.UserExistsAlready as UEA:
print(e) pass # @TODO User was determined to exists already, shouldn't happen but is possible
except lib.UserExceptions.UnknownReturnCode as URC:
pass # @TODO Unknown Return Codes. Can happen in various function
except lib.UserExceptions.SSHDirUncreatable as SDU:
pass # @TODO SSH Directory doesn't exist AND couldn't be created. Inherently wrong design!
except lib.UserExceptions.ModifyFilesystem as MFS:
pass # @TODO Same as SSH Dir but more general, same problem: Wrong Permissions,
# Missing Dirs etc
except Exception as E: # @TODO well less broad is hard to achieve Kappa
print(E)
continue continue
elif row["status"] == "0": elif row["status"] == "0":
print(row['username'] + "not approved, therefore not registered.") print(row['username'] + " not approved, therefore not registered.")
try: try:
sql.safequery( sql.safequery(
"INSERT INTO `applications` (username, name, timestamp, email, pubkey, status) " "INSERT INTO `applications` (username, name, timestamp, email, pubkey, status) "
@ -100,8 +111,8 @@ class Backup:
except OSError as E: except OSError as E:
pass pass
print(f"UUFFF, something went WRONG with the file {fname}: {E}") print(f"UUFFF, something went WRONG with the file {fname}: {E}")
except Exception as e: except Exception as didntCatch:
print(f"Exception! UNCATCHED! {type(e)}") print(f"Exception! UNCATCHED! {type(didntCatch)}")
return True return True

@ -3,10 +3,12 @@ import pwd
def checkUsernameCharacters(username: str): def checkUsernameCharacters(username: str):
if re.match("[a-z]+[a-z0-9]", username): if " " not in username and "_" not in username and username.isascii() and username.islower() and \
return True not username[0].isnumeric():
else: if not re.search(r"\W+", username):
return False if not re.search("[^a-z0-9]", username):
return True
return False
def checkUsernameLength(username: str): def checkUsernameLength(username: str):
@ -21,9 +23,9 @@ def checkUserExists(username: str):
try: try:
pwd.getpwnam(username) pwd.getpwnam(username)
except KeyError: except KeyError:
return True # User already exists return False # User already exists
else: else:
return False # User doesnt exist return True # User doesnt exist
def checkSSHKey(key: str): def checkSSHKey(key: str):

@ -77,6 +77,12 @@ def __checkSQLite(cursor, connection):
def check_username(value): def check_username(value):
global VALID_USER global VALID_USER
if " " in value or "_ " in value or not value.isascii() or not value.islower() or value[0].isnumeric():
VALID_USER = False
return False
if re.search(r"\W+", value):
VALID_USER = False
return False
if len(value) < 3: if len(value) < 3:
VALID_USER = False VALID_USER = False
return False return False

Loading…
Cancel
Save