How to implement role-based access control and session management in React JS using React Router

I am building a web application for my final year project using the MERN stack and I am stuck on how to implement role-based access control. The app itself is a peer-to-peer lending app. I have three different user types: admin, lenders, and borrowers. All three user types have different views on their menus and dashboards. When a lender logs in, they should be redirected to the lender dashboard and the same should apply to the borrower. The system should also capture the logged-in user’s id and only show transactions that are associated with that id. In my database, there is a field for user-type that I’m using to identify whether the logged-in user is a lender or a borrower. The problem I have is capturing the user’s unique id when they log in and then redirect them to a page that only shows their specific transactions.

Below is the code for the login function. Kindly assist.

import { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Logo from "../../assets/images/logo.png";
import Control from "../Controls/Control";
import useStyles from "./LoginStyles";

export default function Login({ history }) {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");
    const classes = useStyles();
    
    useEffect(() => {
        if (localStorage.getItem("authToken")) {
            history.push("/");
        }
    }, [history]);

    const signInHandler = async (e) => {
        e.preventDefault();

        const config = {
            header: {
                "Content-Type": "application/json",
            },
        };

        try {
            const { data } = await axios.post(
                "/api/auth/login",
                { email, password },
                config
            );

            localStorage.setItem("authToken", data.token);
            const myToken = localStorage.getItem("authToken");
            const loggedInUser = JSON.parse(window.atob(myToken.slice(37, 127)));
            
            history.push('/lenders');
        } catch (error) {
            setError(error.response.data.error);
            setTimeout(() => {
                setError("");
            }, 5000);
        }
    };

    return (
        <div>
            <AppBar position='static'>
                <Toolbar>
                    <img src={Logo} alt='logo' className={classes.logo} />
                    <Typography variant='h6' className={classes.title}>
                        EazyKopa
                    </Typography>
                    <Link className={classes.links}>Home</Link>
                    <Link className={classes.links}>About</Link>
                    <Link className={classes.links}>How it works</Link>
                </Toolbar>
            </AppBar>
            <section className={classes.skewBox}>
                <div className={classes.content}>
                    Please provide your registered email and password to login to the
                    platform or sign up if you are a new user.
                </div>
                <div className={classes.loginForm}>
                    <form onSubmit={signInHandler}>
                        <Typography variant='h5'>Sign In</Typography>
                        {error && <span>{error}</span>}
                        <div className={classes.formElements}>
                            <Control.Input
                                variant='outlined'
                                label='Email'
                                type='email'
                                required
                                name='email'
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                className={classes.inputButton}
                            />
                            <Control.Input
                                variant='outlined'
                                label='Password'
                                name='password'
                                type='password'
                                required
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                className={classes.inputButton}
                            />
                        </div>
                        <Control.Button
                            type='submit'
                            text='Login'
                            variant='contained'
                            color='primary'
                            size='large'
                            disabled={email === "" || password === ""}
                            className={classes.loginButton}
                        />
                        <Typography variant='h6'>
                            Don't have an account? <Link to='/sign-up'>Sign Up</Link>
                        </Typography>
                    </form>
                </div>
            </section>
        </div>
    );
}

Source: Ask Javascript Questions

LEAVE A COMMENT