Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #59: Added timeout tracker to check session expiration #134

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import Notifications from './pages/Notifications'
import Context from './modules/Context'
import ContextReducer from './modules/ContextReducer'
import Footer from './components/Footer'
import IdleTimer from './utils/IdleTimer'
import logout from './utils/Logout'
const { sessionLimit } = require('./config.json')

const initialState = {
auth: false,
Expand Down Expand Up @@ -56,6 +59,29 @@ const App = () => {
}
}, [userId])

useEffect(() => {
if (!userId) return

const timer = new IdleTimer({
timeout: sessionLimit || 6 * 3600,
onTimeout: () => {
logout()
dispatch({
type: 'DEAUTHENTICATE'
})
},
onExpired: () => {
dispatch({
type: 'DEAUTHENTICATE'
})
}
})

return () => {
timer.cleanUp()
}
}, [userId])

return (
<Context.Provider value={{ state, dispatch }}>
<Router>
Expand Down
5 changes: 5 additions & 0 deletions src/pages/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import AuthWrapper, {
AuthLeftContainer,
AuthRightContainer
} from '../components/AuthWrapper'
const { sessionLimit } = require('../config.json')

export const Login = (props) => {
const { message } = props
Expand Down Expand Up @@ -41,6 +42,10 @@ export const Login = (props) => {
localStorage.setItem('id', payload.user.id)
localStorage.setItem('username', payload.user.username)
localStorage.setItem('email', payload.user.email)
localStorage.setItem(
'_expiredTime',
Date.now() + (sessionLimit || 3600) * 1000
)
dispatch({
type: 'AUTHENTICATE'
})
Expand Down
56 changes: 56 additions & 0 deletions src/utils/IdleTimer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* @Class of a timeout tracker that constantly checks
* if the session has expired or not. When the session expires,
* the user is automatically logged out of the application.
* @parameters
* timeout - the time (in seconds) for which the session will be valid
* onTimeout - callback to be executed when the session is expired
* onExpired - callback to be executed if the user opens the applciation
* after the session has already expired
*/

class IdleTimer {
constructor({ timeout, onTimeout, onExpired }) {
this.timeout = timeout
this.onTimeout = onTimeout

// Get the expiration time from local storage and
// check if the session has already expired
const expiredTime = parseInt(localStorage.getItem('_expiredTime') || 0, 10)

// If session has already expired, fire the onExpired callback
if (expiredTime > 0 && expiredTime < Date.now()) {
onExpired()
return
}

// If the session has not expired, start checking the remaining time periodically
this.startInterval()
}

// Function to check periodically if the session has expires
startInterval() {
// Run the check every 1 second
this.interval = setInterval(() => {
const expiredTime = parseInt(
localStorage.getItem('_expiredTime') || 0,
10
)

// Check if the session has expired
if (expiredTime < Date.now()) {
if (this.onTimeout) {
this.onTimeout()
this.cleanUp()
}
}
}, 1000)
}

// cleanup code for the timeout tracker
cleanUp() {
localStorage.removeItem('_expiredTime')
clearInterval(this.interval)
}
}
export default IdleTimer
11 changes: 11 additions & 0 deletions src/utils/Logout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import axios from 'axios'
import { navigate } from '@reach/router'
const { apiURL } = require('../config.json')

const logout = async () => {
await axios.post(`${apiURL}/logout`, {}, { withCredentials: true })
localStorage.clear()
navigate('/')
}

export default logout