0

Trying to build an auto-logout feature, and have got a timer going but looking for a way to start/restart the timer based on user's last active time.

The scenario is that the user has been away from their keyboard for X amount of time, and we want to log them out.

Adding the code I've come up with since then:

// main.js
import React from 'react'
import { Admin } from 'react-admin'
import authProvider from '../../auth-provider'
import restClient from '../../rest-client'
import buildResources from './build-resources'
import { setLastActive } from './last-active'

const customReducers = {
  lastActive,
}

function lastActive() {
  const now = Date.now()
  setLastActive(now)

  return now
}

export const Main = () => (
  <Admin
    authProvider={authProvider}
    dataProvider={restClient}
    customReducers={customReducers}
  >
    {buildResources}
  </Admin>
)

// last-active.js
let lastActive

export const setLastActive = (timestamp = Date.now()) =>
  (lastActive = timestamp)

export const getLastActive = () => lastActive || null

It's not all the code, but enough to show the gist. I can know use the redux store, or the singleton to grab when they were last active. It's a bit flawed since most, not all actions go through the redux store.

  • You might want to demonstrate what you have tried before someone can answer the question. Good question recommendations on SO mention that you have to prove you have tried something. – Whirl Mind Mar 24 '20 at 08:55
  • Was kinda of hoping for an official solution that wasn't yet documented. I ended up giving it a messy shot, and got it working somewhat close to being production ready. I think to get to where I really need to be, I'll need to put up a PR to get in the library and be able to use the Providers directly. – Pedro Mass Apr 02 '20 at 14:24

1 Answers1

0

react-admin works well with API-structured Apps.

Based on that fact, am assuming your App consumes endpoints (a lot!!).
Here's a possible process to auto-logout a user.

  • Set the token in authProvider.login method

  • Within your authprovider.checkError method, use setTimeout method to clear the token. This timeout can be based on last CRUD method executed.

  • Once the token is cleared, react-admin redirects the user to logout.
    Thus requiring the user to re-login.

MwamiTovi
  • 2,425
  • 17
  • 25