reboottime / React-Develpment

Some notes, thought, articles or source code readings aggregated here about React Web development.
0 stars 0 forks source link

Securing Your React Application #104

Open reboottime opened 5 months ago

reboottime commented 5 months ago

Overview

This article covers topic - build secure react app, together some general tips


Content

reboottime commented 5 months ago

Common Practices

Network Perspective



Programming Part

reboottime commented 5 months ago

Securing Your React Application

General tips

Solutions

reboottime commented 5 months ago

react-idle-timer sample code

In a production app, the session validity and idle time are configurable. so you will need to derive the MAX_IDLE_TIME from the session validity time and sometime to remind user to take action.


image



If user clicks the stay logged in button, frontend makes request to backend side to extend the session time.



  const [showIdleDialog, setShowIdleDialog] = useState(false);

  const { start, reset } = useIdleTimer({
    startManually: true,
    timeout: MAX_IDLE_TIME,
    onIdle: () => {
      setShowIdleDialog(true);
    });

  // Apply your logic to start/rset the timer programatically 


import { useEffect, useRef, useState } from 'react';

import Button from './ui/button';
import Dialog, { DialogContent, DialogFooter, DialogTitle } from './ui/dialog';

const IdleDialog = ({ onStayLoggedIn, onLogout }: IdleDialogProps) => {
  const timerRef = useRef<ReturnType<typeof setInterval> | undefined>();
  const [remainingTime, setRemainingTime] = useState(60);

  useEffect(() => {
    timerRef.current = setInterval(() => {
      setRemainingTime((prev) => {
        const nextTime = prev - 1;

        if (nextTime <= 0) {
          clearInterval(timerRef.current);
          onLogout();
        }

        return nextTime;
      });
    }, 1000);

    return () => {
      clearInterval(timerRef.current);
    };
  }, [onLogout]);

  return (
    <Dialog open>
      <DialogContent className='border border-brand'>
        <DialogTitle>Reminder</DialogTitle>
        <p className='text-dark mb-6'>
          You have been inactive for a while. To secure your data, you will be
          logged out in{' '}
          <span className='font-bold text-xl text-brand'>{remainingTime}</span>{' '}
          seconds.
        </p>
        <DialogFooter className='flex justify-end'>
          <Button onClick={onLogout} variant='outline'>
            Logout
          </Button>
          <Button
            onClick={() => {
              onStayLoggedIn();
              clearTimeout(timerRef.current);
              setRemainingTime(60);
            }}
          >
            Stay Logged In
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default IdleDialog;

interface IdleDialogProps {
  onLogout: () => void;
  onStayLoggedIn: () => void;
}