Exemplo n.º 1
0
    def readRFIDTag(self):
        while(self.lock == True):
            print "still locked (readRFIDTag)"
            time.sleep(0.15)

        self.lock = True

        (status,TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)

        # If a card is found
        #if status == RFIDReader.MI_OK:
        #    print "rfid tag detected"

        # Get the UID of the card
        (status,uid) = RFIDReader.MFRC522_Anticoll()

        # If we have the UID, continue
        if status == RFIDReader.MI_OK:

            # Print UID
            #print "Card read UID: "+str(uid[0])+"."+str(uid[1])+"."+str(uid[2])+"."+str(uid[3])

            self.tagInfo.tagId = str(uid[0])+"."+str(uid[1])+"."+str(uid[2])+"."+str(uid[3])
            self.tagInfo.userInfo = ""

            # This is the default key for authentication
            key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

            # Select the scanned tag
            RFIDReader.MFRC522_SelectTag(uid)

            # Authenticate
            status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A, 8, key, uid)

            # Check if authenticated
            if status == RFIDReader.MI_OK:
                user = User.query.filter_by(cardID=self.tagInfo.tagId).first()
                if user is None:
                    print "No user asigned to card"
                else:
                    self.tagInfo.userInfo = user.email
                    if user.checkUserAccessPrivleges() == "access granted":
                        self.requestOpening = True
                    print user.email

                RFIDReader.MFRC522_StopCrypto1()
                self.lock = False
                return True
            else:
                print "Authentication error"
                self.lock = False
                return False

        self.lock = False
        return False
Exemplo n.º 2
0
 def __init__(self):
     super(TestApp, self).__init__()
     self.rfidReader = RFIDReader(handler_function=self.handler)
     self.firebase = Firebase(config)
     self.cleanInfoEvent = None
     self.screen_manager = ScreenManager(transition=NoTransition())
     self.home_screen = HomeScreen(name='home')
     self.viewer_screen = ViewerScreen(name='viewer',
                                       firebase=self.firebase)
     self.screen_manager.add_widget(self.home_screen)
     self.screen_manager.add_widget(self.viewer_screen)
Exemplo n.º 3
0
    def assignRFIDTag(self, user):
        while(self.lock == True):
            print "still locked (assignRFIDTag)"
            time.sleep(0.15)

        self.lock = True

        print "background-worker assign"

        (status,TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)

        (status,uid) = RFIDReader.MFRC522_Anticoll()

        # If we have the UID, continue
        if status == RFIDReader.MI_OK:

            # Print UID
            uid_str = str(uid[0])+"." +str(uid[1])+"."+str(uid[2])+"."+str(uid[3])
            print "Card read UID: " + uid_str

            if(uid_str != user.cardID)
                print "Wrong cardID detected while assigning RFID-tag to user"
                return False

            # This is the default key for authentication
            key = []
            secret = []

            # extract keyA from database and print it
            formated_key_list = user.cardAuthKeyA.split()
            for x in formated_key_list:
                key.append(int(x, 16))
            print key

            # extract secret from database and print it
            formated_secret_list = user.cardSecret.split()
            for x in formated_secret_list:
                secret.append(int(x, 16))
            print secret

            # Select the scanned tag
            RFIDReader.MFRC522_SelectTag(uid)

            # Authenticate for auth-sector
            status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A, user.cardAuthSector * 4 + user, key, uid)

            # Check if authenticated
            if status == RFIDReader.MI_OK:
                # read trailer from auth-sector
                RFIDReader.MFRC522_Read(user.cardAuthSector * 4 + 3)
                # read auth block in auth-sector
                RFIDReader.MFRC522_Read(user.cardAuthSector * 4 + user.cardAuthBlock)
                # write secret to auth block in auth-sector
                RFIDReader.MFRC522_Write(user.cardAuthSector * 4 + user.cardAuthBlock, secret)
                # read back secret from  auth block in auth-sector
                RFIDReader.MFRC522_Read(user.cardAuthSector * 4 + user.cardAuthBlock)
                RFIDReader.MFRC522_StopCrypto1()
                # unlock and return succesfully
                self.lock = False
                return True
            else:
                print "Authentication error"
                self.lock = False
                return False

        self.lock = False
        return False
Exemplo n.º 4
0
    def withdrawRFIDTag(self, user):
        while (self.lock == True):
            if config.DEBUG == False:
                print "still locked (withdrawRFIDTag)"
            time.sleep(0.3)

        try:
            self.lock = True

            time.sleep(0.2)

            print "background-worker withdrawRFIDTag"

            for i in range(0, 4):
                (status,
                 TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)
                (status, uid) = RFIDReader.MFRC522_Anticoll()
                if status == RFIDReader.MI_OK:
                    break
                else:
                    print "retry anticoll card (withdrawRFIDTag)"
                    time.sleep(0.3)

            # If we have the UID, continue
            if status == RFIDReader.MI_OK:
                # Print UID
                uid_str = str(uid[0]) + "." + str(uid[1]) + "." + str(
                    uid[2]) + "." + str(uid[3])
                print "Card read UID: " + uid_str

                if (uid_str != user.cardID):
                    print "Wrong cardID detected while withdrawing RFID-tag to user"
                    self.lock = False
                    return False

                # This is the default key for authentication
                defaultkey = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                defaultsecret = [
                    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
                    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                ]

                userkey = []
                usersecret = []

                userkeyString = user.cardAuthKeyA
                for x in userkeyString.split('-'):
                    userkey.append(int(x, 16))

                print "Userkey: " + str(userkey)

                usersecretString = user.cardSecret
                for x in usersecretString.split('-'):
                    usersecret.append(int(x, 16))

                print "Usersecret: " + str(usersecret)

                SecretBlockAddr = user.cardAuthSector * 4 + user.cardAuthBlock
                TrailerBlockAddr = user.cardAuthSector * 4 + 3

                # Select the scanned tag
                RFIDReader.MFRC522_SelectTag(uid)

                # Authenticate for secret-block
                status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A,
                                                 SecretBlockAddr, userkey, uid)

                # write user secret
                if status == RFIDReader.MI_OK:
                    RFIDReader.MFRC522_Write(SecretBlockAddr, defaultsecret)
                else:
                    print "Authentication error while write rfid-tag secret sector"
                    self.lock = False
                    return False

                status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A,
                                                 TrailerBlockAddr, userkey,
                                                 uid)

                # Check if authenticated
                if status == RFIDReader.MI_OK:
                    print "Read TrailerBlock :"
                    # Read block 8
                    result = RFIDReader.MFRC522_Read(TrailerBlockAddr)
                    print result

                    for x in range(0, 6):
                        result[x] = 0xFF
                    print result

                    print "Write new trailer:"
                    # Write the data
                    RFIDReader.MFRC522_Write(TrailerBlockAddr, result)
                    print "\n"

                    RFIDReader.MFRC522_StopCrypto1()
                    # unlock and return succesfully
                    self.lock = False
                    return True
                else:
                    print "Authentication error while write rfid-tag key sector"
                    self.lock = False
                    return False
            else:
                print "Authentication error while looking for cards"
                self.lock = False
                return False
        except:
            self.lock = False
            print "unexpected error withdrawRFIDTag"
            raise
Exemplo n.º 5
0
    def checkRFIDTag(self):

        #if self.first == True:
        #    self.first = False
        #    raise ValueError('A very specific bad thing happened')

        while (self.lock == True):
            print "still locked (checkRFIDTag)"
            time.sleep(0.2)

        try:
            self.lock = True

            (status,
             TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)

            for i in range(0, 2):
                (status, uid) = RFIDReader.MFRC522_Anticoll()
                if status == RFIDReader.MI_OK:
                    break
                else:
                    time.sleep(0.2)

            self.resetTagInfo()

            # If we have the UID, continue
            if status == RFIDReader.MI_OK:

                # Print UID
                self.tagInfo.tagId = str(uid[0]) + "." + str(
                    uid[1]) + "." + str(uid[2]) + "." + str(uid[3])
                self.tagInfo.userInfo = ""

                user = User.query.filter_by(cardID=self.tagInfo.tagId).first()

                if user is None:
                    self.ledState = self.LED_STATE_ACCESS_DENIED
                    self.lock = False
                    return

                self.tagInfo.userInfo = user.email
                # print user.email

                # This is the default key for authentication
                defaultkey = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                userkey = []
                usersecret = []

                userkeyString = user.cardAuthKeyA
                for x in userkeyString.split('-'):
                    userkey.append(int(x, 16))

                # print "Userkey: " + str(userkey)

                usersecretString = user.cardSecret
                for x in usersecretString.split('-'):
                    usersecret.append(int(x, 16))

                # print "Usersecret: " + str(usersecret)

                SecretBlockAddr = user.cardAuthSector * 4 + user.cardAuthBlock
                TrailerBlockAddr = user.cardAuthSector * 4 + 3

                # Select the scanned tag
                RFIDReader.MFRC522_SelectTag(uid)

                # Authenticate
                status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A,
                                                 SecretBlockAddr, userkey, uid)

                # Check if authenticated
                if status == RFIDReader.MI_OK:

                    readSecret = RFIDReader.MFRC522_Read(SecretBlockAddr)
                    # print readSecret
                    readSecretString = ''
                    i = 0

                    if not readSecret:
                        print "Read secret string is empty."
                        self.lock = False
                        RFIDReader.MFRC522_StopCrypto1()
                        return False

                    for x in readSecret:
                        if i != 0:
                            readSecretString = readSecretString + '-'
                        i = i + 1
                        readSecretString = readSecretString + format(x, '02X')

                    # print readSecretString

                    if readSecretString == user.cardSecret:
                        print "correct secret"
                        if security.checkUserAccessPrivleges(
                                datetime.datetime.now(),
                                user) == "Access granted.":
                            if datetime.datetime.now(
                            ) > user.lastAccessDateTime + datetime.timedelta(
                                    minutes=config.NODE_LOG_MERGE):
                                user.lastAccessDateTime = datetime.datetime.now(
                                )

                                logentry = Action(
                                    datetime.datetime.utcnow(),
                                    config.NODE_NAME,
                                    user.firstName + ' ' + user.lastName,
                                    user.email, 'Opening request (' + str(1) +
                                    ' attempts)', 'Opening request', 'L2', 1,
                                    'Card based',
                                    Action.ACTION_OPENING_REQUEST, 1)
                                print "Log-entry created"
                                try:
                                    db.session.add(logentry)
                                    db.session.commit()
                                except:
                                    self.ledState = self.LED_STATE_ACCESS_DENIED
                                    db.session.rollback()
                                    raise

                            else:
                                lastlogEntry = Action.query.filter_by(
                                    logType='Opening request',
                                    userMail=user.email).order_by(
                                        Action.date.desc()).first()
                                if lastlogEntry is not None:
                                    if lastlogEntry.synced is 0:
                                        lastlogEntry.date = datetime.datetime.utcnow(
                                        )
                                        lastlogEntry.actionParameter += 1
                                        lastlogEntry.logText = 'Opening request (' + str(
                                            lastlogEntry.actionParameter
                                        ) + ' attempts)'
                                    else:
                                        lastlogEntry.synced = 0
                                        lastlogEntry.date = datetime.datetime.utcnow(
                                        )
                                        lastlogEntry.actionParameter = 1
                                        lastlogEntry.logText = 'Opening request (' + str(
                                            lastlogEntry.actionParameter
                                        ) + ' attempts)'
                                print "Log-entry is in merge-range ts = " + str(
                                    datetime.datetime.now(
                                    )) + " last = " + str(
                                        user.lastAccessDateTime
                                    ) + " merge = " + str(
                                        config.NODE_LOG_MERGE) + " minutes"
                                try:
                                    db.session.commit()
                                except:
                                    self.ledState = self.LED_STATE_ACCESS_DENIED
                                    db.session.rollback()
                                    raise

                            self.requestOpening = True
                            self.ledState = self.LED_STATE_ACCESS_GRANTED
                        else:
                            self.ledState = self.LED_STATE_ACCESS_DENIED
                            print "no user-access privilege"
                    else:
                        self.tagInfo.userInfo = user.email + '(inv. sec.)'
                        print "no user-access privilege"
                        self.ledState = self.LED_STATE_ACCESS_DENIED

                    RFIDReader.MFRC522_StopCrypto1()
                    self.lock = False
                    return True
                else:
                    self.tagInfo.userInfo = user.email + '(inv. key.)'
                    print "Authentication error"
                    self.ledState = self.LED_STATE_ACCESS_DENIED
                    self.lock = False
                    return False
            else:
                self.lock = False
                return False
        except:
            self.lock = False
            print "unexpected error in checkRFIDTag"
            self.ledState = self.LED_STATE_ACCESS_DENIED
            raise
Exemplo n.º 6
0
class TestApp(App):
    def __init__(self):
        super(TestApp, self).__init__()
        self.rfidReader = RFIDReader(handler_function=self.handler)
        self.firebase = Firebase(config)
        self.cleanInfoEvent = None
        self.screen_manager = ScreenManager(transition=NoTransition())
        self.home_screen = HomeScreen(name='home')
        self.viewer_screen = ViewerScreen(name='viewer',
                                          firebase=self.firebase)
        self.screen_manager.add_widget(self.home_screen)
        self.screen_manager.add_widget(self.viewer_screen)

    def build(self):
        self.rfidReader.start()
        return self.screen_manager

    def stop(self):
        self.rfidReader.stop()

    def __del__(self):
        self.rfidReader.stop()

    def getUserData(self, rfid):
        try:
            user_data = self.firebase.get("users/" + rfid).val()
            return user_data
        except Exception:
            raise Exception(
                "Nessuna connessione ad internet. Contatta la segreteria!")

    def downloadUserFile(self, rfid, destination_path, filename_path):
        try:
            system("mkdir -p %s" % destination_path)
            system("rm -f %s/*" % destination_path)
            node = self.firebase.getNode("users/" + rfid + "/scheda.zip")
            node.download(filename_path)
        except Exception as e:
            raise Exception("Impossibile scaricare file dal server. " + str(e))

    def extractUserFile(self, rfid, destination_path, filename_path):
        try:
            with zipfile.ZipFile(filename_path, "r") as zip_ref:
                for zip_info in zip_ref.infolist():
                    if zip_info.filename[-1] == '/':
                        continue
                    zip_info.filename = path.basename(zip_info.filename)
                    zip_ref.extract(zip_info, destination_path)
        except Exception:
            raise Exception(
                "Impossibile estrarre scheda dall'archivio. Contatta la segreteria!"
            )

    def createQRCode(self, rfid, destination_path):
        try:
            qr = pyqrcode.create(
                'https://firebasestorage.googleapis.com/v0/b/master-fitness.appspot.com/o/users%2F'
                + rfid + '%2Fscheda.pdf?alt=media')
            qr.png(destination_path + '/qr_code.png', scale=4)
        except Exception as e:
            raise Exception(
                "Impossibile creare il QR Code. Contatta la segreteria!")

    def loadViewerScreen(self, rfid, *largs):
        try:
            # try to download user data from firebase
            user_data = self.getUserData(rfid)
            # if user data is not found, raise exception
            if not user_data:
                raise Exception(
                    "Utente non registrato. Chiedi informazioni in segreteria!"
                )

            # ex. filename_path: storage_data/0123456789/scheda_2019-12-28_02-06-09.zip
            destination_path = 'storage_data/' + rfid
            filename_path = destination_path + '/' + user_data['file']
            # if .zip file doesnt exist download from firebase
            if not path.isfile(filename_path):
                self.downloadUserFile(rfid, destination_path, filename_path)

            if not path.isfile(destination_path + '/scheda_0.jpg'):
                self.extractUserFile(rfid, destination_path, filename_path)

            if not path.isfile(destination_path + '/qr_code.png'):
                self.createQRCode(rfid, destination_path)

            self.viewer_screen.setUserData(user_data)
            self.screen_manager.current = 'viewer'

        except Exception as e:
            self.showHint(str(e))

    def handler(self, rfid):
        Clock.schedule_once(
            partial(self.home_screen.setHintMessage, "Carico scheda..."), -1)
        self.screen_manager.current = 'home'
        Clock.schedule_once(partial(self.loadViewerScreen, rfid), 0.1)

    def showHint(self, text, timeout=6):
        if self.cleanInfoEvent: Clock.unschedule(self.cleanInfoEvent)
        self.home_screen.setHintMessage(text)
        self.cleanInfoEvent = Clock.schedule_once(
            partial(self.home_screen.setHintMessage, ""), timeout)