示例#1
0
    def test_getdate_in_view(self):
        tableCursor = getDateForViewCursor(self.context)
        tableCursor.deleteAll()

        viewCursor = viewWithGetDateCursor(self.context)
        self.assertEquals(0, viewCursor.count())

        tableCursor.date = Timestamp.valueOf(LocalDateTime.now().minusDays(1))
        tableCursor.insert()
        self.assertEquals(0, viewCursor.count())

        tableCursor.clear()
        tableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        tableCursor.insert()
        self.assertEquals(1, viewCursor.count())
    def unLockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService = CdiUtil.bean(CacheService)

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        object_to_store = json.dumps(
            {
                'locked': False,
                'created': LocalDateTime.now().toString()
            },
            separators=(',', ':'))
        cacheService.put(StringHelper.toString(self.lockExpirationTime),
                         "lock_user_" + user_name, object_to_store)

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus",
                                       "active")
        userService.setCustomAttribute(find_user_by_uid,
                                       self.invalidLoginCountAttribute, None)
        updated_user = userService.updateUser(find_user_by_uid)

        print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
示例#3
0
    def _testInFilterWithAdditionalLookup(self, a, b, g):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)
        gTableCursor = gFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()
        gTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        self._fillTablesForTestInFilterWithRangeOnOtherCursor(aTableCursor, bTableCursor, timestamp)

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 5
        gTableCursor.num2 = -30
        gTableCursor.insert()
        gTableCursor.clear()

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 6
        gTableCursor.num2 = -40
        gTableCursor.insert()
        gTableCursor.clear()

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 1
        gTableCursor.num2 = -41
        gTableCursor.insert()
        gTableCursor.clear()

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 1
        gTableCursor.num2 = -42
        gTableCursor.insert()
        gTableCursor.clear()


        lookup = a.setIn(b).add("date", "created").add("number1", "numb1")
        additionalLookup = lookup.and(g).add("date", "createDate").add("number1", "num1")

        self.assertEquals(3, a.count())

        b.setRange('numb2', -40)
        self.assertEquals(2, a.count())

        a.first()
        self.assertEquals(5, a.number1)
        self.assertEquals(-10, a.number2)

        a.navigate('>')
        self.assertEquals(6, a.number1)
        self.assertEquals(-20, a.number2)

        g.setRange('num2', -30)
        self.assertEquals(1, a.count())

        a.first()
        self.assertEquals(5, a.number1)
        self.assertEquals(-10, a.number2)
示例#4
0
    def _testInFilterWithRangeInOtherCursorAfterSetIn(self, a, b):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        self._fillTablesForTestInFilterWithRangeOnOtherCursor(aTableCursor, bTableCursor, timestamp)


        lookup = a.setIn(b).add("date", "created").add("number1", "numb1")

        self.assertEquals(3, a.count())

        b.setRange('numb2', -40)
        self.assertEquals(2, a.count())

        a.first()
        self.assertEquals(5, a.number1)
        self.assertEquals(-10, a.number2)

        a.navigate('>')
        self.assertEquals(6, a.number1)
        self.assertEquals(-20, a.number2)
示例#5
0
    def lockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        status_attribute_value = userService.getCustomAttribute(find_user_by_uid, "gluuStatus")
        if status_attribute_value != None:
            user_status = status_attribute_value.getValue()
            if StringHelper.equals(user_status, "inactive"):
                print "Basic (lock account). Lock user. User '%s' locked already" % user_name
                return
        
        userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "inactive")
        updated_user = userService.updateUser(find_user_by_uid)

        object_to_store = json.dumps({'locked': True, 'created': LocalDateTime.now().toString()}, separators=(',',':'))

        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your account is locked. Please try again after " + StringHelper.toString(self.lockExpirationTime) + " secs")

        print "Basic (lock account). Lock user. User '%s' locked" % user_name
示例#6
0
    def _testInFilterForIndices(self, a, b):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        aTableCursor.date = timestamp
        aTableCursor.number1 = 5
        aTableCursor.number2 = -10
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = timestamp
        aTableCursor.number1 = 1
        aTableCursor.number2 = -20
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        aTableCursor.number2 = -30
        aTableCursor.insert()
        aTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 2
        bTableCursor.numb2 = -40
        bTableCursor.insert()
        bTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 5
        bTableCursor.numb2 = -50
        bTableCursor.insert()
        bTableCursor.clear()

        lookup = a.setIn(b).add("date", "created")
        self.assertEquals(2, a.count())

        lookup = a.setIn(b).add("date", "created").add("number1", "numb1")
        self.assertEquals(1, a.count())

        a.setIn(b).add("date", "created").add("number1", "numb1").add("number2", "numb2")
        self.assertEquals(0, a.count())
示例#7
0
 def onCall(self, type):
     if type == "string":
         return DynamicValue("text", StringType())
     elif type == "boolean":
         return DynamicValue(True, BooleanType())
     elif type == "datetime":
         return DynamicValue(LocalDateTime.now(), DateTimeType().withTime().withFormat("HH:mm"))
     else:
         return None
示例#8
0
    def _testInFilterWithRangeInMainCursor(self, a, b):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        aTableCursor.date = timestamp
        aTableCursor.number1 = 5
        aTableCursor.number2 = -10
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = timestamp
        aTableCursor.number1 = 1
        aTableCursor.number2 = -20
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        aTableCursor.number2 = -30
        aTableCursor.insert()
        aTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 2
        bTableCursor.numb2 = -40
        bTableCursor.insert()
        bTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 5
        bTableCursor.numb2 = -50
        bTableCursor.insert()
        bTableCursor.clear()

        a.setRange('number1', 5)
        lookup = a.setIn(b).add("date", "created")
        self.assertEquals(1, a.count())
        a.first()
示例#9
0
    def addLog(self, messageInfo, toolFlag, time, row, operationName):

        self.panel.getLogTableModel().getLogArray().add(
            Log(
                LocalDateTime.now(), self._callbacks.getToolName(toolFlag),
                self._callbacks.saveBuffersToTempFiles(messageInfo),
                self._helpers.analyzeRequest(messageInfo).getUrl(),
                self._helpers.analyzeResponse(
                    messageInfo.getResponse()).getStatusCode(), operationName,
                time))
        self.panel.getLogTableModel().fireTableRowsInserted(row, row)
示例#10
0
	def __init__(self,uuid,url,title,dateTime):    

		'''HistoryDataElements must have at least one UUID, URL, Title, & DateTime '''
		valid = (type(uuid) is UUID) and (isinstance(url,str))	and (isinstance(title,str)) and (type(dateTime) is LocalDateTime)

		if not valid:
			from InvalidHistoryDataElementException import InvalidHistoryDataElementException
			raise InvalidHistoryDataElementException()
		else:
			super(HistoryDataElement,self).add(0, uuid)
			super(HistoryDataElement,self).add(1, url)
			super(HistoryDataElement,self).add(2, title)
			super(HistoryDataElement,self).add(3, dateTime)
			print("Log: HistoryDataElement object constructed @ " +  str(LocalDateTime.now()) + " with UUID: " + str(self.get(0)))
示例#11
0
    def test_count_with_getdate_condition(self):
        tableCursor = countGetDateCondCursor(self.context)
        tableCursor.deleteAll()

        viewCursor = viewCountGetDateCondCursor(self.context)
        viewCursor.first()
        self.assertEquals(0, viewCursor.c)

        tableCursor.insert()
        tableCursor.clear()
        tableCursor.date = Timestamp.valueOf(
            LocalDateTime.now().minusSeconds(2))
        tableCursor.insert()

        viewCursor.first()
        self.assertEquals(0, viewCursor.c)

        tableCursor.clear()
        tableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        tableCursor.insert()

        viewCursor.first()
        self.assertEquals(1, viewCursor.c)
    def unLockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        object_to_store = json.dumps({'locked': False, 'created': LocalDateTime.now().toString()}, separators=(',',':'))
        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "active")
        userService.setCustomAttribute(find_user_by_uid, self.invalidLoginCountAttribute, None)
        updated_user = userService.updateUser(find_user_by_uid)


        print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
示例#13
0
    def _fillTablesForTestInFilterWithRangeOnOtherCursor(self, a, b, timestamp):
        a.date = timestamp
        a.number1 = 5
        a.number2 = -10
        a.insert()
        a.clear()

        a.date = timestamp
        a.number1 = 6
        a.number2 = -20
        a.insert()
        a.clear()

        a.date = timestamp
        a.number1 = 1
        a.number2 = -20
        a.insert()
        a.clear()

        a.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        a.number2 = -30
        a.insert()
        a.clear()

        b.created = timestamp
        b.numb1 = 6
        b.numb2 = -40
        b.insert()
        b.clear()

        b.created = timestamp
        b.numb1 = 5
        b.numb2 = -40
        b.insert()
        b.clear()

        b.created = timestamp
        b.numb1 = 1
        b.numb2 = -41
        b.insert()
        b.clear()
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Basic (lock account). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            cacheService = CdiUtil.bean(CacheService)
            userService = CdiUtil.bean(UserService)

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                try:
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if logged_in:
                self.setUserAttributeValue(user_name,
                                           self.invalidLoginCountAttribute,
                                           StringHelper.toString(0))
            else:
                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % (user_name,
                                                            userSatus)

                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % (
                        remainingAttempts, user_name)

                    self.setUserAttributeValue(
                        user_name, self.invalidLoginCountAttribute,
                        StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(
                            FacesMessage.SEVERITY_INFO,
                            StringHelper.toString(remainingAttempts) +
                            " more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and (
                    (userSatus == None) or (userSatus == "active")):
                    print "Basic (lock account). Locking '%s' for '%s' seconds" % (
                        user_name, self.lockExpirationTime)
                    self.lockUser(user_name)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps
                    ) and userSatus == "inactive":
                    print "Basic (lock account). User '%s' is locked. Checking if we can unlock him" % user_name

                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(
                        None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "Basic (lock account). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details[
                            'created']
                        user_lock_details_created_date = LocalDateTime.parse(
                            user_lock_details_created,
                            DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(
                            user_lock_details_created_date,
                            LocalDateTime.now()).getSeconds()
                        print "Basic (lock account). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % (
                            user_name, user_lock_details_locked,
                            user_lock_details_created,
                            user_lock_details_created_diff)

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "Basic (lock account). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(
                            user_name, self.invalidLoginCountAttribute,
                            StringHelper.toString(0))
                        logged_in = authenticationService.authenticate(
                            user_name, user_password)
                        if not logged_in:
                            # Update number of attempts
                            self.setUserAttributeValue(
                                user_name, self.invalidLoginCountAttribute,
                                StringHelper.toString(1))
                            if self.maximumInvalidLoginAttemps == 1:
                                # Lock user if maximum count login attempts is 1
                                self.lockUser(user_name)
                                return False

            return logged_in
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Basic (lock account). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            cacheService = CdiUtil.bean(CacheService)
            userService = CdiUtil.bean(UserService)


            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                try:
                    logged_in = authenticationService.authenticate(user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if logged_in:
                self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0))
            else:
                countInvalidLoginArributeValue = self.getUserAttributeValue(user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % ( user_name, userSatus )

                countInvalidLogin = StringHelper.toInteger(countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % ( remainingAttempts, user_name )

                    self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(FacesMessage.SEVERITY_INFO, StringHelper.toString(remainingAttempts)+" more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and ((userSatus == None) or (userSatus == "active")):
                    print "Basic (lock account). Locking '%s' for '%s' seconds" % ( user_name, self.lockExpirationTime)
                    self.lockUser(user_name)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and userSatus == "inactive":
                    print "Basic (lock account). User '%s' is locked. Checking if we can unlock him" % user_name
                    
                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "Basic (lock account). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details['created']
                        user_lock_details_created_date = LocalDateTime.parse(user_lock_details_created, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(user_lock_details_created_date, LocalDateTime.now()).getSeconds()
                        print "Basic (lock account). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % ( user_name, user_lock_details_locked, user_lock_details_created, user_lock_details_created_diff )

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "Basic (lock account). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0))
                        logged_in = authenticationService.authenticate(user_name, user_password)
                        if not logged_in:
                            # Update number of attempts 
                            self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(1))
                            if self.maximumInvalidLoginAttemps == 1:
                                # Lock user if maximum count login attempts is 1 
                                self.lockUser(user_name)
                                return False


            return logged_in
        else:
            return False
示例#16
0
    def show(self):
        #Root Pane
        root = VBox()
        #FXML Loader
        fxmlLoader = FXMLLoader()

        #TextArea
        from javafx.scene.control import TextArea
        textArea = TextArea("Loading . . .")

        #Configure Text Area
        textArea.setEditable(False)
        textArea.setPrefHeight(600)

        #Bottom Bar, Current Stylesheet
        if self.app.getCurrentTheme() == "Dark":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_dark.fxml").toURI().
                toURL())  #For some odd reason this is broken?
            bottom_bar = self.app.bottom_bar_dt
        elif self.app.getCurrentTheme() == "Light":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_light.fxml").toURI().
                toURL())
            bottom_bar = ImageView(
                Image(
                    String(
                        File('../resources/icons/bottom_bar_lt.png').toURI().
                        toString()), True))
        #Think about future themes
        else:
            pass

        #URL Bar
        try:
            url_bar = fxmlLoader.load(
            )  #BROKEN - For some reason this breaks after a couple toggles.
        except LoadException as e:
            print('Log: Exception: An FXML Load Exception has occured.' +
                  str(e.getCause()))

        #Add Children to root pane
        root.getChildren().addAll(url_bar, textArea, bottom_bar)

        #Fill Width, assume Theme of Main Stage
        root.setFillWidth(True)

        #Set scene, title
        scene = Scene(root, 1350, 625)

        #We are leaving the default controls for now.

        #Make sure the Text Area's scroll bar is always visible.
        scene.getStylesheets().add(
            File("../resources/themes/text-area_scroll-pane.css").toURI().
            toString())
        self.stage.setScene(scene)
        self.stage.setTitle("History - EmeraldFX")

        #Position History Stage
        self.stage.setX(self.app.getMainStage().getX())
        self.stage.setY(self.app.getMainStage().getY() + 52)

        #Display History Stage
        self.stage.show()

        #It is CSV, let us display as plain text.
        history_csv = File("../resources/history/HISTORY.csv")
        history_txt = File("../resources/history/HISTORY.txt")

        #Delete text copy if it exists
        history_txt.delete() if history_txt.exists() else None

        #Copy
        Files.copy(history_csv.toPath(), history_txt.toPath())

        #Prevent Resizing
        self.stage.setResizable(False)

        #Flush Stream
        self.BS.triggerHistoryWrite()

        #GetController instance
        controller = fxmlLoader.getController()
        ''' Failed Attempts '''

        #WebView
        # webView = WebView()
        #Grab Web Engine
        # webEng = webView.getEngine()
        #Enable JS
        # webEng.setJavaScriptEnabled(True)

        #Attempt #1 - Start scrolling from the bottom - FAILED
        # webEng.executeScript("window.scrollTo(" + "0" + ", " + "600" + ");")

        #Attempt #2 - Scroll Pane - FAILED
        # from javafx.scene.control import ScrollPane
        # wv_scroll = ScrollPane()
        # wv_scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS)
        # wv_scroll.setContent(webView)
        # wv_scroll.setFitToWidth(True)
        # wv_scroll.setFitToHeight(True)
        # wv_scroll.setVvalue(wv_scroll.getVmin())

        #Load History
        # try:
        # webEng.load(history_txt.toURI().toString())
        # except Exception as e:
        # print ('Log: Load Exception: Error Loading History: ' + str(e.getCause()))
        # return

        #Attempt #3 - Execute Script for Scroll Bar - FAILD
        # webEng.executeScript(
        # "function scrollDown() { window.scrollTo(0,400); }" +
        # "scrollDown();"
        # )

        #Set Position of Scroll Bar
        class AnonInnerCL_TA(ChangeListener):
            """Inner Class for Scrolling Down"""
            def __init__(self, textArea):
                self.textArea = textArea

            #@Override
            def changed(self, observable, old, new):
                if new > old:
                    from java.lang import Double
                    self.textArea.setScrollTop(Double.MAX_VALUE)
                else:
                    pass

        textArea.textProperty().addListener(AnonInnerCL_TA(textArea))

        #Show History after it is loaded
        if self.stage.isShowing(
        ):  #May or may not be broken. If there is litle to no delay, "Loading . . ." will not be noticed.
            #Load History on separate thread.
            #Clear initial text: Loading . . .
            textArea.clear()
            #Instantate Service
            service = HistoryService(history_txt, textArea)
            #Algorithm improved. Start service
            service.start()
        '''Add resources to controller'''
        #Theme Resources
        controller.addThemeResources(
            self.app.getMainStage(), self.stage,
            self.app.getMainStage().getScene(), self.app.getCurrentTheme(),
            textArea
        )  #(Stage mainStage, Stage histStage, Scene scene, String theme, TextArea textArea)
        #Clear Resource
        controller.addClearResources(self.BS.isHistoryCleared())  #(boolean)
        #Quit Resources
        controller.addQuitResources(
            self.app.getAllStages(),
            self.BS.getHistoryWriter())  #(List<Stages>, PrintWriter)
        #Media Resources
        MMC = self.app.getMediaControls()
        controller.addMediaResources(MMC)

        #Create Bidirectional Bindings between Main Stage's media controls and history's controls
        from javafx.beans.binding import Bindings

        MMC_IT = MMC.listIterator()
        HMC = controller.getMediaControls()

        #Set history media controls to current state
        class HMCC(Consumer):
            def __init__(self, MMC_IT):
                self.MMC_IT = MMC_IT

            #@Override
            def accept(self, button):
                button.setDisabled(MMC_IT.next().isDisabled())

        HMC.forEach(HMCC(MMC_IT))

        #Fails - first arg cannot be coerced into Consumer? Odd.
        # history_media_controls.forEach(lambda button: button.setDisabled( main_media_controls.forEach(lambda button: button.isDisabled()) ) )

        #Play
        #Won't work -- read only property does not inherit Property, seperate API.
        # Bindings.bindBidirectional(history_media_controls.get(0).disabledProperty(), main_media_controls[0].disabledProperty() )
        #Stop
        # Bindings.bindBidirectional(history_media_controls.get(1).disabledProperty(), main_media_controls[1].disabledProperty() )
        #Previous
        # Bindings.bindBidirectional(history_media_controls.get(2).disabledProperty(), main_media_controls[2].disabledProperty() )
        #Next
        # Bindings.bindBidirectional(history_media_controls.get(3).disabledProperty(), main_media_controls[3].disabledProperty() )

        #Shortcut Keys Allowed for History (CTRL + D, CTRL + Q, CTRL + T)
        scene.addEventFilter(
            KeyEvent.KEY_PRESSED, lambda event: self.handleHistoryShortcuts(
                event, self.BS, controller.getToggleTheme(),
                controller.getClearHistory()))

        #Python needs to fix lambdas so we don't have to resort to wrapping inner classes in collections. Yuck.
        class HistoryClosed:
            @staticmethod
            def printClosed():
                print("Log: Quit Action: History just closed.")

        #Switch back to the main stage
        self.stage.setOnCloseRequest(lambda event: [
            self.app.getMainStage().toFront(),
            self.stage.close(),
            HistoryClosed.printClosed()
        ])

        #Log
        print('Log: History Notification: History data displayed @ ' +
              str(LocalDateTime.now()))
示例#17
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        self.setRequestScopedParameters(identity)

        if step == 1:

            #############################################
            ### LOCKOUT
            print "OTP (with lockout). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            cacheService = CdiUtil.bean(CacheService)

            print "OTP (with lockout). Authenticate for step 1"
            authenticated_user = self.processBasicAuthentication(credentials)

            if authenticated_user != None:
                self.setUserAttributeValue(user_name,
                                           self.invalidLoginCountAttribute,
                                           StringHelper.toString(0))
            elif user_name != self.no_lockout_admin:
                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % (user_name,
                                                            userSatus)

                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % (
                        remainingAttempts, user_name)

                    self.setUserAttributeValue(
                        user_name, self.invalidLoginCountAttribute,
                        StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(
                            FacesMessage.SEVERITY_INFO,
                            StringHelper.toString(remainingAttempts) +
                            " more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and (
                    (userSatus == None) or (userSatus == "active")):
                    print "OTP (with lockout). Locking '%s' for '%s' seconds" % (
                        user_name, self.lockExpirationTime)
                    self.lockUser(user_name, self.maximumInvalidLoginAttemps)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps
                    ) and userSatus == "inactive":
                    print "OTP (with lockout). User '%s' is locked. Checking if we can unlock him" % user_name

                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(
                        None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "OTP (with lockout). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details[
                            'created']
                        user_lock_details_created_date = LocalDateTime.parse(
                            user_lock_details_created,
                            DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(
                            user_lock_details_created_date,
                            LocalDateTime.now()).getSeconds()
                        print "OTP (with lockout). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % (
                            user_name, user_lock_details_locked,
                            user_lock_details_created,
                            user_lock_details_created_diff)

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "OTP (with lockout). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(
                            user_name, self.invalidLoginCountAttribute,
                            StringHelper.toString(0))
                        ### TODO: Fix free attempt after unlock
                        authenticated_user = self.processBasicAuthentication(
                            credentials)
                        if authenticated_user == None:
                            self.setUserAttributeValue(
                                user_name, self.invalidLoginCountAttribute,
                                StringHelper.toString(1))

            if authenticated_user == None:
                return False
            ### LOCKOUT
            #############################################

            # Check the otp_group user membership
            if (self.use_otp_group):
                print "OTP (with lockout). Authenticate for step 1. Checking if user '%s' belongs to otp_group" % authenticated_user.getUserId(
                )
                is_member_otp_group = self.isUserMemberOfGroup(
                    authenticated_user, self.audit_attribute, self.otp_group)
                if not is_member_otp_group:
                    print "OTP (with lockout). Authenticate for step 1. User '%s' not a member of otp group, skipping OTP" % authenticated_user.getUserId(
                    )
                    identity.setWorkingParameter("otp_count_login_steps", 1)
                    return True
                else:
                    print "OTP (with lockout). Authenticate for step 1. User '%s' is a member of otp group, continue to OTP" % authenticated_user.getUserId(
                    )

            otp_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second OTP registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    otp_auth_method = "enroll"

            if otp_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(
                    authenticated_user.getUserId())
                if len(user_enrollments) == 0:
                    otp_auth_method = "enroll"
                    print "OTP (with lockout). Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % (
                        authenticated_user.getUserId(), otp_auth_method)

            if otp_auth_method == "enroll":
                print "OTP (with lockout). Authenticate for step 1. Setting count steps: '%s'" % 3
                identity.setWorkingParameter("otp_count_login_steps", 3)

            print "OTP (with lockout). Authenticate for step 1. otp_auth_method: '%s'" % otp_auth_method
            identity.setWorkingParameter("otp_auth_method", otp_auth_method)

            return True
        elif step == 2:
            print "OTP (with lockout). Authenticate for step 2"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP (with lockout). Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method == 'enroll':
                auth_result = ServerUtil.getFirstValue(requestParameters,
                                                       "auth_result")
                if not StringHelper.isEmpty(auth_result):
                    print "OTP (with lockout). Authenticate for step 2. User not enrolled OTP"
                    return False

                print "OTP (with lockout). Authenticate for step 2. Skipping this step during enrollment"
                return True

            otp_auth_result = self.processOtpAuthentication(
                requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP (with lockout). Authenticate for step 2. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        elif step == 3:
            print "OTP (with lockout). Authenticate for step 3"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP (with lockout). Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method != 'enroll':
                return False

            otp_auth_result = self.processOtpAuthentication(
                requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP (with lockout). Authenticate for step 3. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        else:
            return False