import React from 'react' ; import { throttle } from 'lodash' ; import Logger from 'shared/libs/logger' ; import session from 'teleport/services/session' ; import history from 'teleport/services/history' ; import localStorage from 'teleport/services/localStorage' ; const logger = Logger . create ( '/components/Authenticated' ) ; const ACTIVITY_CHECKER_INTERVAL_MS = 30 * 1000 ; const ACTIVITY_EVENT_DELAY_MS = 15 * 1000 ; const events = [ 'keydown' , 'pointermove' , 'pointerdown' , ] ; const Authenticated = ( { children } ) => { React . useEffect ( ( ) => { if ( ! session . isValid ( ) ) { logger . warn ( 'invalid session' ) ; session . clear ( ) ; history . goToLogin ( true ) ; return ; } session . ensureSession ( ) ; const inactivityTtl = session . getInactivityTimeout ( ) ; if ( inactivityTtl === 0 ) { return ; } return startActivityChecker ( inactivityTtl ) ; } , [ ] ) ; if ( ! session . isValid ( ) ) { return null ; } return < > { children } < />; } ; export default Authenticated ; function startActivityChecker ( ttl = 0 ) { const adjustedTtl = ttl - ACTIVITY_CHECKER_INTERVAL_MS ; if ( isInactive ( adjustedTtl ) ) { logger . warn ( 'inactive session' ) ; session . logout ( ) ; return ; } localStorage . setLastActive ( Date . now ( ) ) ; const intervalId = setInterval ( ( ) => { if ( isInactive ( adjustedTtl ) ) { logger . warn ( 'inactive session' ) ; session . logout ( ) ; } } , ACTIVITY_CHECKER_INTERVAL_MS ) ; const throttled = throttle ( ( ) => { localStorage . setLastActive ( Date . now ( ) ) ; } , ACTIVITY_EVENT_DELAY_MS ) ; events . forEach ( event => window . addEventListener ( event , throttled ) ) ; function stop ( ) { throttled . cancel ( ) ; clearInterval ( intervalId ) ; events . forEach ( event => window . removeEventListener ( event , throttled ) ) ; } return stop ; } function isInactive ( ttl = 0 ) { const lastActive = localStorage . getLastActive ( ) ; return lastActive > 0 && Date . now ( ) - lastActive > ttl ; }