Exemple #1
0
 def __init__(self, client_id: str, client_secret: str):
     Authenticator.__init__(self, {
         'client_id': client_id,
         'client_secret': client_secret
     })
     Session.__init__(self)
     self.anime, self.manga = Anime(), Manga()
Exemple #2
0
    def __init__(self, main_window):
        QtCore.QThread.__init__(self)
        self.authenticator = Authenticator()
        self.main_window = main_window

        # Create a link between buttons and functions
        self.main_window.ui.add_user.clicked.connect(self.add_user)
        self.main_window.ui.remove_user.clicked.connect(self.remove_user)
Exemple #3
0
 def reset(self):
     self.data = b""
     self.topics = []
     self.will = {}
     self.clientID = ""
     self.username = ""
     self.config = Config()
     self.config.reload()
     self.auth = Authenticator(self.config)
Exemple #4
0
 def __init__(self, watchdog, sock):
     self.data = b""
     self.topics = []
     self.will = {}
     self.clientID = ""
     self.config = Config()
     self.config.reload()
     self.auth = Authenticator(self.config)
     self.watchdog = watchdog
     self.socket = sock
Exemple #5
0
 def setUp(self):
     url = 'http://localhost:8080/tmis-ws-medipad/tmis-medipad?wsdl'
     # do not cache wsdl documents
     self.client = Client(url, username='', password='', cache=None)
     # Authenticate
     authenticator = Authenticator()
     authData = authenticator.asUser(u'Педиатров', '698d51a19d8a121ce581499d7b701668', 19)
     # Add auth headers
     tmisAuthNS = ('ta', 'http://korus.ru/tmis/auth')
     authHeader = Element('tmisAuthToken', ns = tmisAuthNS).setText(authData.authToken.id)
     self.client.set_options(soapheaders=authHeader)
Exemple #6
0
    def setUp(self):
        medipadWsUrl = 'http://localhost:8080/tmis-ws-medipad/tmis-medipad?wsdl'
        self.medipadClient = Client(medipadWsUrl,
                                    username='',
                                    password='',
                                    cache=None)

        # Authenticate
        authenticator = Authenticator()
        authData = authenticator.asAdmin()

        # Add auth headers
        tmisAuthNS = ('ta', 'http://korus.ru/tmis/auth')
        authHeader = Element('tmisAuthToken',
                             ns=tmisAuthNS).setText(authData.authToken.id)
        self.medipadClient.set_options(soapheaders=authHeader)
Exemple #7
0
    def owner_main():

        mydb = myc.connect(host="", user="", passwd="", database="")
        mycur = mydb.cursor()
        print("Welcome to the owner module")
        user = input("Enter your username")
        passw = input("Enter your password")
        if a.auth_main(user, passw):
            print(
                "Welcome back Dear owner \nPress one to check the logs of your current turfs\nPress 2 to add a new "
                "turf on your account\nPress three to exit ")
            ch = int(input())
            if ch == 1:
                x = ds.data_main(user)
                print(x)
                print(
                    "press the Name of thr turf to which you want to fetch the data"
                )
                name = input().lower()
                result = ds.data_main(name)
                for i in result:
                    print(i)
            elif ch == 2:
                name = input(
                    "Enter the name with which you want to make the entry")
                dw.owner_writer(name, user)
            elif ch == 3:
                print("Thanks for using AM's Database Manager")
                exit(1)
        else:
            print("Authentication Failed")
    def get_patron(self):
        auth = Authenticator.initialize(self._db)
        username = self.conf[Configuration.AUTHENTICATION_TEST_USERNAME]
        password = self.conf[Configuration.AUTHENTICATION_TEST_PASSWORD]

        patron = auth.authenticated_patron(self._db, username, password)
        if not patron:
            raise ValueError("Could not authenticate test patron!")
        return patron
Exemple #9
0
class App:

    def __init__(self):
        self.br = mechanize.Browser()
        self.sc = Scraper(self.br)
        self.auth = Authenticator(self.br)

    def run(self):
        self.make_browser()
        self.auth.set_credentials()
        self.auth.log_in()
        self.sc.count_statuses()
        self.sc.print_results()

    def make_browser(self):
        cookie_jar = cj.CookieJar()
        self.br.set_cookiejar(cookie_jar)
        self.br.addheaders = [('User-agent', 'Firefox')]
        self.br.set_handle_robots(False)
Exemple #10
0
def main(db: str):
    global router

    dao = create_dao(db)

    authenticator = Authenticator(dao=dao, )

    try:
        dao.connect_to_database()
    except Exception as ex:
        # TODO: get rid of this or handle more specific exception
        # this is here just to make it easier to test dummy methods
        traceback.print_exc()

    context = ServerContext(
        authenticator=authenticator,
        dao=dao,
    )

    router = Router({
        "buildings":
        Router({
            "<building_name>":
            Router({
                "fountains": ListFountainsRoute(context),
            }),
        }),
        "campuses":
        Router({
            "":
            ListCampusesRoute(context),
            "<campus_name>":
            Router({
                "buildings": ListBuildingsRoute(context),
            })
        }),
        "fountains":
        Router({
            "<fountain_name>": Router({
                "ratings": RatingsRoute(context),
            }),
        }),
        "login":
        LoginRoute(context),
        "users":
        UsersRoute(context),
    })

    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("serving at port", PORT)

        try:
            httpd.serve_forever()
        finally:
            dao.disconnect_from_database()
Exemple #11
0
def main():
    num_subjects = 5
    train_runs = [6, 10]
    auth_runs = [14]
    num_tests = 5

    auth = Authenticator()
    subjects = list(range(1, num_subjects + 1))
    auth.train(subjects, train_runs)

    output = ''

    for subject in subjects:
        _, data, _ = auth.get_user_data(subject, auth_runs, dict(T0=subject, T1=subject, T2=subject))
        labels = auth.authenticate(subject, data)
        unique, counts = np.unique(labels, return_counts=True)
        label_counts = dict(zip(unique, counts))

        try:
            confidence = float(label_counts[subject]) / float(len(labels))
        except KeyError:
            confidence = 0.0

        output += '{}: {}\n'.format(subject, confidence)
        output += '{}\n\n'.format(str(label_counts))

    file_name = 'auth_test_{}.txt'.format(str(num_subjects))
    with open(file_name, 'w') as f:
        f.write(output)
Exemple #12
0
 def wrapper():
     decoded_token = jwt.decode(request.headers.get('api-token'),
                                self.__SECRET,
                                algorithm=self.__AlGO)
     ok = Authenticator().validate_token(decoded_token)
     if not ok:
         __msg = str({
             "status": "failed",
             "message": "UNAUTHORIZED USER"
         })
         __status = 401
         return __msg, __status
     return fn()
Exemple #13
0
 def manager_main():
     print("Welcome to the Manager module")
     user = input("Enter your username")
     passw = input("Enter your password")
     if a.auth_main(user, passw):
         print("Welcome back Manager")
         print("Enter The Turf under your Jurisdiction")
         name = input().lower()
         x = ds.data_main(name)
         for i in x:
             print(i)
     else:
         print("Authentication Failed")
Exemple #14
0
def main():

    TEST_NAME = "dot1x.dot1x"

    LOGGER = get_logger('test_dot1x')
    arg_length = len(sys.argv)
    if arg_length > 1:
        write_file = sys.argv[1]
    else:
        write_file = '/tmp/dot1x_result.txt'
    if arg_length > 2:
        config_file = sys.argv[2]
    else:
        config_file = '/config/device/module_config.json'

    # TODO: Link with authentucation module once ready.
    # Currently simply writes an empty result into the file.
    LOGGER.info('Initialising authenticator')
    authenticator = Authenticator(config_file)
    LOGGER.info('Running auth test')
    result_summary, test_result = authenticator.run_authentication_test()
    result_line = "RESULT %s %s %s" % (test_result, TEST_NAME, result_summary)
    with open(write_file, 'w') as w_file:
        w_file.write(result_line)
Exemple #15
0
class FlowTracer(metaclass=abc.ABCMeta):
    app_auth = Authenticator()
    controller = app_auth.working_creds['controller']['controller-ip']

    def __init__(self, user, password, host, db):
        self.flow_path = []
        self.links_traversed = []
        self.sql_auth = {
            "user": user,
            "password": password,
            "host": host,
            "db": db
        }

    @abc.abstractmethod
    def trace_flows(self, source, dest):
        pass
 def __init__(self,
              url,
              receiver_name,
              sender_name='pulp.task',
              asserting=False,
              auth=Authenticator(),
              **options):
     '''establishes a connection to given url; initializes session, sender and receiver'''
     self.url = url
     self.receiver_name = receiver_name
     self.sender_name = sender_name
     self._asserting = asserting
     self.last_sent = None
     self.last_fetched = None
     self.session = Connection.establish(self.url, **options).session()
     self.receiver = self.session.receiver(
         "pulp.agent.%s; {create: always}" % self.receiver_name)
     self.sender = self.session.sender(self.sender_name)
     self._timeout = None
     self.auth = auth
Exemple #17
0
 def cust_main():
     print("Welcome to the Customer module")
     user = input("Enter your username")
     passw = input("Enter your password")
     if a.auth_main(user, passw):
         print(
             "Welcome back Customer\nPress 1 to make a booking\nPress 2 to check an existing booking\nPress any "
             "other key to exit")
         n = int(input("Enter your choice now"))
         if n == 1:
             Booking.booking_main(user)
         elif n == 2:
             print(
                 "Enter the name of the turf with which you made the booking"
             )
             check = input("Here")
             Booking.checker(user, check)
         else:
             print("Thanks for Using AM's DBMS")
             exit(1)
     else:
         print("Authentication Failed")
Exemple #18
0
 def generate_token(self, user_key):
     org_id, user_id = Authenticator().validate_user_key(user_key)
     if not org_id or not user_id:
         __msg = str({"status": "failed", "message": "UNAUTHORIZED USER"})
         __status = 401
         return __msg, __status
     try:
         curr_time = datetime.utcnow()
         token_payload = {
             "user_key": user_key,
             "organization_id": org_id,
             "user_id": user_id,
             "iat": curr_time,
             "exp": curr_time + timedelta(days=self.__token_tol)
         }
         token = jwt.encode(token_payload,
                            self.__SECRET,
                            algorithm=self.__AlGO)
     except Exception as ex:
         __msg = str({"status": "failed", "message": "Method failure"})
         __status = 520
         return __msg, __status
     return str({"status": "success", "token": token}), 201
 def __init__(self, controller_ip):
     """"Initalizer for AbstractAgent"""
     self.auth = Authenticator()
     self.yaml_db_creds = self.auth.working_creds['database']
     self.sql_auth = {
         "user": self.yaml_db_creds['MYSQL_USER'],
         "password": self.yaml_db_creds['MYSQL_PASSWORD'],
         "host": self.yaml_db_creds['MYSQL_HOST']
     }
     self.db = self.auth.working_creds['database']['MYSQL_DB']
     self.odl_auth = self.auth.working_creds['controller']
     self.http_auth = HTTPBasicAuth(self.odl_auth['username'],
                                    self.odl_auth['password'])
     self.controller_ip = controller_ip
     self.headers = {
         'Accept': 'application/json',
         'content-type': 'application/json'
     }
     self.base_url = f"http://{self.controller_ip}:8181/restconf/operational/"
     # TODO: Change once DB implemented
     self.cnx = mysql.connector.connect(**self.sql_auth, db=self.db)
     self.cursor = self.cnx.cursor()
     self.sql_tool = SQLTools(**self.sql_auth, db=self.db)
Exemple #20
0
class GraphForm(Form):
    """
    Class to select the device and interface for graphs
    """

    auth = Authenticator()
    # Get SQL Auth & Creds
    yaml_db_creds = auth.working_creds['database']
    sql_creds = {"user": yaml_db_creds['MYSQL_USER'],
                 "password": yaml_db_creds['MYSQL_PASSWORD'],
                 "host": yaml_db_creds['MYSQL_HOST']
                 }
    db = auth.working_creds['database']['MYSQL_DB']
    topo_db = Topo_DB_Interactions(**sql_creds, db=db)
    while True:
        sleep(5)
        try:
            switches = topo_db.get_switches()
            break
        except:
            print('Waiting for DB to be ready!')
            sleep(5)
            continue
    
    switch_tuple = []
    for index, switch in enumerate(switches):
        tup = index+1, switch
        switch_tuple.append(tup)
    
    node = SelectField('Node', choices=switch_tuple)
    interface = SelectField('Interface', choices=[('-', '-')])
    
    time = SelectField('Graph Duration', choices=[(
             '1', '30 Minutes'), ('2', '1 Hour'),
            ('3', '2 Hours'), ('4', '6 Hours'),
            ('5', '1 Day'), ('6', 'All Time')])
 def __init__(self):
     auth = Authenticator().authenticate()
     self.drive = googleapiclient.discovery.build('drive', 'v3', credentials=auth)
class Client:
    rp_url = None,
    username = None,
    pin = None
    authenticator = None

    def __init__(self, rp_url: str, username: str, pin: str):
        self.rp_url = rp_url
        self.username = username
        self.pin = pin
        self.authenticator = Authenticator(rp_url).get_conn()

    def register(self):
        # Get server challenge
        url = self.rp_url + '/makeCredential/' + self.username
        resp = requests.get(url)
        registration_cookie = resp.cookies.get('webauthn-session')
        cred_creation_options = resp.json().get('publicKey')
        cred_creation_options['challenge'] = base64.urlsafe_b64decode(
            cred_creation_options['challenge'])
        cred_creation_options['user']['id'] = base64.urlsafe_b64decode(
            cred_creation_options['user']['id'])

        # Create credential on the authenticator
        print("\nTouch your authenticator device now...\n")

        attestation_object, client_data = self.authenticator.make_credential(
            cred_creation_options, pin=self.pin)

        # Register credential at the RP
        cred_id = str(
            base64.urlsafe_b64encode(
                attestation_object.auth_data.credential_data.credential_id),
            'ascii').rstrip('=')
        attestation_object_bin = cbor.encode(
            dict(
                (k.string_key, v) for k, v in attestation_object.data.items()))
        payload = {
            'id': cred_id,
            'rawId': cred_id,
            'response': {
                'attestationObject':
                str(base64.urlsafe_b64encode(attestation_object_bin),
                    'ascii').rstrip('='),
                'clientDataJSON':
                client_data.b64
            },
            'type': 'public-key'
        }
        register_credential_url = self.rp_url + '/makeCredential'
        resp = requests.post(register_credential_url,
                             json=payload,
                             cookies={'webauthn-session': registration_cookie})

        if not resp.ok:
            print('Registration error.')
            sys.exit(1)

        print("New credential created!")
        print("CLIENT DATA:", client_data)
        print("ATTESTATION OBJECT:", attestation_object)

    def authorize(self, tx, tx_attack):
        # Get options from RP
        get_assertion_options_url = self.rp_url + '/assertion/' + self.username
        resp = requests.get(get_assertion_options_url,
                            params={'txAuthExtension': tx})
        assertion_cookie = resp.cookies.get('webauthn-session')
        assertion_options = resp.json().get('publicKey')
        assertion_options['challenge'] = base64.b64decode(
            assertion_options['challenge'])

        if tx_attack:
            assertion_options['extensions']['txAuthSimple'] = tx_attack

        for k, v in enumerate(assertion_options['allowCredentials']):
            assertion_options['allowCredentials'][k][
                'id'] = base64.urlsafe_b64decode(v['id'])

        # Generate assertion
        print("\nTouch your authenticator device now...\n")

        assertions, client_data = self.authenticator.get_assertion(
            assertion_options, pin=self.pin)
        assertion = assertions[
            0]  # just take the first assertion - it's only a poc

        cred_id = str(base64.urlsafe_b64encode(assertion.credential['id']),
                      'ascii').rstrip('=')
        auth_data = assertion.data[assertion.KEY.AUTH_DATA]
        signature = assertion.data[assertion.KEY.SIGNATURE]
        payload = {
            'id': cred_id,
            'rawId': cred_id,
            'response': {
                'authenticatorData':
                str(base64.urlsafe_b64encode(auth_data), 'ascii').rstrip('='),
                'clientDataJSON':
                client_data.b64,
                'signature':
                str(base64.urlsafe_b64encode(signature), 'ascii').rstrip('='),
                'userHandle':
                ''
            },
            'type': 'public-key'
        }
        register_credential_url = self.rp_url + '/assertion'
        resp = requests.post(register_credential_url,
                             json=payload,
                             cookies={'webauthn-session': assertion_cookie})

        if not resp.ok:
            print('Authorization error.')
            sys.exit(1)

        print("Transaction authorized!")
        print("CLIENT DATA:", client_data)
        print("ASSERTION DATA:", assertion)
Exemple #23
0
class Editor:
    autenticador = Authenticator()
    miautorizador = Authorizor(autenticador)

    def __init__(self):
        self.username = None
        self.menu_map = {
            "1": self.login,
            "2": self.add_user,
            "3": self.add_permision,
            "4": self.is_permitted,
            "5": self.permit_user,
            "6": self.quit
        }

    def add_permision(self):
        perm_name = input("Permision: ")

        try:
            Editor.miautorizador.add_permission(perm_name)
        except PermissionError as exception:
            print(exception)

    def permit_user(self):
        perm_name = input("Permision: ")
        username = input("User name: ")

        try:
            Editor.miautorizador.permit_user(perm_name, username)
        except PermissionError as exception:
            print(exception)
        except InvalidUsername as exception:
            print(exception)

    def add_user(self):
        username = input("username: "******"password: "******"The password from user {} is too short".format(exception))

    def login(self):
        logged_in = False
        while not logged_in:
            username = input("username: "******"password: "******"Sorry, that username does not exist")
            except InvalidPassword:
                print("Sorry, incorrect password")
            else:
                self.username = username

    def is_permitted(self):
        is_perm = False
        while not is_perm:
            perm_name = input("Permission: ")
            try:
                is_perm = Editor.miautorizador.check_permission(
                    perm_name, self.username)
            except NotLoggedInError as e:
                if e.username == None:
                    print("There is no an user logged, you shoul login in")
                else:
                    print("{} is not logged in".format(e.username))
                return False
            except NotPermittedError as e:
                print("{} cannot {}".format(e.username, perm_name))
                return False
            else:
                print("{} can {}".format(self.username, perm_name))
                return True

    def quit(self):
        raise SystemExit()

    def menu(self):
        try:
            answer = ""
            while True:
                print("""
                    Please enter a command:
                    1. Login
                    2. Add user
                    3. Add permision
                    4. Check permision
                    5. Permit user
                    6. Quit
                    """)
                answer = input("enter a command: ").lower()
                try:
                    func = self.menu_map[answer]
                except KeyError:
                    print("{} is not a valid option".format(answer))
                else:
                    func()
        finally:
            print("Thank you for testing the auth module")
Exemple #24
0
 def __init__(self):
     self.br = mechanize.Browser()
     self.sc = Scraper(self.br)
     self.auth = Authenticator(self.br)
Exemple #25
0
def main():
    if not os.getenv('SAVE_DIR'):
        save_dir = '/var/local/eeg/'
    else:
        save_dir = os.getenv('SAVE_DIR')

    save_path = os.path.join(save_dir, 'auth.bin')

    if not os.getenv('SOCK_PATH'):
        sock_path = '/tmp/eeg.sock'
    else:
        sock_path = os.getenv('SOCK_PATH')

    # Restore or create the Authenticator object
    if os.path.exists(save_path):
        if not os.path.exists(save_dir):
            logging.debug('Creating {}'.format(save_dir))
            try:
                os.mkdir(save_dir)
            except OSError:
                logging.error('Creation of directory failed')
                sys.exit(1)
        # Restore from file
        logging.info('Saved authenticator found at {}'.format(save_path))
        auth = pickle.load(open(save_path, 'rb'))
    else:
        # If no saved file is found, create a new object and train the model
        logging.info('Saved authenticator not found, creating from scratch')
        auth = Authenticator()
        train_model(auth)

    # Run the cleanup function to save the Authenticator object on exit
    atexit.register(cleanup, auth, save_path)

    # Create the unix socket
    try:
        os.unlink(sock_path)
    except OSError:
        if os.path.exists(sock_path):
            logging.error('Error removing socket')
            sys.exit(1)

    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    logging.debug('Starting socket at {}'.format(sock_path))
    sock.bind(sock_path)

    sock.listen(1)

    while True:
        conn, addr = sock.accept()

        try:
            logging.info('Accepted connection from {}'.format(addr))

            message = ''
            while True:
                data = conn.recv(1024)

                if data:
                    message += data.decode('utf-8')

                    if authenticate(auth, int(message)):
                        conn.sendall(b'Authentication success')
                    else:
                        conn.sendall(b'Authentication failure')
                    break
                else:
                    break
        finally:
            print(message)
            conn.close()
Exemple #26
0
 def __init__(self):
     authenticator = Authenticator()
     auth = authenticator.authenticate()
     self.api = tweepy.API(auth)
Exemple #27
0
from authenticator import Authenticator
from authorizor import Authorizor

authenticator = Authenticator()
authorizor = Authorizor(authenticator)

authenticator.add_user("joe", "password")
authorizor.add_permission("paint")

authenticator.login("joe", "password")

authorizor.permit_user("paint", "joe")

print(authorizor.check_permission("paint", "joe"))
Exemple #28
0
"""Main module for the agent component of our app."""
import time
import threading

import mysql.connector
from mysql.connector import errorcode

from authenticator import Authenticator
from abstract_agent import AbstractAgent
from topology_agent import TopologyAgent
from link_agent import LinkAgent
from port_counter_agent import PortCounterAgent
from device_agent import DeviceAgent
from flow_agent import FlowAgent

auth = Authenticator()
yaml_db_creds = auth.working_creds['database']
sql_creds = {
    "user": yaml_db_creds['MYSQL_USER'],
    "password": yaml_db_creds['MYSQL_PASSWORD'],
    "host": yaml_db_creds['MYSQL_HOST']
}
db = auth.working_creds['database']['MYSQL_DB']
controller_ip = auth.working_creds['controller']['controller-ip']


# TODO: Move db functions into its own module
def create_db():
    """creates DB for our monitoring app"""
    try:
        cnx = mysql.connector.connect(**sql_creds, database=db)
Exemple #29
0
class Session:
    def __init__(self, watchdog, sock):
        self.data = b""
        self.topics = []
        self.will = {}
        self.clientID = ""
        self.config = Config()
        self.config.reload()
        self.auth = Authenticator(self.config)
        self.watchdog = watchdog
        self.socket = sock

    def reset(self):
        self.data = b""
        self.topics = []
        self.will = {}
        self.clientID = ""
        self.username = ""
        self.config = Config()
        self.config.reload()
        self.auth = Authenticator(self.config)

    def registerNewData(self, data: bytes):
        self.data = data

    def classifyData(self) -> MQTTPacket:
        ptype = self.data[0] // 16
        print(f"GOT ANOTHER PACKET  WITH PTYPE : {ptype}")
        print(self.data)
        if ptype == 1:
            print("Returning ConnectPacket")
            return ConnectPacket(self.data)
        elif ptype == 2:
            raise MQTTError("Connack Packets should not be parsed by server")
        elif ptype == 3:
            return PublishPacket(self.data)
        elif ptype == 4:
            return PubackPacket(self.data)
        elif ptype == 5:
            return PubrecPacket(self.data)
        elif ptype == 6:
            return PubrelPacket(self.data)
        elif ptype == 7:
            return PubcompPacket(self.data)
        elif ptype == 8:
            return SubscribePacket(self.data)
        elif ptype == 9:
            return SubackPacket(self.data)
        elif ptype == 10:
            return UnsubscribePacket(self.data)
        elif ptype == 11:
            return UnsubackPacket(self.data)
        elif ptype == 12:
            return PingReqPacket(self.data)
        elif ptype == 13:
            return PingResPacket(self.data)
        elif ptype == 14:
            return DisconnectPacket(self.data)
        elif ptype == 15:
            return AuthPacket(self.data)
            raise MQTTError("Not properly implemented yet")

    def handleConnection(self, packet: MQTTPacket) -> MQTTPacket:
        packet.parse()
        nextPacket = packet.data[packet.fixed['remainingLength'] + 3:]
        #citeste gresit pachetul
        print(nextPacket)
        while len(nextPacket):
            if isinstance(packet, ConnectPacket):
                print(packet.fixed)
                print(packet.variable)
                print(packet.payload)
                if packet.variable['cleanStart']:
                    self.reset()
                if packet.variable['willFlag']:
                    self.will = packet.payload['willProperties']
                if not self.config.config['AllowPublicAccess']:
                    if packet.variable['usernameFlag'] and packet.variable[
                            'passwordFlag']:
                        if self.auth.authenticate(packet.payload['username'],
                                                  packet.payload['password']):
                            self.clientID = packet.payload['clientID']
                            return ConnackPacket(
                                ConnackPacket.generatePacketData(
                                    False, 0x00, {'SessionExpiryInterval': 0}))
                        else:
                            return ConnackPacket(
                                ConnackPacket.generatePacketData(
                                    False, 0x04, {'SessionExpiryInterval': 0}))
                else:
                    if self.watchdog.isUsedClientID(packet.payload['clientID'],
                                                    self.socket):
                        return ConnackPacket(
                            ConnackPacket.generatePacketData(
                                False, 0x03, {'SessionExpiryInterval': 0}))
                return ConnackPacket(
                    ConnackPacket.generatePacketData(
                        False, 0x00, {'SessionExpiryInterval': 0}))

            elif isinstance(packet, PublishPacket):
                packet.parse()
                subscribers = self.watchdog.getSubscriberSockets(
                    packet.variable['topicName'], self.sock)
                self.watchdog.broadcastByTopic(packet,
                                               packet.variable['topicName'],
                                               self.sock)
                packet.parse()
                print(packet.fixed)
                print(packet.variable)
                print(packet.payload)

                if packet.fixed['QoS'] == 1:
                    if subscribers == []:
                        return PubackPacket(
                            PubackPacket.generatePacketData(
                                packet.variable['packetIdentifier'], 0x10, []))
                    else:
                        return PubackPacket(
                            PubackPacket.generatePacketData(
                                packet.variable['packetIdentifier'], 0x00, []))
                elif packet.fixed['QoS'] == 2:
                    if subscribers == []:
                        return PubrecPacket(
                            PubrecPacket.generatePacketData(
                                packet.variable['packet_id'], 0x10,
                                "No subscribers", {}))
                    else:
                        return PubrecPacket(
                            PubrecPacket.generatePacketData(
                                packet.variable['packet_id'], 0x00, "SUCCESS",
                                {}))
                else:
                    return packet
            elif isinstance(packet, PubrecPacket):
                return
            self.registerNewData(nextPacket)
            print("REGISTERED NEW DATA")
            packet = self.classifyData()
Exemple #30
0
def main(argv):
    device_name = None
    server_url = None
    gpio_number = None
    rgb = []
    key = None
    lock_id = None
    logfile = None
    mode = 'single_lock'

    def help(cmd):
        print cmd + '-i <input device> -u <server url> -g <gpio number> -k <secret key> -l <lock number> -o <logfile>'

    try:
        opts, args = getopt.getopt(argv, "hi:u:b:g:r:k:l:o:m:", [
            "input=", "url=", "gpio=", "rgb=", "key=", "lock=", "logfile=",
            "mode="
        ])
    except getopt.GetoptError:
        help(sys.argv[0])
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            help(sys.argv[0])
            sys.exit()
        elif opt in ("-i", "--input"):
            device_name = arg
        elif opt in ("-u", "--url"):
            server_url = arg
        elif opt in ("-g", "--gpio"):
            gpio_number = arg
        elif opt in ("-r", "--rgb"):
            rgb.extend(arg.split(','))
        elif opt in ("-k", "--key"):
            key = arg
        elif opt in ("-l", "--lock"):
            lock_id = arg
        elif opt in ("-o", "--logfile"):
            logfile = arg
        elif opt in ("-m", "--mode"):
            mode = arg

    if not server_url or not key:
        help(sys.argv[0])
        sys.exit(2)

    if mode != 'single_lock' and mode != 'open_all':
        print('unknown mode %s' % mode)
        sys.exit(2)

    # create lock
    if gpio_number:
        lock = Lock(lock_id, Gpio(gpio_number))
    else:
        lock = DummyLock(lock_id)

    # create logger
    if logfile:
        logger = create_file_logger(logfile, lock)
    else:
        logger = create_stdout_logger(lock)

    # create authenticator
    logger.info("server url: %s" % server_url)
    authenticator = Authenticator(server_url, key)

    # create reader
    if device_name:
        reader = Reader(device_name)
    else:
        reader = DummyReader()

    rgb_led = None
    if rgb:
        rgb_led = RgbLed(int(rgb[0]), int(rgb[1]), int(rgb[2]))

    # read loop
    for user_id in reader.read():
        if mode == 'single_lock':

            if authenticator.auth(lock, user_id):
                if rgb_led:
                    rgb_led.green(1)

                lock.open(pulse_time_s=1)
                logger.info("%s: valid" % user_id)

                if rgb_led:
                    rgb_led.green(0)
            else:

                if rgb_led:
                    rgb_led.red(1)

                logger.info("%s: invalid" % user_id)
                time.sleep(1)

                if rgb_led:
                    rgb_led.red(0)

        elif mode == 'open_all':

            state = authenticator.auth(lock, user_id)
            if state:
                logger.info("%s: valid" % user_id)

                if state == 'on':
                    logger.info("all on")
                    if rgb_led:
                        rgb_led.green(1)
                        rgb_led.red(0)
                elif state == 'off':
                    logger.info("all off")
                    if rgb_led:
                        rgb_led.green(0)
                        rgb_led.red(1)
                else:
                    logger.info("unknown state: %s" % state)
            else:
                logger.info("%s: invalid" % user_id)
Exemple #31
0
 def __init__(self):
     mytest = User('diego', 'mypassword')
     mytest.update(Authenticator())