def test5_login_password_false(self): """Checks if a user login is successful with wrong password""" umanager = UserManager() response = umanager.registerUser(self.username + "5", "Root@123", "admin") response = umanager.logIn(self.username + "5", "Root123") self.assertEquals(response, "Password incorrect")
def test6_delete_user(self): """Checks if a user is deleted successfully""" umanager = UserManager() response = umanager.registerUser(self.username + "6", "Root@123", "admin") response = umanager.deleteUser(self.username + "6") self.assertEquals(response, "User deleted")
def test3_login_user(self): """Checks if a user login is successful""" umanager = UserManager() response = umanager.registerUser(self.username + "3", "Root@123", "admin") response = umanager.logIn(self.username + "3", "Root@123") self.assertEquals(response, "Log In Success")
def test4_login_username_false(self): """Checks if a user login is successful with wrong username""" umanager = UserManager() response = umanager.registerUser(self.username + "4", "Root@123", "admin") response = umanager.logIn(self.username + "789", "Root@123") self.assertEquals(response, "Unknown user")
def test_login(self): ''' This function will test if we can login as an existing user. ''' userbase = UserManager() username = "******" password = "******" salt = Authenticator.generate_salt() # Create a new user creator = UserCreation(userbase, username, password, salt) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(username) == True) # Login to that user salt = userbase.get_user_salt(username) auther = Authenticator(userbase, username, password, salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() assert (token is not None) assert (token != "") assert (userbase.get_user_from_token(token) == username)
def test_many_bad_logins(self): ''' This test will check if we can login to an existing user with an incorrect password. ''' userbase = UserManager() username = "******" password = "******" wrong_pass = "******" salt = Authenticator.generate_salt() # Create a new user creator = UserCreation(userbase, username, password, salt) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(username) == True) # Try to login many times to the same user. for xx in range(0, 10): salt = userbase.get_user_salt(username) auther = Authenticator(userbase, username, wrong_pass, salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() assert (token is not None) assert (token == "") assert (userbase.get_user_from_token(token) == "")
def main(): ''' This function is the driver function and runs the basic loop that controls program interaction. Functions are stored in a list for easy access via a UI input collector function. active_token is used to store the current active session token. Normal ''' active_token = "" option_functions = { "new_user": create_new_user, "login": login_existing_user, "logout": logout_current_user, "input_error": input_error, "exit": exit_application } # Having no access to database usage, we use a class that manages our # userbase. We will pass this to all of our methods. userbase = UserManager() while (True): show_ui_options(active_token, userbase) active_token = option_functions[gather_user_input()](active_token, userbase) #UI formatting to clear up space. print("\n\n\n\n\n\n")
def openUserManagement(self): self.alertMessage( "User Manager.", "This feature is still in development, some features may not work as expected." ) self.user_manager = UserManager(self.user_id, self.password) self.user_manager.show()
def test2_register_user_exists(self): """Checks if a user is created when same username already exists""" umanager = UserManager() response = umanager.registerUser(self.username + "2", "Root@123", "admin") response = umanager.registerUser(self.username + "2", "Root@123", "user") self.assertEquals(response, "user already exists")
def test_logout_while_not_logged_in(self): ''' This function will test that we can "logout" while not in an active session and no failures will occur. ''' active_token = "" userbase = UserManager() assert (userbase.logout_user(active_token) == "")
def reloadUsers(self): # Remove everything from the list while self.usersView.count() > 0: self.usersView.takeItem(0) # For each user add their name to the view for user in UserManager(): self.usersView.addItem(user['name'])
def handle(self): if self.field.text() and self.fieldPass.text(): # Field are not empty call the user manager and reload the view UserManager().addUser(self.field.text(), self.fieldPass.text()) self.loginWindow.reloadUsers() self.close() else: # Prompt the user that the one of the fields is empty QMessageBox.warning(self, "Puste Pole", "Pola nie mogą być puste.")
def attempt(self): if UserManager().verifyPassword(self.userid, self.field.text()): global coursesWindow coursesWindow = CoursesWindow(self.loginWindow.application) self.close() self.loginWindow.close() coursesWindow.show() else: QMessageBox.warning(self, "Hasło", "Wprowadzone złe hasło")
def test_gather_user_credentials_called(self): ''' This function will test if we are correctly calling the gather_user_creation_details. ''' userbase = UserManager() creator = UserCreation(userbase) creator.gather_user_creation_details = MagicMock(return_value=False) creator.create() creator.gather_user_creation_details.assert_called_once()
def __init__(self): """Initialize the server manager object. The parameters are passed on to the init function of server manager """ self.user = User("") self.usermanager = UserManager() self.absolutePath = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) self.fileManager = FileManager(self.absolutePath) super().__init__()
def test_collect_user_credentials_called(self): ''' This function will test if we are correctly calling the collect_user_credentials method ''' userbase = UserManager() auther = Authenticator(userbase) auther.collect_user_credentials = MagicMock(return_value=False) auther.login() auther.collect_user_credentials.assert_called_once()
def __init__(self, sleep, bot_controller_factory, debug_mode): self.__stop = threading.Event() self.sleep = sleep self.debug_mode = debug_mode self.bot_logger = logging.getLogger('Bot_Sender') self.logger = logging.getLogger('Sending_Manager') self.user_manager = UserManager(bot_controller_factory, self.debug_mode) self.users = self.user_manager.users self.user_card_manager = {}
def __init__(self, bot_controller_factory, debug_mode): self.cycles = 0 #self.max_idle_time = max_idle_time self.debug_mode = debug_mode self.bot_controller_factory = bot_controller_factory self.logger = logging.getLogger('Message_Handler') self.bot_logger = logging.getLogger('Bot_Sender') self.bot = None self.user_manager = UserManager(self.bot_controller_factory, self.debug_mode) self.user_manager.reset_all_states() self.__stop = threading.Event()
def signIn(self): confirmUser = None userManager = UserManager(self.registeredUser, self.databaseFilename) username = input('Please enter the your username: '******'Please enter the your password: ') confirmUser = userManager.confirmUser(username, password) return confirmUser
def loadFutureTools(self, range_start, range_end_days = 42): functionName = 'loadFutureTools' # empty list returnedToolList = [] try: # calculationg range_end range_end = range_start + timedelta(days = range_end_days) userManager = UserManager(self.registeredUser, self.databaseFilename) # Connecting to the DB databaseConnection = DatabaseConnection.CreateDBConnection(self.databaseFilename) cursor = databaseConnection.cursor() cursor.execute("SELECT tool_id, duration FROM Bookings WHERE start_date BETWEEN ? AND ?", (range_start, range_end)) tool_rows = cursor.fetchall() for tool in tool_rows: # Read our values from the record tool_id = tool[0] cust_id = tool[1] tool_name = tool[2] tool_cat = tool[3] tool_desc = tool[4] price = tool[5] halfDayPrice = tool[6] # get ID user = userManager.LoadUserId(cust_id) # create tool singleTool = Tools(tool_id, user, tool_name, tool_cat, tool_desc, price, halfDayPrice) returnedToolList.append(singleTool) # Disconnecting from the DB DatabaseConnection.CloseDBConnection(databaseConnection) return returnedToolList except Error as e: print(__name__, ':', functionName, ':', e) raise
def test_create_new_user(self): ''' This function will test if we can correctly create a new user. ''' userbase = UserManager() username = "******" password = "******" salt = Authenticator.generate_salt() creator = UserCreation(userbase, username, password, salt) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(username) == True)
class Inventory(BaseDaemon.Inventory): import pyre.facilities import pyre.properties from UserManager import UserManager from SessionManager import SessionManager inventory = [ pyre.properties.str("db", default="users.db"), pyre.properties.int("port", default=50000), pyre.facilities.facility("userManager", default=UserManager()), pyre.facilities.facility("sessionManager", default=SessionManager()) ]
def test_create_duplicate_new_users(self): ''' This test case will ensure that only 1 unique user exists per username. ''' userbase = UserManager() usernames = ["chad", "chad"] passwords = ["password", "hockey"] salts = [Authenticator.generate_salt()] * 2 for xx in range(0, len(usernames)): creator = UserCreation(userbase, usernames[xx], passwords[xx], salts[xx]) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.get_total_users() == len(usernames) - 1)
def searchToolByCategory(self, search_criteria): functionName = 'searchToolByCategory' # empty list returnedToolList = [] try: userManager = UserManager(self.registeredUser, self.databaseFilename) # Connecting to the DB databaseConnection = DatabaseConnection.CreateDBConnection(self.databaseFilename) cursor = databaseConnection.cursor() cursor.execute("SELECT tool_id, cust_id, tool_name, tool_cat, price, tool_desc, half_price FROM Tools WHERE tool_cat = ?", (search_criteria)) tool_rows = cursor.fetchall() for tool in tool_rows: tool_id = tool[0] cust_id = tool[1] tool_name = tool[2] tool_cat = tool[3] price = tool[4] tool_desc = tool[5] half_price = tool[6] # get user user = userManager.LoadUserId(cust_id) # create tool single_tool = Tools(tool_id, user, tool_name, tool_cat, price, tool_desc, half_price) returnedToolList.append(single_tool) # Disconnecting from the DB DatabaseConnection.CloseDBConnection(databaseConnection) return returnedToolList except Error as e: print(__name__, ':', functionName, ':', e) raise
def test_login_to_new_user_while_logged_in(self): ''' This test will ensure that we can log into a new user while logged in as an old user. This should change the current session token. ''' # Create many users. userbase = UserManager() usernames = ["chad", "jay", "dylan", "ellen", "pat", "jon"] passwords = [ "password", "hockey", "cooking", "teaching", "painting", "swimming" ] salts = [Authenticator.generate_salt()] * 6 for xx in range(0, len(usernames)): creator = UserCreation(userbase, usernames[xx], passwords[xx], salts[xx]) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() # login to one user salt = userbase.get_user_salt(usernames[0]) auther = Authenticator(userbase, usernames[0], passwords[0], salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() # Ensure we've logged in correctly. assert (token is not None) assert (token != "") assert (userbase.get_user_from_token(token) == usernames[0]) # store token to test against. old_token = token # Login to a new user. salt = userbase.get_user_salt(usernames[1]) auther = Authenticator(userbase, usernames[1], passwords[1], salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() assert (token is not None) assert (token != "") assert (userbase.get_user_from_token(token) == usernames[1]) assert (token != old_token)
def test_create_many_users(self): ''' This test case will ensure that multiple users can be created in one session. ''' userbase = UserManager() usernames = ["chad", "jay", "dylan", "ellen", "pat", "jon"] passwords = [ "password", "hockey", "cooking", "teaching", "painting", "swimming" ] salts = [Authenticator.generate_salt()] * 6 for xx in range(0, len(usernames)): creator = UserCreation(userbase, usernames[xx], passwords[xx], salts[xx]) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() assert (userbase.is_existing_user(usernames[xx]) == True) assert (userbase.get_total_users() == len(usernames))
def test_bad_login_while_logged_in_as_user(self): ''' This test will ensure that if we attempt to log into another account with the wrong credentials, while logged in our user will be logged out. ''' # Create many users. userbase = UserManager() usernames = ["chad", "jay", "dylan", "ellen", "pat", "jon"] passwords = [ "password", "hockey", "cooking", "teaching", "painting", "swimming" ] salts = [Authenticator.generate_salt()] * 6 for xx in range(0, len(usernames)): creator = UserCreation(userbase, usernames[xx], passwords[xx], salts[xx]) creator.gather_user_creation_details = MagicMock(return_value=True) creator.create() # login to one user salt = userbase.get_user_salt(usernames[0]) auther = Authenticator(userbase, usernames[0], passwords[0], salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() # Ensure we've logged in correctly. assert (token is not None) assert (token != "") assert (userbase.get_user_from_token(token) == usernames[0]) # store token to test against. old_token = token # Fail to login to a new user. salt = userbase.get_user_salt(usernames[1]) auther = Authenticator(userbase, usernames[1], "bad", salt) auther.collect_user_credentials = MagicMock(return_value=True) token = auther.login() auther.collect_user_credentials.assert_called_once() assert (token is not None) assert (token == "") assert (userbase.get_user_from_token(token) == "")
def connect(self, serverUrl, login, password): """Connect to confluence server for example, connect('http://172.17.1.26', 'testAccount', 'testPassword'), or connect('172.17.1.26', 'testAccount', 'testPassword') @param serverUrl: confluence server url starting with 'http://<domain name, or ip address>', or ip address @param login: user login @param password: user password""" if self._impl: raise ValueError('Already connected to %(host)s as %(user)s' % { 'host': self._serverAddress, 'user': self._login }) if not serverUrl.startswith('http://'): serverUrl = 'http://' + serverUrl try: _confluence = ConfluenceImpl(serverUrl, login, password) userManager = UserManager(q.logger) spaceManager = SpaceManager(q.logger) _confluence.pm_setProxy(self) _confluence.pm_setUserManager(userManager) _confluence.pm_setSpaceManager(spaceManager) self._impl = _confluence #set the reference of the concrete implementation to the newly created object #keep server url and login for use by status messages self._serverAddress = serverUrl self._login = login except Exception, ex: q.logger.log(str(ex), 3) raise ValueError( 'Not able to connect to server %(serverUrl)s with user %(login)s, Reason %(errorMessage)s' % { 'serverUrl': serverUrl, 'login': login, 'errorMessage': Utils.extractDetails(ex) })
def __init__(self, parent, userid): QDialog.__init__(self, parent) # Dialog has a label a text field # a button to cancel and a button to confirm the input self.loginWindow = parent self.setWindowTitle("Podaj hasło") self.userid = userid self.layout = QVBoxLayout() self.label = QLabel() self.field = QLineEdit() self.field.setEchoMode(QLineEdit.Password) # Hide the letters self.label.setText("Hasło użytkownika {}".format(UserManager().users[userid]['name'])) self.layoutButtons = QHBoxLayout() self.buttonCancel = QPushButton() self.buttonCancel.setText("Anuluj") self.buttonCancel.setDefault(False) self.buttonCancel.released.connect(self.close) self.buttonAdd = QPushButton() self.buttonAdd.setText("Potwierdź") self.buttonAdd.setDefault(True) self.buttonAdd.released.connect(self.attempt) self.layoutButtons.addWidget(self.buttonCancel) self.layoutButtons.addWidget(self.buttonAdd) self.layout.addWidget(self.label) self.layout.addWidget(self.field) self.layout.addLayout(self.layoutButtons) self.setLayout(self.layout)
# Uses the requests library to get the HTML from Billboard Top100 on the specified date response = requests.get(BASE_URL + date) response.raise_for_status() # Uses Beautiful Soup to scrap song title from the HTML page and compile them as a list soup = BeautifulSoup(response.text, "html.parser") # song_title_tags = soup.find_all(name="span", class_="chart-element__information__song") song_title_tags = soup.find_all(name="h3", class_="a-font-primary-bold-s") songs = [tag.getText() for tag in song_title_tags] # Initialises the custom class SpotifyManager with the date (see description in the class itself) sm = SpotifyManager(date) # Gets the list of users from the subscribers Google Sheet um = UserManager() users = um.get_users() # Uses list comprehension to make a list of song URIs ("if" statement checks if the element in the list exists - # method get_song_uri car return None if there is no such song on Spotify) track_URIs = [sm.get_song_uri(song) for song in songs if sm.get_song_uri(song)] # Creates the playlist with songs from previous step playlist = sm.create_playlist(tracks=track_URIs) # Initialize Nmtification Manager with the current playlist nm = NotificationManager(playlist) # Send e-mails to all subscribed users for user in users: nm.send_email(user)