General overhaul, better messages, ordered imports etc

pull/4/head
Darksider3 5 years ago
parent 32c6ea7e07
commit 8008fa36b9

@ -1,9 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import ListUsers import configparser
import csv import csv
import io import io
import configparser
import ListUsers
import lib.uis.default as default_cmd # Follows -u, -a, -f flags import lib.uis.default as default_cmd # Follows -u, -a, -f flags
@ -115,7 +116,6 @@ if __name__ == "__main__":
args = default_cmd.argparser.parse_args() args = default_cmd.argparser.parse_args()
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(args.config) config.read(args.config)
try:
L = ListUsers.ListUsers(config['DEFAULT']['applications_db'], L = ListUsers.ListUsers(config['DEFAULT']['applications_db'],
unapproved=args.unapproved, approved=args.approved) unapproved=args.unapproved, approved=args.approved)
fetch = L.get_fetch() fetch = L.get_fetch()
@ -127,5 +127,3 @@ if __name__ == "__main__":
print("nothing to backup!") print("nothing to backup!")
exit(1) exit(1)
exit(0) exit(0)
except KeyboardInterrupt as e:
pass

@ -1,8 +1,9 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import configparser
import csv import csv
import os import os
import configparser
import lib.UserExceptions import lib.UserExceptions
import lib.uis.config_ui # dont go to default, just following -c flag import lib.uis.config_ui # dont go to default, just following -c flag
@ -74,7 +75,7 @@ if __name__ == "__main__":
args = ArgParser.parse_args() args = ArgParser.parse_args()
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(args.config) config.read(args.config)
try:
if not args.Import: if not args.Import:
print("Error, need the import flag") print("Error, need the import flag")
if not args.file: if not args.file:
@ -84,5 +85,3 @@ if __name__ == "__main__":
exit(1) exit(1)
import_from_file(args.file, config['DEFAULT']['applications_db']) import_from_file(args.file, config['DEFAULT']['applications_db'])
exit(0) exit(0)
except KeyboardInterrupt as e:
pass

@ -1,11 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from lib.sqlitedb import SQLiteDB
import lib.uis.default as default_cmd # Follows -u, -a, -f flags
from typing import List # Typing support!
import sqlite3 # sqlite3.Row-Object
import configparser import configparser
import sqlite3 # sqlite3.Row-Object
from typing import List # Typing support!
import lib.uis.default as default_cmd # Follows -u, -a, -f flags
from lib.sqlitedb import SQLiteDB
class ListUsers: class ListUsers:
@ -46,7 +46,7 @@ class ListUsers:
query = "SELECT `username` FROM `applications` WHERE `status` = '1' ORDER BY timestamp ASC" query = "SELECT `username` FROM `applications` WHERE `status` = '1' ORDER BY timestamp ASC"
self.usersFetch = self.db.query(query) self.usersFetch = self.db.query(query)
for users in self.usersFetch: for users in self.usersFetch:
list_str += users["username"]+"\n" list_str += users["username"] + "\n"
return list_str return list_str
def prettyPrint(self) -> None: def prettyPrint(self) -> None:
@ -94,7 +94,6 @@ if __name__ == "__main__":
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(args.config) config.read(args.config)
try:
ret = "" ret = ""
if args.user is not None: if args.user is not None:
L = ListUsers(config['DEFAULT']['applications_db'], unapproved=args.unapproved, approved=args.approved, L = ListUsers(config['DEFAULT']['applications_db'], unapproved=args.unapproved, approved=args.approved,
@ -119,5 +118,3 @@ if __name__ == "__main__":
else: else:
print(ret) print(ret)
exit(0) exit(0)
except KeyboardInterrupt:
pass

@ -1,12 +1,13 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import configparser import configparser
import lib.uis.config_ui # only follow -c flag import sqlite3
import lib.Validator
import lib.sqlitedb
import lib.System import lib.System
import lib.UserExceptions import lib.UserExceptions
import sqlite3 import lib.Validator
import lib.sqlitedb
import lib.uis.config_ui # only follow -c flag
if __name__ == "__main__": if __name__ == "__main__":
lib.uis.config_ui.argparser.description += " - Edit Tilde Users" lib.uis.config_ui.argparser.description += " - Edit Tilde Users"
@ -35,7 +36,6 @@ if __name__ == "__main__":
args = ArgParser.parse_args() args = ArgParser.parse_args()
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read(args.config) config.read(args.config)
try:
db = config['DEFAULT']['applications_db'] db = config['DEFAULT']['applications_db']
if not args.sshpubkey and not args.name and not args.username and not args.email and args.status is None \ if not args.sshpubkey and not args.name and not args.username and not args.email and args.status is None \
and not args.remove: and not args.remove:
@ -145,5 +145,3 @@ if __name__ == "__main__":
exit(1) exit(1)
print(f"Successfully changed '{args.user}'s status to 1 and created on the system.") print(f"Successfully changed '{args.user}'s status to 1 and created on the system.")
exit(0) exit(0)
except KeyboardInterrupt as e:
pass

@ -1,6 +1,7 @@
import os import os
import subprocess
import pwd import pwd
import subprocess
import lib.UserExceptions import lib.UserExceptions
@ -136,7 +137,7 @@ class System:
os.chown(ssh_dir + "authorized_keys", pwd.getpwnam(self.user)[2], pwd.getpwnam(self.user)[3]) os.chown(ssh_dir + "authorized_keys", pwd.getpwnam(self.user)[2], pwd.getpwnam(self.user)[3])
except OSError as e: # by os.chown except OSError as e: # by os.chown
raise lib.UserExceptions.ModifyFilesystem( raise lib.UserExceptions.ModifyFilesystem(
f"Could not chown {ssh_dir} and/or authorized_keys to {self.user} and their group, Exception: {e}",) f"Could not chown {ssh_dir} and/or authorized_keys to {self.user} and their group, Exception: {e}", )
except KeyError as e: # by PWD except KeyError as e: # by PWD
raise lib.UserExceptions.General(f"PWD can't find {self.user}: {e}") raise lib.UserExceptions.General(f"PWD can't find {self.user}: {e}")
return True return True
@ -201,7 +202,7 @@ class System:
rt = subprocess.call(cc) rt = subprocess.call(cc)
if rt != 0: if rt != 0:
raise lib.UserExceptions.UnknownReturnCode( raise lib.UserExceptions.UnknownReturnCode(
f"Could not add user '{self.user}' to group '{group}' with command '{cc}', returned '{rt}'",) f"Could not add user '{self.user}' to group '{group}' with command '{cc}', returned '{rt}'", )
return True return True
@staticmethod @staticmethod
@ -242,7 +243,7 @@ class System:
if ret.returncode != 0 and ret.returncode != 6: # userdel returns 6 when no mail dir was found but success if ret.returncode != 0 and ret.returncode != 6: # userdel returns 6 when no mail dir was found but success
raise lib.UserExceptions.UnknownReturnCode( raise lib.UserExceptions.UnknownReturnCode(
f"Could not delete user with command {cc}. Return code: {ret.returncode}," f"Could not delete user with command {cc}. Return code: {ret.returncode},"
f" stdout/stderr: {stdio+err_io}") f" stdout/stderr: {stdio + err_io}")
return True return True

@ -2,15 +2,21 @@ class General(Exception):
pass pass
class UnknownUser(General): class User(General):
pass pass
class UnknownReturnCode(General): class UnknownUser(User):
pass def __init__(self, name):
Exception.__init__(self, f"Tried to perform action on unknown user '{name}'")
class UserExistsAlready(User):
def __init__(self, name):
Exception.__init__(self, f"User '{name}' is already registered")
class UserExistsAlready(UnknownReturnCode): class UnknownReturnCode(General):
pass pass
@ -26,10 +32,6 @@ class SQLiteDatabaseDoesntExistYet(General):
pass pass
class User(Exception):
pass
class UsernameLength(User): class UsernameLength(User):
pass pass

@ -1,7 +1,8 @@
import re import csv
import pwd import pwd
import re
import lib.sqlitedb import lib.sqlitedb
import csv
def checkUsernameCharacters(username: str) -> bool: def checkUsernameCharacters(username: str) -> bool:
@ -54,9 +55,8 @@ def checkUserExists(username: str) -> bool:
try: try:
pwd.getpwnam(username) pwd.getpwnam(username)
except KeyError: except KeyError:
return True # User already exists
else:
return False return False
return True # User already exists
def checkUserInDB(username: str, db: str) -> bool: def checkUserInDB(username: str, db: str) -> bool:
@ -203,7 +203,7 @@ def checkImportFile(path: str, db: str):
if not lib.Validator.checkEmail(row["email"]): if not lib.Validator.checkEmail(row["email"]):
errstr += f"Line {ln}: E-Mail address of user '{row['username']}' '{row['email']}' is not valid.\n" errstr += f"Line {ln}: E-Mail address of user '{row['username']}' '{row['email']}' is not valid.\n"
valid = False valid = False
if not lib.Validator.checkUserExists(row["username"]) or checkUserInDB(row["username"], db): if lib.Validator.checkUserExists(row["username"]) or checkUserInDB(row["username"], db):
errstr += f"Line {ln}: User '{row['username']}' already exists.\n" errstr += f"Line {ln}: User '{row['username']}' already exists.\n"
valid = False valid = False
if not lib.Validator.checkDatetimeFormat(row["timestamp"]): if not lib.Validator.checkDatetimeFormat(row["timestamp"]):

Loading…
Cancel
Save