def accept(reqId): # Validate input is sql safe. if not validate_sql(reqId): print("Bad SQL - Enter only alphanumeric chars or '.' or '@'.") return False # Add user with fields from request line minus the id field. newUser = [] request = to_sql("SELECT * FROM requests WHERE id = " + str(reqId), "r", "whm.db")['details'][0] for field in request: newUser.append(field) del newUser[0] add_response = add(newUser) # Option if add failed. if add_response[0] == "Failed": print("\n" + add_response[1]) if not cli: return False if input("Would you like to remove the failed request? Y/N: ") in [ "y", "Y" ]: delReq(reqId) else: return False # If add was successful, request is deleted. elif add_response[0] == "Success": delReq(reqId) return True
def newPassword(user_id): # Specify user for new password. printUsers() print("Enter the User ID of user that needs a new password.") user_id = input("User ID: ") #Validate user exists (if user exists, it should also be safe for sql) user_exists = False try: for user in getUsers(group="users"): if user[0] == int(user_id): user_exists = True except: print("\nBad User ID\n") return if not user_exists: print("\nInvalid User ID...\n") return # Attempt to update db. if to_sql( "UPDATE users SET pw = '" + getHash() + "' WHERE user_id = " + str(user_id), "w", "whm.db")['success']: print("\nPassword updated.\n") else: print("\nFailed to update password.\n")
def updateUser(info): # Attempt load current user information into target. target = [-1] for user in getUsers(): if user[0] == int(info[0]): target = user if target[0] == -1: # This indicates a failure. return -1 # For each index in target excluding user_id, username, and admin: for i in range(2, 7): # Set blank info positions to the current value from the db. if not info[i - 1]: info[i - 1] = target[i] # Check sql safety except if working on password. Passwords hashes may have non-standard chars. elif i != 2: if not validate_sql(info[i - 1]): return { 'return': False, 'details': "Input failed sql validation." } # Attempt to run update with sql and return result. if to_sql( "UPDATE users SET pw = '" + info[1] + "', first = '" + info[2] + "', last = '" + info[3] + "', email = '" + info[4] + "', phone = '" + info[5] + "' WHERE user_id = '" + str(info[0]) + "'", "w", "whm.db")['success']: return {'return': True, 'details': "User information updated."} else: return {'return': False, 'details': "Sql failed to run."}
def getUsers(group="users"): # Get raw db lines. data = to_sql("SELECT * FROM " + group, "r", "whm.db")['details'] # result will be build from data with any necessary processing. result = [] # Mark all requesters as non-admins. if group == "requests": for request in data: result.append(request + (0, )) else: result = data return result
def delReq(reqId): # Validate input is sql safe. if not validate_sql(reqId): print("Bad SQL - Enter only alphanumeric chars or '.' or '@'.") return # Attempt to remove request from db. if to_sql("DELETE FROM requests WHERE id = " + str(reqId), "w", "whm.db")['success']: if cli: print("\nRequest has been removed.\n") else: if cli: print("\nFailed to remove request\n")
def main(): # Create whm.db to track users and requesters if it doesn't exits. This unblockes the web interface. if not os.path.exists( os.path.join(os.path.abspath(os.path.dirname(__file__)), "whm.db")): os.mknod( os.path.join(os.path.abspath(os.path.dirname(__file__)), "whm.db")) if not to_sql( "CREATE TABLE 'requests' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'username' TEXT NOT NULL, 'pw' TEXT NOT NULL, 'first' TEXT NOT NULL, 'last' TEXT NOT NULL, 'email' TEXT NOT NULL, 'phone' TEXT NOT NULL)", "w", "whm.db")['success']: print("Failed to create requests table") if not to_sql( "CREATE TABLE 'users' ('user_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'username' TEXT NOT NULL, 'pw' TEXT NOT NULL, 'first' TEXT NOT NULL, 'last' TEXT NOT NULL, 'email' TEXT NOT NULL, 'phone' TEXT NOT NULL, 'su' BOOLEAN NOT NULL)", "w", "whm.db")['success']: print("failed to create users table") logger.write('whm.db initialized.') # Remember CLI and welcome user. cli = True print("\n\nWelcome to the WHM user management CLI!\n") # Make first user if needed. first_user() # Present an option to review requests if requests are present. requestCount = len(getUsers(group="requests")) if requestCount > 0: print("There are " + str(requestCount) + " new user registration request(s).") if input("Review them now? Y/N: ") in ["Y", "y"]: reviewRequests() else: print("") else: print("No new user registration requests.\n") mainMenu()
def getUser(key, value): # Ensure sql security. if not validate_sql(key) or not validate_sql(value): return {'return': False, 'details': "Failed sql validation"} # Get lines from db. lines = to_sql( 'SELECT * FROM users WHERE "' + str(key) + '" = "' + str(value) + '"', 'r', "whm.db")['details'] # Return user info if sql returned exactly 1 line. if len(lines) == 1: return {'return': True, 'user': lines[0]} else: return {'return': False, 'details': "SQL didn't return exactly 1 line"}
def toggleAdmin(user_id): # User needs to be specified. if user_id == -1: printUsers() print( "Enter the User ID of the user that should have admin rights changed." ) user_id = input("User ID: ") # Finds user by id. target = [-1] try: for user in getUsers(group="users"): if user[0] == int(user_id): target = user except: print("\nBad User ID...\n") return # Validate user was found. if target[0] == -1: if cli: print("\nInvalid User ID\n") return # 1 is made 0 and 0 is made 1. admin = abs(target[7] - 1) # Attempt to update db. if to_sql( "UPDATE users SET su = " + str(admin) + " WHERE user_id = " + str(user_id), "w", "whm.db")['success']: if cli: if admin == 1: print( "\nUser has been made an admin and has full access from the web interface.\n" ) else: print("\nUser has had admin rights removed.\n") logger.write("Toggled Admin Rights - user_id: " + str(user_id) + ", Admin: " + str(admin)) else: if cli: logger.write("Failed to toggle admin rights - user_id: " + str(user_id) + ", Admin: " + str(admin))
def delete(user_id): # User need to be specified. if user_id == -1: printUsers() print("Enter the User ID of the user that should be deleted.") user_id = input("User ID: ") # Validate user_id for sql. if not validate_sql(user_id): print("\nBad SQL - Enter only alphanumeric chars or '.' or '@'.\n") return # Attempt to interact with db. if to_sql("DELETE FROM users WHERE user_id = " + str(user_id), "w", "whm.db")['success']: if cli: print("\nIf user id existed, it has been deleted.\n") logger.write( "If user id existed, it has been deleted - user_id: " + str(user_id)) else: if cli: print("\nFailed to delete specifed user...\n") logger.write("Failed to delete user - user_id: " + str(user_id))
def add(user): # No info provided, collect it from CLI. if len(user) == 0: print( "\nPlease enter new user details. Use only alpha-numeric and '@' and '.'.\n" ) # Loop until user name is accepted. while len(user) == 0: attempt = input("Desired Username: "******"\tBad SQL - Enter only alphanumeric chars or '.' or '@'.") continue # next while # Add username to user if it is available. if not getUser("username", attempt)["return"]: user.append(attempt) else: print("\tUsername is already in use. Please try another.") # Add a password hash to user. user.append(getHash()) # Load user with Firt Name, Last Name, Email, and Phone while validating input is safe for sql. while len(user) < 3: fn = input("First Name: ") if not validate_sql(fn): print( "\tBad SQL - Enter only alphanumeric chars or '.' or '@'.") continue user.append(fn) while len(user) < 4: ln = input("Last Name: ") if not validate_sql(ln): print( "\tBad SQL - Enter only alphanumeric chars or '.' or '@'.") continue user.append(ln) while len(user) < 5: em = input("Email: ") if not validate_sql(em): print( "\tBad SQL - Enter only alphanumeric chars or '.' or '@'.") continue user.append(em) while len(user) < 6: ph = input("Phone: ") if not validate_sql(ph): print( "\tBad SQL - Enter only alphanumeric chars or '.' or '@'.") continue user.append(ph) # Add 0 indicating none admin by default. user.append(0) # Attempt to update db. if getUser("username", user[0])["return"]: return ("Failed", "Username is already in use. Requester should resubmit.") if to_sql("INSERT INTO users VALUES (NULL, " + str(user)[1:-1] + ");", "w", "whm.db")['success']: if cli: print( "\nUser has been added and can now access the web interface.\n" ) logger.write("User added - " + user[0]) return ("Success", "") else: logger.write("Failed to add user - " + user[0])