dev-jaanvi #1
|
@ -10,7 +10,7 @@
|
||||||
"@mui/x-charts": "^7.23.2",
|
"@mui/x-charts": "^7.23.2",
|
||||||
"@mui/x-data-grid": "^7.23.5",
|
"@mui/x-data-grid": "^7.23.5",
|
||||||
"@mui/x-date-pickers": "^7.23.3",
|
"@mui/x-date-pickers": "^7.23.3",
|
||||||
"@mui/x-tree-view": "^7.23.2",
|
"@mui/x-tree-view": "^7.23.2",
|
||||||
"@react-spring/web": "^9.7.5",
|
"@react-spring/web": "^9.7.5",
|
||||||
"@reduxjs/toolkit": "^2.5.0",
|
"@reduxjs/toolkit": "^2.5.0",
|
||||||
"AdapterDayjs": "link:@mui/x-date-pickers/AdapterDayjs",
|
"AdapterDayjs": "link:@mui/x-date-pickers/AdapterDayjs",
|
||||||
|
@ -73,4 +73,4 @@
|
||||||
"@types/react-dom": "^19.0.2",
|
"@types/react-dom": "^19.0.2",
|
||||||
"typescript": "^5.7.3"
|
"typescript": "^5.7.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,76 +1,95 @@
|
||||||
import List from '@mui/material/List';
|
import List from "@mui/material/List";
|
||||||
import ListItem from '@mui/material/ListItem';
|
import ListItem from "@mui/material/ListItem";
|
||||||
import ListItemButton from '@mui/material/ListItemButton';
|
import ListItemButton from "@mui/material/ListItemButton";
|
||||||
import ListItemIcon from '@mui/material/ListItemIcon';
|
import ListItemIcon from "@mui/material/ListItemIcon";
|
||||||
import ListItemText from '@mui/material/ListItemText';
|
import ListItemText from "@mui/material/ListItemText";
|
||||||
import Stack from '@mui/material/Stack';
|
import Stack from "@mui/material/Stack";
|
||||||
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
|
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
|
||||||
import AnalyticsRoundedIcon from '@mui/icons-material/AnalyticsRounded';
|
import AnalyticsRoundedIcon from "@mui/icons-material/AnalyticsRounded";
|
||||||
import FormatListBulletedIcon from '@mui/icons-material/FormatListBulleted';
|
import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
import { Link, useLocation } from "react-router-dom";
|
||||||
|
import { useSelector } from "react-redux";
|
||||||
|
import { RootState } from "../../redux/store/store";
|
||||||
|
|
||||||
const mainListItems = [
|
const baseMenuItems = [
|
||||||
{
|
{
|
||||||
text: 'Home',
|
text: "Home",
|
||||||
icon: <HomeRoundedIcon />,
|
icon: <HomeRoundedIcon />,
|
||||||
url: '/panel/dashboard',
|
url: "/panel/dashboard",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
text: 'Vehicles',
|
text: "Vehicles",
|
||||||
icon: <AnalyticsRoundedIcon />,
|
icon: <AnalyticsRoundedIcon />,
|
||||||
url: '/panel/vehicles',
|
url: "/panel/vehicles",
|
||||||
},
|
},
|
||||||
//created by Eknnor and Jaanvi
|
//created by Eknnor and Jaanvi
|
||||||
{
|
];
|
||||||
text: 'Admin List',
|
|
||||||
icon: <FormatListBulletedIcon />,
|
//Eknoor singh and Jaanvi
|
||||||
url: '/panel/adminlist',
|
//date:- 12-Feb-2025
|
||||||
},
|
//Made a different variable for super admin to access all the details.
|
||||||
|
|
||||||
|
const superAdminOnlyItems = [
|
||||||
|
{
|
||||||
|
text: "Admin List",
|
||||||
|
icon: <FormatListBulletedIcon />,
|
||||||
|
url: "/panel/adminlist",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
type PropType = {
|
type PropType = {
|
||||||
hidden: boolean;
|
hidden: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function MenuContent({ hidden }: PropType) {
|
export default function MenuContent({ hidden }: PropType) {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const userRole = useSelector((state: RootState) => state.auth.user?.role);
|
||||||
|
|
||||||
return (
|
const mainListItems = [
|
||||||
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: 'space-between' }}>
|
...baseMenuItems,
|
||||||
<List dense>
|
...(userRole === "superadmin" ? superAdminOnlyItems : []),
|
||||||
{mainListItems.map((item, index) => (
|
];
|
||||||
<ListItem key={index} disablePadding sx={{ display: 'block', py: 1 }}>
|
|
||||||
{/* Wrap ListItemButton with Link to enable routing */}
|
return (
|
||||||
<ListItemButton
|
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
|
||||||
component={Link}
|
<List dense>
|
||||||
to={item.url}
|
{mainListItems.map((item, index) => (
|
||||||
selected={item.url === location.pathname}
|
<ListItem
|
||||||
sx={{ alignItems: 'center', columnGap: 1 }}
|
key={index}
|
||||||
>
|
disablePadding
|
||||||
<ListItemIcon
|
sx={{ display: "block", py: 1 }}
|
||||||
sx={{
|
>
|
||||||
minWidth: 'fit-content',
|
{/* Wrap ListItemButton with Link to enable routing */}
|
||||||
'.MuiSvgIcon-root': {
|
<ListItemButton
|
||||||
fontSize: 24,
|
component={Link}
|
||||||
},
|
to={item.url}
|
||||||
}}
|
selected={item.url === location.pathname}
|
||||||
>
|
sx={{ alignItems: "center", columnGap: 1 }}
|
||||||
{item.icon}
|
>
|
||||||
</ListItemIcon>
|
<ListItemIcon
|
||||||
<ListItemText
|
sx={{
|
||||||
sx={{
|
minWidth: "fit-content",
|
||||||
display: !hidden ? 'none' : '',
|
".MuiSvgIcon-root": {
|
||||||
transition: 'all 0.5s ease',
|
fontSize: 24,
|
||||||
'.MuiListItemText-primary': {
|
},
|
||||||
fontSize: '16px',
|
}}
|
||||||
},
|
>
|
||||||
}}
|
{item.icon}
|
||||||
primary={item.text}
|
</ListItemIcon>
|
||||||
/>
|
<ListItemText
|
||||||
</ListItemButton>
|
sx={{
|
||||||
</ListItem>
|
display: !hidden ? "none" : "",
|
||||||
))}
|
transition: "all 0.5s ease",
|
||||||
</List>
|
".MuiListItemText-primary": {
|
||||||
</Stack>
|
fontSize: "16px",
|
||||||
);
|
},
|
||||||
|
}}
|
||||||
|
primary={item.text}
|
||||||
|
/>
|
||||||
|
</ListItemButton>
|
||||||
|
</ListItem>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,6 +11,7 @@ import LogoutRoundedIcon from "@mui/icons-material/LogoutRounded";
|
||||||
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
|
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
|
||||||
import MenuButton from "../MenuButton";
|
import MenuButton from "../MenuButton";
|
||||||
import { Avatar } from "@mui/material";
|
import { Avatar } from "@mui/material";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
const MenuItem = styled(MuiMenuItem)({
|
const MenuItem = styled(MuiMenuItem)({
|
||||||
margin: "2px 0",
|
margin: "2px 0",
|
||||||
|
@ -20,11 +21,18 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
|
||||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||||
const open = Boolean(anchorEl);
|
const open = Boolean(anchorEl);
|
||||||
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||||
setAnchorEl(event.currentTarget);
|
setAnchorEl(event?.currentTarget);
|
||||||
};
|
};
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setAnchorEl(null);
|
setAnchorEl(null);
|
||||||
};
|
};
|
||||||
|
//Eknoor singh and jaanvi
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Made a navigation page for the profile page
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const handleProfile = () => {
|
||||||
|
navigate("/auth/profile");
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<React.Fragment>
|
<React.Fragment>
|
||||||
<MenuButton
|
<MenuButton
|
||||||
|
@ -63,7 +71,7 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<MenuItem onClick={handleClose}>Profile</MenuItem>
|
<MenuItem onClick={handleProfile}>Profile</MenuItem>
|
||||||
<MenuItem onClick={handleClose}>My account</MenuItem>
|
<MenuItem onClick={handleClose}>My account</MenuItem>
|
||||||
<Divider />
|
<Divider />
|
||||||
<MenuItem onClick={handleClose}>Add another account</MenuItem>
|
<MenuItem onClick={handleClose}>Add another account</MenuItem>
|
||||||
|
|
|
@ -1,93 +1,111 @@
|
||||||
import { styled } from '@mui/material/styles';
|
import { styled } from "@mui/material/styles";
|
||||||
import Avatar from '@mui/material/Avatar';
|
import Avatar from "@mui/material/Avatar";
|
||||||
import MuiDrawer, { drawerClasses } from '@mui/material/Drawer';
|
import MuiDrawer, { drawerClasses } from "@mui/material/Drawer";
|
||||||
import Box from '@mui/material/Box';
|
import Box from "@mui/material/Box";
|
||||||
import Stack from '@mui/material/Stack';
|
import Stack from "@mui/material/Stack";
|
||||||
import Typography from '@mui/material/Typography';
|
import Typography from "@mui/material/Typography";
|
||||||
import MenuContent from '../MenuContent';
|
import MenuContent from "../MenuContent";
|
||||||
import OptionsMenu from '../OptionsMenu';
|
import OptionsMenu from "../OptionsMenu";
|
||||||
import React from 'react';
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
import { ArrowLeftIcon, ArrowRightIcon } from '@mui/x-date-pickers';
|
import React, { useEffect } from "react";
|
||||||
import { Button } from '@mui/material';
|
import { ArrowLeftIcon, ArrowRightIcon } from "@mui/x-date-pickers";
|
||||||
|
import { AppDispatch, RootState } from "../../redux/store/store";
|
||||||
|
import { Button } from "@mui/material";
|
||||||
|
import { fetchAdminProfile } from "../../redux/slices/authSlice";
|
||||||
|
|
||||||
const drawerWidth = 240;
|
const drawerWidth = 240;
|
||||||
|
|
||||||
const Drawer = styled(MuiDrawer)({
|
const Drawer = styled(MuiDrawer)({
|
||||||
width: drawerWidth,
|
width: drawerWidth,
|
||||||
flexShrink: 0,
|
flexShrink: 0,
|
||||||
boxSizing: 'border-box',
|
boxSizing: "border-box",
|
||||||
mt: 10,
|
mt: 10,
|
||||||
[`& .${drawerClasses.paper}`]: {
|
[`& .${drawerClasses.paper}`]: {
|
||||||
width: drawerWidth,
|
width: drawerWidth,
|
||||||
boxSizing: 'border-box',
|
boxSizing: "border-box",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function SideMenu() {
|
export default function SideMenu() {
|
||||||
const [open, setOpen] = React.useState(true);
|
const [open, setOpen] = React.useState(true);
|
||||||
return (
|
|
||||||
<Drawer
|
//Eknoor singh
|
||||||
open={open}
|
//date:- 12-Feb-2025
|
||||||
variant="permanent"
|
//Dispatch is called with user from Authstate Interface
|
||||||
anchor="left"
|
|
||||||
sx={{
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
display: {
|
const { user } = useSelector((state: RootState) => state?.auth);
|
||||||
xs: 'none',
|
|
||||||
md: 'block',
|
useEffect(() => {
|
||||||
width: open ? 220 : 80,
|
dispatch(fetchAdminProfile());
|
||||||
transition: 'all 0.5s ease',
|
}, [dispatch]);
|
||||||
},
|
|
||||||
[`& .${drawerClasses.paper}`]: {
|
return (
|
||||||
backgroundColor: 'background.paper',
|
<Drawer
|
||||||
width: open ? 220 : 80,
|
open={open}
|
||||||
transition: 'all 0.5s ease',
|
variant="permanent"
|
||||||
},
|
anchor="left"
|
||||||
}}
|
sx={{
|
||||||
>
|
display: {
|
||||||
<Box
|
xs: "none",
|
||||||
sx={{
|
md: "block",
|
||||||
display: 'flex',
|
width: open ? 250 : 80,
|
||||||
justifyContent: open ? 'flex-end' : 'center',
|
transition: "all 0.5s ease",
|
||||||
alignItems: 'center',
|
},
|
||||||
pt: 1.5,
|
[`& .${drawerClasses.paper}`]: {
|
||||||
textAlign: 'center',
|
backgroundColor: "background.paper",
|
||||||
}}
|
width: open ? 250 : 80,
|
||||||
>
|
transition: "all 0.5s ease",
|
||||||
<Button variant="text" onClick={() => setOpen(!open)}>
|
},
|
||||||
{open ? <ArrowLeftIcon /> : <ArrowRightIcon />}
|
}}
|
||||||
</Button>
|
>
|
||||||
</Box>
|
<Box
|
||||||
<MenuContent hidden={open} />
|
sx={{
|
||||||
{/* <CardAlert /> */}
|
display: "flex",
|
||||||
<Stack
|
justifyContent: open ? "flex-end" : "center",
|
||||||
direction="row"
|
alignItems: "center",
|
||||||
sx={{
|
pt: 1.5,
|
||||||
p: 2,
|
textAlign: "center",
|
||||||
gap: 1,
|
}}
|
||||||
alignItems: 'center',
|
>
|
||||||
borderTop: '1px solid',
|
<Button variant="text" onClick={() => setOpen(!open)}>
|
||||||
borderColor: 'divider',
|
{open ? <ArrowLeftIcon /> : <ArrowRightIcon />}
|
||||||
}}
|
</Button>
|
||||||
>
|
</Box>
|
||||||
<Avatar
|
<MenuContent hidden={open} />
|
||||||
sizes="small"
|
{/* <CardAlert /> */}
|
||||||
alt="Riley Carter"
|
<Stack
|
||||||
src="/static/images/avatar/7.jpg"
|
direction="row"
|
||||||
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
|
sx={{
|
||||||
/>
|
p: 2,
|
||||||
<Box sx={{ mr: 'auto', display: !open ? 'none' : 'block' }}>
|
gap: 1,
|
||||||
<Typography
|
alignItems: "center",
|
||||||
variant="body2"
|
borderTop: "1px solid",
|
||||||
sx={{ fontWeight: 500, lineHeight: '16px' }}
|
borderColor: "divider",
|
||||||
>
|
}}
|
||||||
Riley Carter
|
>
|
||||||
</Typography>
|
<Avatar
|
||||||
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
|
sizes="small"
|
||||||
riley@email.com
|
alt="Riley Carter"
|
||||||
</Typography>
|
src="/static/images/avatar/7.jpg"
|
||||||
</Box>
|
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
|
||||||
<OptionsMenu avatar={open} />
|
/>
|
||||||
</Stack>
|
<Box sx={{ mr: "auto", display: !open ? "none" : "block" }}>
|
||||||
</Drawer>
|
<Typography
|
||||||
);
|
variant="body2"
|
||||||
|
sx={{ fontWeight: 500, lineHeight: "16px" }}
|
||||||
|
>
|
||||||
|
{user?.name || "No Admin"}
|
||||||
|
</Typography>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={{ color: "text.secondary" }}
|
||||||
|
>
|
||||||
|
{user?.email || "No Email"}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<OptionsMenu avatar={open} />
|
||||||
|
</Stack>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,27 +15,30 @@
|
||||||
|
|
||||||
// export default http;
|
// export default http;
|
||||||
|
|
||||||
import axios, { AxiosInstance } from 'axios';
|
//Eknoor singh
|
||||||
|
//date:- 10-Feb-2025
|
||||||
|
//Made different functions for calling different backends and sent them in a function for clarity
|
||||||
|
|
||||||
|
import axios, { AxiosInstance } from "axios";
|
||||||
|
|
||||||
const backendHttp = axios.create({
|
const backendHttp = axios.create({
|
||||||
baseURL: process.env.REACT_APP_BACKEND_URL,
|
baseURL: process.env.REACT_APP_BACKEND_URL,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Axios instance for the local API
|
// Axios instance for the local API
|
||||||
const apiHttp = axios.create({
|
const apiHttp = axios.create({
|
||||||
baseURL: "http://localhost:5000/api",
|
baseURL: "http://localhost:5000/api",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// Add interceptors to both instances
|
// Add interceptors to both instances
|
||||||
const addAuthInterceptor = (instance: AxiosInstance) => {
|
const addAuthInterceptor = (instance: AxiosInstance) => {
|
||||||
instance.interceptors.request.use((config) => {
|
instance.interceptors.request.use((config) => {
|
||||||
const authToken = localStorage.getItem('authToken');
|
const authToken = localStorage.getItem("authToken");
|
||||||
if (authToken) {
|
if (authToken) {
|
||||||
config.headers.Authorization = authToken;
|
config.headers.Authorization = `Bearer ${authToken}`; // <-- Add "Bearer "
|
||||||
}
|
}
|
||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
addAuthInterceptor(backendHttp);
|
addAuthInterceptor(backendHttp);
|
||||||
|
|
102
src/pages/ProfilePage/index.tsx
Normal file
102
src/pages/ProfilePage/index.tsx
Normal file
|
@ -0,0 +1,102 @@
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Made a special page for showing the profile details
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import {
|
||||||
|
Container,
|
||||||
|
Typography,
|
||||||
|
CircularProgress,
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
Grid,
|
||||||
|
Avatar,
|
||||||
|
Box,
|
||||||
|
} from "@mui/material";
|
||||||
|
|
||||||
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
|
import { AppDispatch, RootState } from "../../redux/store/store";
|
||||||
|
import { fetchAdminProfile } from "../../redux/slices/authSlice";
|
||||||
|
|
||||||
|
const ProfilePage = () => {
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Dispatch is called and user, isLoading, and error from Authstate Interface
|
||||||
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
|
const { user, isLoading, error } = useSelector(
|
||||||
|
(state: RootState) => state?.auth
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
dispatch(fetchAdminProfile());
|
||||||
|
}, [dispatch]);
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
height: "100vh",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Container>
|
||||||
|
<Typography variant="h5" color="error" gutterBottom>
|
||||||
|
<h2>An error occurred while loading profile</h2>
|
||||||
|
</Typography>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(user?.name);
|
||||||
|
console.log(user?.email);
|
||||||
|
console.log(user?.role);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container sx={{ py: 4 }}>
|
||||||
|
<Typography variant="h4" gutterBottom>
|
||||||
|
Profile
|
||||||
|
</Typography>
|
||||||
|
<Card sx={{ maxWidth: 600, margin: "0 auto" }}>
|
||||||
|
<CardContent>
|
||||||
|
<Grid container spacing={2} alignItems="center">
|
||||||
|
<Grid item>
|
||||||
|
<Avatar
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//user is called for name and email
|
||||||
|
alt={user?.name || "User Avatar"}
|
||||||
|
src={"/static/images/avatar/7.jpg"}
|
||||||
|
sx={{ width: 80, height: 80 }}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs>
|
||||||
|
<Typography variant="h6">
|
||||||
|
{user?.name || "N/A"}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Email: {user?.email || "N/A"}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Phone: {user?.phone || "N/A"}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Role: {user?.role || "N/A"}
|
||||||
|
</Typography>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProfilePage;
|
|
@ -1,35 +1,41 @@
|
||||||
import {
|
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
||||||
createSlice,
|
|
||||||
createAsyncThunk,
|
|
||||||
PayloadAction,
|
|
||||||
} from "@reduxjs/toolkit";
|
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { backendHttp, apiHttp } from "../../lib/https";
|
import { backendHttp, apiHttp } from "../../lib/https";
|
||||||
import { toast } from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
|
|
||||||
// Define types for state
|
// Define types for state
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Token for the user has been declared
|
||||||
interface User {
|
interface User {
|
||||||
|
token: string | null;
|
||||||
map(
|
map(
|
||||||
arg0: (
|
arg0: (
|
||||||
admin: { name: any; role: any },
|
admin: { name: any; role: any; email: any; phone: any },
|
||||||
index: number
|
index: number
|
||||||
) => { srno: number; name: any; role: any }
|
) => { srno: number; name: any; role: any; email: any; phone: any }
|
||||||
): unknown;
|
): unknown;
|
||||||
id: string;
|
id: string;
|
||||||
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
|
role: string;
|
||||||
|
phone: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Admin {
|
interface Admin {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
email: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AuthState {
|
interface AuthState {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
admins: Admin[];
|
admins: Admin[];
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
error: object | string | null;
|
error: object | string | null;
|
||||||
|
token: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Async thunk for login
|
// Async thunk for login
|
||||||
|
@ -39,7 +45,7 @@ export const loginUser = createAsyncThunk<
|
||||||
{ rejectValue: string }
|
{ rejectValue: string }
|
||||||
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
|
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
|
||||||
try {
|
try {
|
||||||
const response = await backendHttp.post("admin/login", {
|
const response = await apiHttp.post("auth/login", {
|
||||||
email,
|
email,
|
||||||
password,
|
password,
|
||||||
});
|
});
|
||||||
|
@ -85,10 +91,16 @@ export const adminList = createAsyncThunk<
|
||||||
const response = await apiHttp.get("/auth");
|
const response = await apiHttp.get("/auth");
|
||||||
console.log(response?.data?.data);
|
console.log(response?.data?.data);
|
||||||
return response?.data?.data?.map(
|
return response?.data?.data?.map(
|
||||||
(admin: { id: string; name: string; role: string }) => ({
|
(admin: {
|
||||||
id: admin.id,
|
id: string;
|
||||||
|
name: string;
|
||||||
|
role: string;
|
||||||
|
email: string;
|
||||||
|
}) => ({
|
||||||
|
id: admin?.id,
|
||||||
name: admin?.name,
|
name: admin?.name,
|
||||||
role: admin?.role || "N/A",
|
role: admin?.role || "N/A",
|
||||||
|
email: admin?.email,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
|
@ -127,8 +139,8 @@ export const updateAdmin = createAsyncThunk(
|
||||||
try {
|
try {
|
||||||
const response = await apiHttp.put(`/auth/${id}`, { name, role });
|
const response = await apiHttp.put(`/auth/${id}`, { name, role });
|
||||||
toast.success("Admin updated successfully");
|
toast.success("Admin updated successfully");
|
||||||
console.log(response.data);
|
console.log(response?.data);
|
||||||
return response.data;
|
return response?.data;
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return rejectWithValue(
|
return rejectWithValue(
|
||||||
error.response?.data?.message || "An error occurred"
|
error.response?.data?.message || "An error occurred"
|
||||||
|
@ -137,12 +149,50 @@ export const updateAdmin = createAsyncThunk(
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Function for fetching profile of a particular user has been implemented with Redux.
|
||||||
|
export const fetchAdminProfile = createAsyncThunk<
|
||||||
|
User,
|
||||||
|
void,
|
||||||
|
{ rejectValue: string }
|
||||||
|
>("auth/fetchAdminProfile", async (_, { rejectWithValue }) => {
|
||||||
|
try {
|
||||||
|
const token = localStorage?.getItem("authToken");
|
||||||
|
if (!token) throw new Error("No token found");
|
||||||
|
|
||||||
|
const response = await apiHttp?.get("/auth/profile", {
|
||||||
|
headers: { Authorization: `Bearer ${token}` }, // Ensure 'Bearer' prefix
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("API Response:", response?.data); // Debugging
|
||||||
|
|
||||||
|
if (!response.data?.data) {
|
||||||
|
throw new Error("Invalid API response");
|
||||||
|
}
|
||||||
|
|
||||||
|
return response?.data?.data; // Fix: Return only `data`, assuming it contains user info.
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error(
|
||||||
|
"Profile Fetch Error:",
|
||||||
|
error?.response?.data || error?.message
|
||||||
|
);
|
||||||
|
return rejectWithValue(
|
||||||
|
error?.response?.data?.message || "An error occurred"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const initialState: AuthState = {
|
const initialState: AuthState = {
|
||||||
user: null,
|
user: null,
|
||||||
admins: [],
|
admins: [],
|
||||||
isAuthenticated: false,
|
isAuthenticated: false,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
error: null,
|
error: null,
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//initial state of token set to null
|
||||||
|
token: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const authSlice = createSlice({
|
const authSlice = createSlice({
|
||||||
|
@ -152,6 +202,11 @@ const authSlice = createSlice({
|
||||||
logout: (state) => {
|
logout: (state) => {
|
||||||
state.user = null;
|
state.user = null;
|
||||||
state.isAuthenticated = false;
|
state.isAuthenticated = false;
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Token is removed from local storage and set to null
|
||||||
|
state.token = null;
|
||||||
|
localStorage.removeItem("authToken");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
extraReducers: (builder) => {
|
extraReducers: (builder) => {
|
||||||
|
@ -161,14 +216,12 @@ const authSlice = createSlice({
|
||||||
state.isLoading = true;
|
state.isLoading = true;
|
||||||
state.error = null;
|
state.error = null;
|
||||||
})
|
})
|
||||||
.addCase(
|
.addCase(loginUser.fulfilled, (state, action) => {
|
||||||
loginUser.fulfilled,
|
state.isLoading = false;
|
||||||
(state, action: PayloadAction<User>) => {
|
state.isAuthenticated = true;
|
||||||
state.isLoading = false;
|
state.user = action.payload; // Fix: Extract correct payload
|
||||||
state.isAuthenticated = true;
|
state.token = action.payload.token; // Store token in Redux
|
||||||
state.user = action.payload;
|
})
|
||||||
}
|
|
||||||
)
|
|
||||||
.addCase(
|
.addCase(
|
||||||
loginUser.rejected,
|
loginUser.rejected,
|
||||||
(state, action: PayloadAction<string | undefined>) => {
|
(state, action: PayloadAction<string | undefined>) => {
|
||||||
|
@ -241,8 +294,8 @@ const authSlice = createSlice({
|
||||||
})
|
})
|
||||||
.addCase(updateAdmin.fulfilled, (state, action) => {
|
.addCase(updateAdmin.fulfilled, (state, action) => {
|
||||||
const updatedAdmin = action.payload;
|
const updatedAdmin = action.payload;
|
||||||
state.admins = state.admins.map((admin) =>
|
state.admins = state?.admins?.map((admin) =>
|
||||||
admin.id === updatedAdmin.id ? updatedAdmin : admin
|
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
|
||||||
);
|
);
|
||||||
|
|
||||||
state.isLoading = false;
|
state.isLoading = false;
|
||||||
|
@ -252,6 +305,23 @@ const authSlice = createSlice({
|
||||||
state.error =
|
state.error =
|
||||||
action.payload ||
|
action.payload ||
|
||||||
"Something went wrong while updating Admin!!";
|
"Something went wrong while updating Admin!!";
|
||||||
|
})
|
||||||
|
|
||||||
|
//Eknoor singh
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//Reducers for fetching profiles has been implemented
|
||||||
|
.addCase(fetchAdminProfile.pending, (state) => {
|
||||||
|
state.isLoading = true;
|
||||||
|
state.error = null;
|
||||||
|
})
|
||||||
|
.addCase(fetchAdminProfile.fulfilled, (state, action) => {
|
||||||
|
state.isLoading = false;
|
||||||
|
state.user = action.payload;
|
||||||
|
state.isAuthenticated = true;
|
||||||
|
})
|
||||||
|
.addCase(fetchAdminProfile.rejected, (state, action) => {
|
||||||
|
state.isLoading = false;
|
||||||
|
state.error = action.payload || "Failed to fetch admin profile";
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
146
src/router.tsx
146
src/router.tsx
|
@ -1,74 +1,92 @@
|
||||||
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom"
|
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
|
||||||
// import useAuth from "./hooks/useAuth";
|
import React, { Suspense } from "react";
|
||||||
import React, { Suspense } from "react"
|
import LoadingComponent from "./components/Loading";
|
||||||
import LoadingComponent from "./components/Loading"
|
import DashboardLayout from "./layouts/DashboardLayout";
|
||||||
import DashboardLayout from "./layouts/DashboardLayout"
|
import Login from "./pages/Auth/Login";
|
||||||
import Login from "./pages/Auth/Login"
|
import SignUp from "./pages/Auth/SignUp";
|
||||||
import SignUp from "./pages/Auth/SignUp"
|
import Dashboard from "./pages/Dashboard";
|
||||||
import Dashboard from "./pages/Dashboard"
|
import Vehicles from "./pages/Vehicles";
|
||||||
import Vehicles from "./pages/Vehicles"
|
import AdminList from "./pages/AdminList";
|
||||||
import AdminList from "./pages/AdminList"
|
import ProfilePage from "./pages/ProfilePage";
|
||||||
|
|
||||||
|
import SuperAdminRouter from "./superAdminRouter";
|
||||||
|
|
||||||
function ProtectedRoute({
|
function ProtectedRoute({
|
||||||
caps,
|
caps,
|
||||||
component,
|
component,
|
||||||
}: {
|
}: {
|
||||||
caps: string[]
|
caps: string[];
|
||||||
component: React.ReactNode
|
component: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
if (!localStorage.getItem("authToken"))
|
if (!localStorage.getItem("authToken"))
|
||||||
return <Navigate to={`/auth/login`} replace />
|
return <Navigate to={`/auth/login`} replace />;
|
||||||
|
|
||||||
return component
|
return component;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function AppRouter() {
|
export default function AppRouter() {
|
||||||
return (
|
return (
|
||||||
<Suspense fallback={<LoadingComponent />}>
|
<Suspense fallback={<LoadingComponent />}>
|
||||||
<BaseRoutes>
|
<BaseRoutes>
|
||||||
<Route element={<Navigate to="/auth/login" replace />} index />
|
<Route element={<Navigate to="/auth/login" replace />} index />
|
||||||
|
|
||||||
<Route path="/auth">
|
<Route path="/auth">
|
||||||
<Route
|
<Route
|
||||||
path=""
|
path=""
|
||||||
element={<Navigate to="/auth/login" replace />}
|
element={<Navigate to="/auth/login" replace />}
|
||||||
index
|
index
|
||||||
/>
|
/>
|
||||||
<Route path="login" element={<Login />} />
|
<Route path="login" element={<Login />} />
|
||||||
<Route path="signup" element={<SignUp />} />
|
<Route path="signup" element={<SignUp />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="/panel" element={<DashboardLayout />}>
|
|
||||||
<Route
|
<Route path="/panel" element={<DashboardLayout />}>
|
||||||
path="dashboard"
|
<Route
|
||||||
element={
|
path="dashboard"
|
||||||
<ProtectedRoute
|
element={
|
||||||
caps={[]}
|
<ProtectedRoute
|
||||||
component={<Dashboard />}
|
caps={[]}
|
||||||
/>
|
component={<Dashboard />}
|
||||||
}
|
/>
|
||||||
/>
|
}
|
||||||
<Route
|
/>
|
||||||
path="vehicles"
|
<Route
|
||||||
element={
|
path="vehicles"
|
||||||
<ProtectedRoute
|
element={
|
||||||
caps={[]}
|
<ProtectedRoute
|
||||||
component={<Vehicles />}
|
caps={[]}
|
||||||
/>
|
component={<Vehicles />}
|
||||||
}
|
/>
|
||||||
/>
|
}
|
||||||
<Route
|
/>
|
||||||
path="adminlist"
|
<Route
|
||||||
element={
|
path="adminlist"
|
||||||
<ProtectedRoute
|
element={
|
||||||
caps={[]}
|
<ProtectedRoute
|
||||||
component={<AdminList />}
|
caps={[]}
|
||||||
/>
|
component={
|
||||||
}
|
//Eknoor singh and jaanvi
|
||||||
/>
|
//date:- 12-Feb-2025
|
||||||
<Route path="*" element={<>404</>} />
|
//Admin list put under protected route for specific use
|
||||||
</Route>
|
<SuperAdminRouter>
|
||||||
<Route path="*" element={<>404</>} />
|
<AdminList />
|
||||||
</BaseRoutes>
|
</SuperAdminRouter>
|
||||||
</Suspense>
|
}
|
||||||
)
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Route path="*" element={<>404</>} />
|
||||||
|
</Route>
|
||||||
|
<Route
|
||||||
|
path="/auth/profile"
|
||||||
|
element={
|
||||||
|
<ProtectedRoute caps={[]} component={<ProfilePage />} />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Route path="*" element={<>404</>} />
|
||||||
|
</BaseRoutes>
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
25
src/superAdminRouter.tsx
Normal file
25
src/superAdminRouter.tsx
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
//Eknoor singh and jaanvi
|
||||||
|
//date:- 12-Feb-2025
|
||||||
|
//seperate route for super admin implemented
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
import { useSelector } from "react-redux";
|
||||||
|
import { Navigate } from "react-router-dom";
|
||||||
|
import { RootState } from "./redux/store/store";
|
||||||
|
|
||||||
|
interface SuperAdminRouteProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SuperAdminRouter: React.FC<SuperAdminRouteProps> = ({ children }) => {
|
||||||
|
const userRole = useSelector((state: RootState) => state.auth.user?.role);
|
||||||
|
|
||||||
|
if (userRole !== "superadmin") {
|
||||||
|
// Redirect to dashboard if user is not a superadmin
|
||||||
|
return <Navigate to="/panel/dashboard" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SuperAdminRouter;
|
|
@ -1,23 +1,22 @@
|
||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
"jsx": "react",
|
||||||
"target": "ES2022",
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
"lib": [
|
"target": "ES2022",
|
||||||
"ES2023"
|
"lib": ["ES2023"],
|
||||||
],
|
"module": "ESNext",
|
||||||
"module": "ESNext",
|
"skipLibCheck": true,
|
||||||
"skipLibCheck": true,
|
/* Bundler mode */
|
||||||
/* Bundler mode */
|
"moduleResolution": "bundler",
|
||||||
"moduleResolution": "bundler",
|
"allowImportingTsExtensions": true,
|
||||||
"allowImportingTsExtensions": true,
|
"isolatedModules": true,
|
||||||
"isolatedModules": true,
|
"moduleDetection": "force",
|
||||||
"moduleDetection": "force",
|
"noEmit": true,
|
||||||
"noEmit": true,
|
/* Linting */
|
||||||
/* Linting */
|
"strict": true,
|
||||||
"strict": true,
|
"noUnusedLocals": true,
|
||||||
"noUnusedLocals": true,
|
"noUnusedParameters": true,
|
||||||
"noUnusedParameters": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"noFallthroughCasesInSwitch": true,
|
"noUncheckedSideEffectImports": true
|
||||||
"noUncheckedSideEffectImports": true
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
Loading…
Reference in a new issue