def process_headers( self ): # If authentization is enabled if self.AUTH: # Check if client send authorization headder authorization_header = self.headers.get( 'Authorization', "" ) # Client did not send any Authorization header => Unauthorized if not authorization_header: # Send response 401 => Unauthorized self.send_error( 401 ) return False else: # Client sent the Authorization header => we have to validate try: # Authorization format "Basic (username:password).encode("base64")" auth_type, encoded_credentials = authorization_header.lstrip( "Authorization: " ).split(' ') credentials = encoded_credentials.decode( "base64" ) # format username:password username, password = credentials.split( ":" ) authenticator = Authenticator() if not authenticator.authenticate( username, password ): # Not valid credentials self.send_error( 401 ) return False # Valid credentials except ValueError: # Client did not send valid format of credentials self.send_error( 401 ) return False return True
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 test_authenticateByID(self): db = dbHandler() self.truncate(db) the_id = db.insert('1234', '4321') auth = Authenticator() self.assertEqual(auth.authenticateByID(the_id, '4321'), True) self.assertEqual(auth.authenticateByID(the_id, 'ok'), False) self.assertEqual(auth.authenticateByID(100, '1234'), False)
def run(args): """ Usage: python Runner.py <path-to-credentials.json> """ reader = CredReader(args[0]) auth = Authenticator(args[0], reader.get_api_key(), reader.get_api_secret_key()) connection = auth.get_connection() print connection.get_balances()
def test_authenticateByName(self): db = dbHandler() self.truncate(db) db.insert('1234', '4321') auth = Authenticator() self.assertEqual(auth.authenticateByName('1234', '4321'), True) self.assertEqual(auth.authenticateByName('1234', '1234'), False) self.assertEqual(auth.authenticateByName('no_such_name', '4321'), False)
def __init__(self): #Tkinter self.root = Tk() self.audioPlayer = AudioPlayer() self.initWindow() self.queue = queue.Queue() self.authenticator = Authenticator() self.startAuthentication() self.root.mainloop()
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 login_existing_user(active_token, userbase: UserManager) -> str: ''' In this function, we log the user in based on collected username and password. On success we recieve an active token, on failure we recieve no token. Prompts to user will be printed from class on failure. ''' if userbase.is_active_token(): userbase.logout_user(active_token) auther = Authenticator(userbase) return auther.login()
def gather_user_creation_details(self) -> bool: ''' This function will run through the process of generating user credentials. It will also do some basic checking of valid entries. ''' # Username input and validation checking desired_username = input("Desired Username:"******"Username already exists, please try again.") return False self.__username = desired_username # Password input and validation checking. desired_pass = getpass("Desired Password:"******"Please re-enter your desired password:"******"Passwords do not match, try again.") return False self.__password = desired_pass # Wait until after validation to create salt. self.__salt = Authenticator.generate_salt() return True
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 clientconnector(): """\ clientconnector() -> returns Graphline clientconnector is the peer to KPIClient Keyword arguments: None """ return Graphline(authenticator=Authenticator(KPIDBI.getDB("mytree")), notifier=publishTo("KeyManagement"), linkages={ ("", "inbox"): ("authenticator", "inbox"), ("authenticator", "outbox"): ("", "outbox"), ("authenticator", "notifyuser"): ("notifier", "inbox"), })
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 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)
def create(self): ''' This function handles the creation of a new user, it drives the process by gathering wanted user credentials, then using existing methods in UserManager class to store a new user. ''' if self.gather_user_creation_details(): self.__password = Authenticator.generate_hash( self.__password, self.__salt) if (self.__userbase.store_new_user(self.__username, self.__salt, self.__password)): return True else: return False
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 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))
class RESTClient(object): _instance = None def __init__(self): self.authenticator = Authenticator() RESTClient._instance = self @staticmethod def getInstance(): if not RESTClient._instance: RESTClient() return RESTClient._instance def create_cluster(self, name, node_list=[]): data = {"cluster_name": name} response = self._get_response("/HASS/api/cluster", "POST", data) if response["code"] == MESSAGE_OK: if node_list != []: cluster_id = response["data"]["clusterId"] return self.add_node(cluster_id, node_list) else: return response def delete_cluster(self, cluster_id): return self._get_response("/HASS/api/cluster?cluster_id=%s" % cluster_id, "DELETE") def list_cluster(self): return self._get_response("/HASS/api/clusters", "GET") def add_node(self, cluster_id, node_list): data = {"cluster_id": cluster_id,"node_list": node_list} return self._get_response("/HASS/api/node", "POST", data) def delete_node(self, cluster_id, node_name): return self._get_response("/HASS/api/node?cluster_id=%s&&node_name=%s" %(cluster_id, node_name), "DELETE") def list_node(self, cluster_id): return self._get_response("/HASS/api/nodes/%s" % cluster_id, "GET") def add_instance(self, cluster_id, instance_id): data = {"cluster_id": cluster_id, "instance_id": instance_id} return self._get_response("/HASS/api/instance", "POST", data) def delete_instance(self, cluster_id, instance_id): return self._get_response("/HASS/api/instance?cluster_id=%s&&instance_id=%s" % (cluster_id, instance_id), "DELETE") def list_instance(self, cluster_id): return self._get_response("/HASS/api/instances/%s" % cluster_id, "GET") def recover(self, fail_type, cluster_id, node_name): data = {"fail_type": fail_type, "cluster_id": cluster_id, "node_name": node_name} return self._get_response("/HASS/api/recover", "POST", data) def updateDB(self): return self._get_response("/HASS/api/updateDB", "GET") def update_all_cluster(self): return self._get_response("/HASS/api/updateClusters", "GET") def _get_response(self, endpoint, method, data=None): conn = httplib.HTTPConnection(REST_host, REST_port, timeout=500) headers = {'Content-Type' : 'application/json', 'X-Auth-Token' : self.authenticator.get_access_token()} data = json.dumps(data) conn.request(method, endpoint, body=data, headers=headers) response = json.loads(conn.getresponse().read()) return response
class App: def __init__(self): #Tkinter self.root = Tk() self.audioPlayer = AudioPlayer() self.initWindow() self.queue = queue.Queue() self.authenticator = Authenticator() self.startAuthentication() self.root.mainloop() def onEvent(self): try: event = self.queue.get(0) self.processEvent(event) except queue.Empty: pass finally: self.root.after(100, self.onEvent) def processEvent(self, eventList): eventString = eventList[0] print(eventList) if eventString == "AutenticacionTerminada": personAuthenticated = eventList[1] if personAuthenticated == "Unknown": self.audioPlayer.playFaceNotKnownAuthentication() self.labelMessage.set( "Rostro desconocido.\nDebe enrolarse previamente") self.root.after(10000, self.restart) else: self.audioPlayer.playReadDNIAuthenticate() self.labelMessage.set( "Bienvenido\n{} {}\n\nColoque su DNI por favor".format( personAuthenticated.name, personAuthenticated.surname)) self.readDNI() elif eventString == "LecturaDNIEsperaAgotada": self.labelMessage.set("Tiempo de espera agotado") self.audioPlayer.playReadDNIWaitTimeExausted() self.root.after(10000, self.restart) elif eventString == "LecturaDNITerminada": faceMatchesDNI = eventList[1] if faceMatchesDNI: self.audioPlayer.playAuthenticationSucess() self.labelMessage.set("Autenticación exitosa!") self.root.after(10000, self.restart) else: self.audioPlayer.playDNIAuthenticateNotRegistered() self.labelMessage.set( "El DNI colocado no corresponde con el registrado") self.root.after(10000, self.restart) elif eventString == "DeteccionTiempoAgotado": self.labelMessage.set("No se ha detectado un rostro") self.audioPlayer.playFaceNotDetectedTimeExausted() self.root.after(10000, self.restart) elif eventString == "LecturaDNIQrInvalido": self.labelMessage.set("El código QR es inválido") self.audioPlayer.playDNIQrInvalid() self.root.after(10000, self.restart) def authenticateFace(self): AuthenticateFaceThread(self.authenticator, self.queue).start() def readDNI(self): ReadDniThread(self.authenticator, self.queue).start() def restart(self): from py_session import py_session py_session() self.labelMessage.set( "Por favor posicionate mirando\nde frente a la cámara") self.audioPlayer.playPositionFace() self.authenticator.init() self.startAuthentication() def startAuthentication(self): self.root.after(5000, self.authenticateFace) self.onEvent() def initWindow(self): self.root.title("AUTENTICACIÓN") self.root.configure(background='#C8919C') self.root.attributes("-fullscreen", True) self.labelMessage = StringVar() self.labelMessage.set( "Por favor posicionate mirando\nde frente a la cámara") self.audioPlayer.playPositionFace() label = Label(self.root, textvariable=self.labelMessage, font=("Arial", 50, "bold"), justify=CENTER, anchor=W) label.configure(background='#C8919C') label.pack()
class RESTClient(object): _instance = None def __init__(self): self.authenticator = Authenticator() RESTClient._instance = self @staticmethod def get_instance(): if not RESTClient._instance: RESTClient() return RESTClient._instance def create_cluster(self, name, node_list=[], layers_string="111"): data = { "cluster_name": name, "node_list": node_list, "layers_string": layers_string } return self._get_HASS_response("/HASS/api/cluster", "POST", data) def delete_cluster(self, cluster_name): data = {"cluster_name": cluster_name} return self._get_HASS_response("/HASS/api/cluster", "DELETE", data) def list_cluster(self): return self._get_HASS_response("/HASS/api/clusters", "GET") def add_node(self, cluster_name, node_list): data = {"cluster_name": cluster_name, "node_list": node_list} return self._get_HASS_response("/HASS/api/node", "POST", data) def delete_node(self, cluster_name, node_name): data = {"cluster_name": cluster_name, "node_name": node_name} return self._get_HASS_response("/HASS/api/node", "DELETE", data) def list_node(self, cluster_name): return self._get_HASS_response("/HASS/api/nodes/%s" % cluster_name, "GET") def add_instance(self, cluster_name, instance_id): data = {"cluster_name": cluster_name, "instance_id": instance_id} return self._get_HASS_response("/HASS/api/instance", "POST", data) def update_instance_host(self, cluster_name, instance_id): data = {"cluster_name": cluster_name, "instance_id": instance_id} return self._get_HASS_response("/HASS/api/instance", "PUT", data) def delete_instance(self, cluster_name, instance_id): return self._get_HASS_response( "/HASS/api/instance?cluster_name=%s&&instance_id=%s" % (cluster_name, instance_id), "DELETE") def list_instance(self, cluster_name): return self._get_HASS_response("/HASS/api/instances/%s" % cluster_name, "GET") def recover(self, fail_type, cluster_name, node_name): data = { "fail_type": fail_type, "cluster_name": cluster_name, "node_name": node_name } return self._get_HASS_response("/HASS/api/recover", "POST", data) def update_db(self): return self._get_HASS_response("/HASS/api/updateDB", "GET") def _get_HASS_response(self, endpoint, method, data=None): try: headers = { 'Content-Type': 'application/json', 'X-Auth-Token': self.authenticator.get_access_token() } return self._get_response(REST_host, REST_port, endpoint, method, headers, data) except Exception as e: print str(e) logging.error(str(e)) return False def _get_response(self, host, port, endpoint, method, headers, data=None): conn = httplib.HTTPConnection(host, port, timeout=500) headers = headers request_data = json.dumps(data) conn.request(method, endpoint, body=request_data, headers=headers) response = json.loads(conn.getresponse().read()) conn.close() return response
def setUp(self): self.testing_salt = Authenticator.generate_salt()
from Authenticator import Authenticator from Searcher import Searcher auth = Authenticator() api = Authenticator.getapi(auth) Searcher(api)
def __init__(self): self.substituteFetcher = SubstituteFetcher() self.authenticator = Authenticator()
from Authenticator import Authenticator from Authorizor import Authorizor import Exceptions authenticator = Authenticator() authorizor = Authorizor(authenticator)
def __init__(self, auth_server): Authenticator.__init__(self, auth_server) # test if we've got the "Use above" option self.queryer = LDAPDirectoryQueryer(auth_server)
def __init__(self, input_HASS): threading.Thread.__init__(self) global HASS global authenticator HASS = input_HASS authenticator = Authenticator()
def __init__(self): self.authenticator = Authenticator() self.chatSystem = ChatSystem() self.responseFactory = ResponseFactory()
class Controller: def __init__(self): self.authenticator = Authenticator() self.chatSystem = ChatSystem() self.responseFactory = ResponseFactory() #These functions deal with routing the requests to the proper ChatSystem functions, #They assume that all parameters are not None, unless otherwise specified and the #parameters are of the proper type #The functions return a string corresponding to the proper response type #The functions authenticate the users if necessary def login(self, username, password): try: self.__authenticateByName(username, password) userID = self.chatSystem.login(username, password) if userID is None: return self.responseFactory.invalidCredentials() return self.responseFactory.loggedIn(userID) except Exception as e: return self.handleException(e) def signup(self, username, password): try: userID = self.chatSystem.signup(username, password) return self.responseFactory.loggedIn(userID) except Exception as e: return self.handleException(e) def send(self, userID, password, chatroom, text): try: self.__authenticateByID(userID, password) self.chatSystem.addMessage(chatroom, userID, text) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def get(self, userID, password, chatroom, lastUpdate): try: self.__authenticateByID(userID, password) if lastUpdate is None: response = self.chatSystem.getMessagesByTime(chatroom, userID) else: response = self.chatSystem.getMessagesByIndex(chatroom,userID,lastUpdate) return self.responseFactory.returnMessages(response[0], response[1]) except Exception as e: return self.handleException(e) def set_alias(self, userID, password, newUsername): try: self.__authenticateByID(userID, password) self.chatSystem.set_alias(userID, newUsername, password) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def join(self, userID, password, chatroom): try: self.__authenticateByID(userID, password) self.chatSystem.joinChatroom(chatroom, userID) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def create(self, userID, password, chatroom): try: self.__authenticateByID(userID, password) self.chatSystem.addChatroom(userID,chatroom) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def delete(self, userID, password, chatroom): try: self.__authenticateByID(userID, password) self.chatSystem.deleteChatroom(userID, chatroom) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def block(self, userID, password, chatroom, userToBlock): try: self.__authenticateByID(userID, password) self.chatSystem.banUser(userID, chatroom, userToBlock) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def unblock(self, userID, password, chatroom, userToUnblock): try: self.__authenticateByID(userID, password) self.chatSystem.unbanUser(userID, chatroom, userToUnblock) return self.responseFactory.ok() except Exception as e: return self.handleException(e) def __authenticateByID(self,userID, password): if not self.authenticator.authenticateByID(userID, password): raise InvalidCredentialsException def __authenticateByName(self, username, password): if not self.authenticator.authenticateByName(username, password): raise InvalidCredentialsException def handleException(self, e): if isinstance(e,InvalidCredentialsException): return self.responseFactory.invalidCredentials() if isinstance(e,ChatroomDoesNotExistException): return self.responseFactory.chatroomDoesNotExist() elif isinstance(e,DuplicateChatroomException): return self.responseFactory.duplicateChatrooom() elif isinstance(e,DuplicateUsernameException): return self.responseFactory.duplicateUsername() elif isinstance(e,ChatroomFormatException): return self.responseFactory.invalidChatroom() elif isinstance(e,MessageFormatException): return self.responseFactory.invalidMessage() elif isinstance(e,UsernameFormatException): return self.responseFactory.invalidUsername() elif isinstance(e,PasswordFormatException): return self.responseFactory.invalidPassword() elif isinstance(e,UserNotFoundException): return self.responseFactory.userDoesNotExist() elif isinstance(e,NotOwnerException): return self.responseFactory.notOwner() elif isinstance(e,UserBannedException): return self.responseFactory.blocked() elif isinstance(e,UserNotBannedException): return self.responseFactory.userNotOnList() elif isinstance(e,UserIsOwnerException): return self.responseFactory.userIsOwner() else: return self.responseFactory.serverError()
def __init__(self): self.authenticator = Authenticator() RESTClient._instance = self