Profile API and User specific window
This commit is contained in:
parent
85dbeb7537
commit
f921de656d
|
@ -10,7 +10,7 @@
|
|||
"@mui/x-charts": "^7.23.2",
|
||||
"@mui/x-data-grid": "^7.23.5",
|
||||
"@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",
|
||||
"@reduxjs/toolkit": "^2.5.0",
|
||||
"AdapterDayjs": "link:@mui/x-date-pickers/AdapterDayjs",
|
||||
|
@ -73,4 +73,4 @@
|
|||
"@types/react-dom": "^19.0.2",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,76 +1,95 @@
|
|||
import List from '@mui/material/List';
|
||||
import ListItem from '@mui/material/ListItem';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
import ListItemIcon from '@mui/material/ListItemIcon';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
|
||||
import AnalyticsRoundedIcon from '@mui/icons-material/AnalyticsRounded';
|
||||
import FormatListBulletedIcon from '@mui/icons-material/FormatListBulleted';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import List from "@mui/material/List";
|
||||
import ListItem from "@mui/material/ListItem";
|
||||
import ListItemButton from "@mui/material/ListItemButton";
|
||||
import ListItemIcon from "@mui/material/ListItemIcon";
|
||||
import ListItemText from "@mui/material/ListItemText";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
|
||||
import AnalyticsRoundedIcon from "@mui/icons-material/AnalyticsRounded";
|
||||
import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import { useSelector } from "react-redux";
|
||||
import { RootState } from "../../redux/store/store";
|
||||
|
||||
const mainListItems = [
|
||||
{
|
||||
text: 'Home',
|
||||
icon: <HomeRoundedIcon />,
|
||||
url: '/panel/dashboard',
|
||||
},
|
||||
{
|
||||
text: 'Vehicles',
|
||||
icon: <AnalyticsRoundedIcon />,
|
||||
url: '/panel/vehicles',
|
||||
},
|
||||
//created by Eknnor and Jaanvi
|
||||
{
|
||||
text: 'Admin List',
|
||||
icon: <FormatListBulletedIcon />,
|
||||
url: '/panel/adminlist',
|
||||
},
|
||||
const baseMenuItems = [
|
||||
{
|
||||
text: "Home",
|
||||
icon: <HomeRoundedIcon />,
|
||||
url: "/panel/dashboard",
|
||||
},
|
||||
{
|
||||
text: "Vehicles",
|
||||
icon: <AnalyticsRoundedIcon />,
|
||||
url: "/panel/vehicles",
|
||||
},
|
||||
//created by Eknnor and Jaanvi
|
||||
];
|
||||
|
||||
//Eknoor singh and Jaanvi
|
||||
//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 = {
|
||||
hidden: boolean;
|
||||
hidden: boolean;
|
||||
};
|
||||
|
||||
export default function MenuContent({ hidden }: PropType) {
|
||||
const location = useLocation();
|
||||
const location = useLocation();
|
||||
const userRole = useSelector((state: RootState) => state.auth.user?.role);
|
||||
|
||||
return (
|
||||
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: 'space-between' }}>
|
||||
<List dense>
|
||||
{mainListItems.map((item, index) => (
|
||||
<ListItem key={index} disablePadding sx={{ display: 'block', py: 1 }}>
|
||||
{/* Wrap ListItemButton with Link to enable routing */}
|
||||
<ListItemButton
|
||||
component={Link}
|
||||
to={item.url}
|
||||
selected={item.url === location.pathname}
|
||||
sx={{ alignItems: 'center', columnGap: 1 }}
|
||||
>
|
||||
<ListItemIcon
|
||||
sx={{
|
||||
minWidth: 'fit-content',
|
||||
'.MuiSvgIcon-root': {
|
||||
fontSize: 24,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{item.icon}
|
||||
</ListItemIcon>
|
||||
<ListItemText
|
||||
sx={{
|
||||
display: !hidden ? 'none' : '',
|
||||
transition: 'all 0.5s ease',
|
||||
'.MuiListItemText-primary': {
|
||||
fontSize: '16px',
|
||||
},
|
||||
}}
|
||||
primary={item.text}
|
||||
/>
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</Stack>
|
||||
);
|
||||
const mainListItems = [
|
||||
...baseMenuItems,
|
||||
...(userRole === "superadmin" ? superAdminOnlyItems : []),
|
||||
];
|
||||
|
||||
return (
|
||||
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
|
||||
<List dense>
|
||||
{mainListItems.map((item, index) => (
|
||||
<ListItem
|
||||
key={index}
|
||||
disablePadding
|
||||
sx={{ display: "block", py: 1 }}
|
||||
>
|
||||
{/* Wrap ListItemButton with Link to enable routing */}
|
||||
<ListItemButton
|
||||
component={Link}
|
||||
to={item.url}
|
||||
selected={item.url === location.pathname}
|
||||
sx={{ alignItems: "center", columnGap: 1 }}
|
||||
>
|
||||
<ListItemIcon
|
||||
sx={{
|
||||
minWidth: "fit-content",
|
||||
".MuiSvgIcon-root": {
|
||||
fontSize: 24,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{item.icon}
|
||||
</ListItemIcon>
|
||||
<ListItemText
|
||||
sx={{
|
||||
display: !hidden ? "none" : "",
|
||||
transition: "all 0.5s ease",
|
||||
".MuiListItemText-primary": {
|
||||
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 MenuButton from "../MenuButton";
|
||||
import { Avatar } from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const MenuItem = styled(MuiMenuItem)({
|
||||
margin: "2px 0",
|
||||
|
@ -20,11 +21,18 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
|
|||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||
const open = Boolean(anchorEl);
|
||||
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
setAnchorEl(event?.currentTarget);
|
||||
};
|
||||
const handleClose = () => {
|
||||
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 (
|
||||
<React.Fragment>
|
||||
<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>
|
||||
<Divider />
|
||||
<MenuItem onClick={handleClose}>Add another account</MenuItem>
|
||||
|
|
|
@ -1,93 +1,111 @@
|
|||
import { styled } from '@mui/material/styles';
|
||||
import Avatar from '@mui/material/Avatar';
|
||||
import MuiDrawer, { drawerClasses } from '@mui/material/Drawer';
|
||||
import Box from '@mui/material/Box';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import MenuContent from '../MenuContent';
|
||||
import OptionsMenu from '../OptionsMenu';
|
||||
import React from 'react';
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from '@mui/x-date-pickers';
|
||||
import { Button } from '@mui/material';
|
||||
import { styled } from "@mui/material/styles";
|
||||
import Avatar from "@mui/material/Avatar";
|
||||
import MuiDrawer, { drawerClasses } from "@mui/material/Drawer";
|
||||
import Box from "@mui/material/Box";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import MenuContent from "../MenuContent";
|
||||
import OptionsMenu from "../OptionsMenu";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import React, { useEffect } from "react";
|
||||
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 Drawer = styled(MuiDrawer)({
|
||||
width: drawerWidth,
|
||||
flexShrink: 0,
|
||||
boxSizing: 'border-box',
|
||||
mt: 10,
|
||||
[`& .${drawerClasses.paper}`]: {
|
||||
width: drawerWidth,
|
||||
boxSizing: 'border-box',
|
||||
},
|
||||
width: drawerWidth,
|
||||
flexShrink: 0,
|
||||
boxSizing: "border-box",
|
||||
mt: 10,
|
||||
[`& .${drawerClasses.paper}`]: {
|
||||
width: drawerWidth,
|
||||
boxSizing: "border-box",
|
||||
},
|
||||
});
|
||||
|
||||
export default function SideMenu() {
|
||||
const [open, setOpen] = React.useState(true);
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
variant="permanent"
|
||||
anchor="left"
|
||||
sx={{
|
||||
display: {
|
||||
xs: 'none',
|
||||
md: 'block',
|
||||
width: open ? 220 : 80,
|
||||
transition: 'all 0.5s ease',
|
||||
},
|
||||
[`& .${drawerClasses.paper}`]: {
|
||||
backgroundColor: 'background.paper',
|
||||
width: open ? 220 : 80,
|
||||
transition: 'all 0.5s ease',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: open ? 'flex-end' : 'center',
|
||||
alignItems: 'center',
|
||||
pt: 1.5,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<Button variant="text" onClick={() => setOpen(!open)}>
|
||||
{open ? <ArrowLeftIcon /> : <ArrowRightIcon />}
|
||||
</Button>
|
||||
</Box>
|
||||
<MenuContent hidden={open} />
|
||||
{/* <CardAlert /> */}
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
p: 2,
|
||||
gap: 1,
|
||||
alignItems: 'center',
|
||||
borderTop: '1px solid',
|
||||
borderColor: 'divider',
|
||||
}}
|
||||
>
|
||||
<Avatar
|
||||
sizes="small"
|
||||
alt="Riley Carter"
|
||||
src="/static/images/avatar/7.jpg"
|
||||
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
|
||||
/>
|
||||
<Box sx={{ mr: 'auto', display: !open ? 'none' : 'block' }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ fontWeight: 500, lineHeight: '16px' }}
|
||||
>
|
||||
Riley Carter
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
|
||||
riley@email.com
|
||||
</Typography>
|
||||
</Box>
|
||||
<OptionsMenu avatar={open} />
|
||||
</Stack>
|
||||
</Drawer>
|
||||
);
|
||||
const [open, setOpen] = React.useState(true);
|
||||
|
||||
//Eknoor singh
|
||||
//date:- 12-Feb-2025
|
||||
//Dispatch is called with user from Authstate Interface
|
||||
|
||||
const dispatch = useDispatch<AppDispatch>();
|
||||
const { user } = useSelector((state: RootState) => state?.auth);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchAdminProfile());
|
||||
}, [dispatch]);
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
variant="permanent"
|
||||
anchor="left"
|
||||
sx={{
|
||||
display: {
|
||||
xs: "none",
|
||||
md: "block",
|
||||
width: open ? 250 : 80,
|
||||
transition: "all 0.5s ease",
|
||||
},
|
||||
[`& .${drawerClasses.paper}`]: {
|
||||
backgroundColor: "background.paper",
|
||||
width: open ? 250 : 80,
|
||||
transition: "all 0.5s ease",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: open ? "flex-end" : "center",
|
||||
alignItems: "center",
|
||||
pt: 1.5,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
<Button variant="text" onClick={() => setOpen(!open)}>
|
||||
{open ? <ArrowLeftIcon /> : <ArrowRightIcon />}
|
||||
</Button>
|
||||
</Box>
|
||||
<MenuContent hidden={open} />
|
||||
{/* <CardAlert /> */}
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
p: 2,
|
||||
gap: 1,
|
||||
alignItems: "center",
|
||||
borderTop: "1px solid",
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
<Avatar
|
||||
sizes="small"
|
||||
alt="Riley Carter"
|
||||
src="/static/images/avatar/7.jpg"
|
||||
sx={{ width: open ? 36 : 0, height: open ? 36 : 0 }}
|
||||
/>
|
||||
<Box sx={{ mr: "auto", display: !open ? "none" : "block" }}>
|
||||
<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;
|
||||
|
||||
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({
|
||||
baseURL: process.env.REACT_APP_BACKEND_URL,
|
||||
baseURL: process.env.REACT_APP_BACKEND_URL,
|
||||
});
|
||||
|
||||
// Axios instance for the local API
|
||||
const apiHttp = axios.create({
|
||||
baseURL: "http://localhost:5000/api",
|
||||
baseURL: "http://localhost:5000/api",
|
||||
});
|
||||
|
||||
|
||||
// Add interceptors to both instances
|
||||
const addAuthInterceptor = (instance: AxiosInstance) => {
|
||||
instance.interceptors.request.use((config) => {
|
||||
const authToken = localStorage.getItem('authToken');
|
||||
if (authToken) {
|
||||
config.headers.Authorization = authToken;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
instance.interceptors.request.use((config) => {
|
||||
const authToken = localStorage.getItem("authToken");
|
||||
if (authToken) {
|
||||
config.headers.Authorization = `Bearer ${authToken}`; // <-- Add "Bearer "
|
||||
}
|
||||
return config;
|
||||
});
|
||||
};
|
||||
|
||||
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 {
|
||||
createSlice,
|
||||
createAsyncThunk,
|
||||
PayloadAction,
|
||||
} from "@reduxjs/toolkit";
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
||||
import axios from "axios";
|
||||
import { backendHttp, apiHttp } from "../../lib/https";
|
||||
import { toast } from "react-toastify";
|
||||
|
||||
// Define types for state
|
||||
//Eknoor singh
|
||||
//date:- 12-Feb-2025
|
||||
//Token for the user has been declared
|
||||
interface User {
|
||||
token: string | null;
|
||||
map(
|
||||
arg0: (
|
||||
admin: { name: any; role: any },
|
||||
admin: { name: any; role: any; email: any; phone: any },
|
||||
index: number
|
||||
) => { srno: number; name: any; role: any }
|
||||
) => { srno: number; name: any; role: any; email: any; phone: any }
|
||||
): unknown;
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
interface Admin {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
admins: Admin[];
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: object | string | null;
|
||||
token: string | null;
|
||||
}
|
||||
|
||||
// Async thunk for login
|
||||
|
@ -39,7 +45,7 @@ export const loginUser = createAsyncThunk<
|
|||
{ rejectValue: string }
|
||||
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await backendHttp.post("admin/login", {
|
||||
const response = await apiHttp.post("auth/login", {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
@ -85,10 +91,16 @@ export const adminList = createAsyncThunk<
|
|||
const response = await apiHttp.get("/auth");
|
||||
console.log(response?.data?.data);
|
||||
return response?.data?.data?.map(
|
||||
(admin: { id: string; name: string; role: string }) => ({
|
||||
id: admin.id,
|
||||
(admin: {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
email: string;
|
||||
}) => ({
|
||||
id: admin?.id,
|
||||
name: admin?.name,
|
||||
role: admin?.role || "N/A",
|
||||
email: admin?.email,
|
||||
})
|
||||
);
|
||||
} catch (error: any) {
|
||||
|
@ -127,8 +139,8 @@ export const updateAdmin = createAsyncThunk(
|
|||
try {
|
||||
const response = await apiHttp.put(`/auth/${id}`, { name, role });
|
||||
toast.success("Admin updated successfully");
|
||||
console.log(response.data);
|
||||
return response.data;
|
||||
console.log(response?.data);
|
||||
return response?.data;
|
||||
} catch (error: any) {
|
||||
return rejectWithValue(
|
||||
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 = {
|
||||
user: null,
|
||||
admins: [],
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
//Eknoor singh
|
||||
//date:- 12-Feb-2025
|
||||
//initial state of token set to null
|
||||
token: null,
|
||||
};
|
||||
|
||||
const authSlice = createSlice({
|
||||
|
@ -152,6 +202,11 @@ const authSlice = createSlice({
|
|||
logout: (state) => {
|
||||
state.user = null;
|
||||
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) => {
|
||||
|
@ -161,14 +216,12 @@ const authSlice = createSlice({
|
|||
state.isLoading = true;
|
||||
state.error = null;
|
||||
})
|
||||
.addCase(
|
||||
loginUser.fulfilled,
|
||||
(state, action: PayloadAction<User>) => {
|
||||
state.isLoading = false;
|
||||
state.isAuthenticated = true;
|
||||
state.user = action.payload;
|
||||
}
|
||||
)
|
||||
.addCase(loginUser.fulfilled, (state, action) => {
|
||||
state.isLoading = false;
|
||||
state.isAuthenticated = true;
|
||||
state.user = action.payload; // Fix: Extract correct payload
|
||||
state.token = action.payload.token; // Store token in Redux
|
||||
})
|
||||
.addCase(
|
||||
loginUser.rejected,
|
||||
(state, action: PayloadAction<string | undefined>) => {
|
||||
|
@ -241,8 +294,8 @@ const authSlice = createSlice({
|
|||
})
|
||||
.addCase(updateAdmin.fulfilled, (state, action) => {
|
||||
const updatedAdmin = action.payload;
|
||||
state.admins = state.admins.map((admin) =>
|
||||
admin.id === updatedAdmin.id ? updatedAdmin : admin
|
||||
state.admins = state?.admins?.map((admin) =>
|
||||
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
|
||||
);
|
||||
|
||||
state.isLoading = false;
|
||||
|
@ -252,6 +305,23 @@ const authSlice = createSlice({
|
|||
state.error =
|
||||
action.payload ||
|
||||
"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 useAuth from "./hooks/useAuth";
|
||||
import React, { Suspense } from "react"
|
||||
import LoadingComponent from "./components/Loading"
|
||||
import DashboardLayout from "./layouts/DashboardLayout"
|
||||
import Login from "./pages/Auth/Login"
|
||||
import SignUp from "./pages/Auth/SignUp"
|
||||
import Dashboard from "./pages/Dashboard"
|
||||
import Vehicles from "./pages/Vehicles"
|
||||
import AdminList from "./pages/AdminList"
|
||||
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
|
||||
import React, { Suspense } from "react";
|
||||
import LoadingComponent from "./components/Loading";
|
||||
import DashboardLayout from "./layouts/DashboardLayout";
|
||||
import Login from "./pages/Auth/Login";
|
||||
import SignUp from "./pages/Auth/SignUp";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
import Vehicles from "./pages/Vehicles";
|
||||
import AdminList from "./pages/AdminList";
|
||||
import ProfilePage from "./pages/ProfilePage";
|
||||
|
||||
import SuperAdminRouter from "./superAdminRouter";
|
||||
|
||||
function ProtectedRoute({
|
||||
caps,
|
||||
component,
|
||||
caps,
|
||||
component,
|
||||
}: {
|
||||
caps: string[]
|
||||
component: React.ReactNode
|
||||
caps: string[];
|
||||
component: React.ReactNode;
|
||||
}) {
|
||||
if (!localStorage.getItem("authToken"))
|
||||
return <Navigate to={`/auth/login`} replace />
|
||||
if (!localStorage.getItem("authToken"))
|
||||
return <Navigate to={`/auth/login`} replace />;
|
||||
|
||||
return component
|
||||
return component;
|
||||
}
|
||||
|
||||
export default function AppRouter() {
|
||||
return (
|
||||
<Suspense fallback={<LoadingComponent />}>
|
||||
<BaseRoutes>
|
||||
<Route element={<Navigate to="/auth/login" replace />} index />
|
||||
return (
|
||||
<Suspense fallback={<LoadingComponent />}>
|
||||
<BaseRoutes>
|
||||
<Route element={<Navigate to="/auth/login" replace />} index />
|
||||
|
||||
<Route path="/auth">
|
||||
<Route
|
||||
path=""
|
||||
element={<Navigate to="/auth/login" replace />}
|
||||
index
|
||||
/>
|
||||
<Route path="login" element={<Login />} />
|
||||
<Route path="signup" element={<SignUp />} />
|
||||
</Route>
|
||||
<Route path="/panel" element={<DashboardLayout />}>
|
||||
<Route
|
||||
path="dashboard"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={<Dashboard />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="vehicles"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={<Vehicles />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="adminlist"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={<AdminList />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<>404</>} />
|
||||
</Route>
|
||||
<Route path="*" element={<>404</>} />
|
||||
</BaseRoutes>
|
||||
</Suspense>
|
||||
)
|
||||
<Route path="/auth">
|
||||
<Route
|
||||
path=""
|
||||
element={<Navigate to="/auth/login" replace />}
|
||||
index
|
||||
/>
|
||||
<Route path="login" element={<Login />} />
|
||||
<Route path="signup" element={<SignUp />} />
|
||||
</Route>
|
||||
|
||||
<Route path="/panel" element={<DashboardLayout />}>
|
||||
<Route
|
||||
path="dashboard"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={<Dashboard />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="vehicles"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={<Vehicles />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="adminlist"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={
|
||||
//Eknoor singh and jaanvi
|
||||
//date:- 12-Feb-2025
|
||||
//Admin list put under protected route for specific use
|
||||
<SuperAdminRouter>
|
||||
<AdminList />
|
||||
</SuperAdminRouter>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<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": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"lib": [
|
||||
"ES2023"
|
||||
],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
}
|
||||
}
|
||||
"compilerOptions": {
|
||||
"jsx": "react",
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue