Merge pull request 'Logout and Signup functionality' (#6) from feature/adminList into develop
Reviewed-on: DigiMantra/digiev_frontend#6
This commit is contained in:
commit
3cbb0e81b7
17215
package-lock.json
generated
17215
package-lock.json
generated
File diff suppressed because it is too large
Load diff
31
package.json
31
package.json
|
@ -6,41 +6,42 @@
|
|||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.0",
|
||||
"@mui/icons-material": "^6.3.0",
|
||||
"@mui/material": "^6.3.0",
|
||||
"@mui/material": "^6.4.4",
|
||||
"@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",
|
||||
"@react-spring/web": "^9.7.5",
|
||||
"@reduxjs/toolkit": "^2.5.0",
|
||||
"AdapterDayjs": "link:@mui/x-date-pickers/AdapterDayjs",
|
||||
"AppBar": "link:@mui/material/AppBar",
|
||||
"Box": "link:@mui/material/Box",
|
||||
"PieChart": "link:@mui/x-charts/PieChart",
|
||||
"RichTreeView": "link:@mui/x-tree-view/RichTreeView",
|
||||
"Stack": "link:@mui/material/Stack",
|
||||
"Tabs": "link:@mui/material/Tabs",
|
||||
"Toolbar": "link:@mui/material/Toolbar",
|
||||
"Typography": "link:@mui/material/Typography",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"AdapterDayjs": "file:@mui/x-date-pickers/AdapterDayjs",
|
||||
"add": "^2.0.6",
|
||||
"AppBar": "file:@mui/material/AppBar",
|
||||
"axios": "^1.7.9",
|
||||
"Box": "file:@mui/material/Box",
|
||||
"clsx": "^2.1.1",
|
||||
"cra-template-typescript": "1.2.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"hooks": "link:@mui/x-charts/hooks",
|
||||
"hooks": "file:@mui/x-charts/hooks",
|
||||
"mui-phone-number": "^3.0.3",
|
||||
"mui-tel-input": "^7.0.0",
|
||||
"PieChart": "file:@mui/x-charts/PieChart",
|
||||
"prop-types": "^15.8.1",
|
||||
"react": "^19.0.0",
|
||||
"react": "^18.0.0",
|
||||
"react-cookie": "^7.2.2",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-dom": "^18.0.0",
|
||||
"react-dropzone": "^14.3.5",
|
||||
"react-hook-form": "^7.54.2",
|
||||
"react-redux": "^9.2.0",
|
||||
"react-router-dom": "^7.1.1",
|
||||
"react-scripts": "5.0.1",
|
||||
"react-toastify": "^11.0.2",
|
||||
"styles": "link:@mui/material/styles",
|
||||
"RichTreeView": "file:@mui/x-tree-view/RichTreeView",
|
||||
"sonner": "^1.7.4",
|
||||
"Stack": "file:@mui/material/Stack",
|
||||
"styles": "file:@mui/material/styles",
|
||||
"Tabs": "file:@mui/material/Tabs",
|
||||
"Toolbar": "file:@mui/material/Toolbar",
|
||||
"Typography": "file:@mui/material/Typography",
|
||||
"web-vitals": "^4.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
|
|
20709
pnpm-lock.yaml
20709
pnpm-lock.yaml
File diff suppressed because it is too large
Load diff
|
@ -74,27 +74,6 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
|
|||
>
|
||||
<DialogTitle>{editRow ? "Edit" : "Add"} Category</DialogTitle>
|
||||
<DialogContent>
|
||||
<Controller
|
||||
name="category"
|
||||
control={control}
|
||||
rules={{
|
||||
required: "Category Name is required",
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
autoFocus
|
||||
required
|
||||
margin="dense"
|
||||
label="Add Category Name"
|
||||
type="text"
|
||||
fullWidth
|
||||
variant="standard"
|
||||
error={!!errors.category}
|
||||
helperText={errors.category?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="name"
|
||||
control={control}
|
||||
|
@ -120,19 +99,17 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
|
|||
<Controller
|
||||
name="role"
|
||||
control={control}
|
||||
rules={{
|
||||
required: "Role is required",
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
margin="dense"
|
||||
label="Role"
|
||||
type="text"
|
||||
|
||||
fullWidth
|
||||
variant="standard"
|
||||
error={!!errors.role}
|
||||
helperText={errors.role?.message}
|
||||
disabled
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
|
|
@ -7,7 +7,7 @@ import TableContainer from "@mui/material/TableContainer"
|
|||
import TableHead from "@mui/material/TableHead"
|
||||
import TableRow from "@mui/material/TableRow"
|
||||
import Paper, { paperClasses } from "@mui/material/Paper"
|
||||
import { deleteAdmin } from "../../redux/slices/authSlice"
|
||||
import { deleteAdmin } from "../../redux/slices/adminSlice"
|
||||
import { useDispatch } from "react-redux"
|
||||
import {
|
||||
Box,
|
||||
|
|
|
@ -43,7 +43,9 @@ type PropType = {
|
|||
|
||||
export default function MenuContent({ hidden }: PropType) {
|
||||
const location = useLocation();
|
||||
const userRole = useSelector((state: RootState) => state.auth.user?.role);
|
||||
const userRole = useSelector(
|
||||
(state: RootState) => state.profileReducer.user?.role
|
||||
);
|
||||
|
||||
const mainListItems = [
|
||||
...baseMenuItems,
|
||||
|
|
|
@ -12,6 +12,7 @@ import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
|
|||
import MenuButton from "../MenuButton";
|
||||
import { Avatar } from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const MenuItem = styled(MuiMenuItem)({
|
||||
margin: "2px 0",
|
||||
|
@ -33,6 +34,15 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
|
|||
const handleProfile = () => {
|
||||
navigate("/auth/profile");
|
||||
};
|
||||
|
||||
//Eknoor singh and jaanvi
|
||||
//date:- 13-Feb-2025
|
||||
//Implemented logout functionality which was static previously
|
||||
const handlelogout = () => {
|
||||
localStorage.clear();
|
||||
navigate("/auth/login");
|
||||
toast.success("Logged out successfully");
|
||||
};
|
||||
return (
|
||||
<React.Fragment>
|
||||
<MenuButton
|
||||
|
@ -86,7 +96,15 @@ export default function OptionsMenu({ avatar }: { avatar?: boolean }) {
|
|||
},
|
||||
}}
|
||||
>
|
||||
<ListItemText>Logout</ListItemText>
|
||||
{/* //Eknoor singh and jaanvi
|
||||
//date:- 13-Feb-2025
|
||||
//Implemented logout functionality which was static previously */}
|
||||
<ListItemText
|
||||
className="toast-button"
|
||||
onClick={handlelogout}
|
||||
>
|
||||
Logout
|
||||
</ListItemText>
|
||||
<ListItemIcon>
|
||||
<LogoutRoundedIcon fontSize="small" />
|
||||
</ListItemIcon>
|
||||
|
|
|
@ -11,7 +11,7 @@ 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";
|
||||
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
|
||||
|
||||
const drawerWidth = 240;
|
||||
|
||||
|
@ -34,7 +34,7 @@ export default function SideMenu() {
|
|||
//Dispatch is called with user from Authstate Interface
|
||||
|
||||
const dispatch = useDispatch<AppDispatch>();
|
||||
const { user } = useSelector((state: RootState) => state?.auth);
|
||||
const { user } = useSelector((state: RootState) => state?.profileReducer);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetchAdminProfile());
|
||||
|
|
|
@ -1,26 +1,25 @@
|
|||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './index.css';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
import App from './App';
|
||||
import { Provider } from 'react-redux';
|
||||
import store from './redux/store/store.ts';
|
||||
import { Slide, ToastContainer } from 'react-toastify';
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import "./index.css";
|
||||
import reportWebVitals from "./reportWebVitals";
|
||||
import App from "./App";
|
||||
import { Provider } from "react-redux";
|
||||
import store from "./redux/store/store.ts";
|
||||
import { Toaster } from "sonner";
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
const root = ReactDOM.createRoot(document.getElementById("root")!);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Provider store={store}>
|
||||
<App />
|
||||
<ToastContainer
|
||||
autoClose={2000}
|
||||
hideProgressBar
|
||||
theme="dark"
|
||||
transition={Slide}
|
||||
toastStyle={{ border: '1px solid dimgray' }}
|
||||
/>
|
||||
</Provider>
|
||||
</React.StrictMode>
|
||||
<React.StrictMode>
|
||||
<Provider store={store}>
|
||||
<App />
|
||||
<Toaster
|
||||
position="top-right"
|
||||
richColors
|
||||
closeButton
|
||||
duration={6000}
|
||||
/>
|
||||
</Provider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
|
|
|
@ -6,7 +6,7 @@ const http = axios.create({
|
|||
http.interceptors.request.use((config) => {
|
||||
const authToken = localStorage.getItem("authToken");
|
||||
if (authToken) {
|
||||
config.headers.Authorization = authToken;
|
||||
config.headers.Authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
|
||||
return config;
|
||||
|
|
|
@ -4,7 +4,7 @@ import AddEditCategoryModal from "../../components/AddEditCategoryModal";
|
|||
import { useForm } from "react-hook-form";
|
||||
import CustomTable, { Column } from "../../components/CustomTable";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { adminList, updateAdmin } from "../../redux/slices/authSlice";
|
||||
import { adminList, updateAdmin } from "../../redux/slices/adminSlice";
|
||||
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector
|
||||
|
||||
export default function AdminList() {
|
||||
|
@ -17,7 +17,7 @@ export default function AdminList() {
|
|||
const dispatch = useDispatch<AppDispatch>();
|
||||
|
||||
// Fetching admin data from the Redux store
|
||||
const admins = useSelector((state: RootState) => state.auth.admins);
|
||||
const admins = useSelector((state: RootState) => state.adminReducer.admins);
|
||||
|
||||
// Dispatching the API call when the component mounts
|
||||
useEffect(() => {
|
||||
|
|
|
@ -1,228 +1,247 @@
|
|||
import * as React from 'react';
|
||||
import Box from '@mui/material/Box';
|
||||
import Button from '@mui/material/Button';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import CssBaseline from '@mui/material/CssBaseline';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import Divider from '@mui/material/Divider';
|
||||
import FormLabel from '@mui/material/FormLabel';
|
||||
import FormControl from '@mui/material/FormControl';
|
||||
import Link from '@mui/material/Link';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import MuiCard from '@mui/material/Card';
|
||||
import { styled } from '@mui/material/styles';
|
||||
import { useForm, Controller, SubmitHandler } from 'react-hook-form';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { loginUser } from '../../../redux/slices/authSlice.ts';
|
||||
import ColorModeSelect from '../../../shared-theme/ColorModeSelect.tsx';
|
||||
import AppTheme from '../../../shared-theme/AppTheme.tsx';
|
||||
import ForgotPassword from './ForgotPassword.tsx';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import * as React from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Checkbox from "@mui/material/Checkbox";
|
||||
import CssBaseline from "@mui/material/CssBaseline";
|
||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||
import Divider from "@mui/material/Divider";
|
||||
import FormLabel from "@mui/material/FormLabel";
|
||||
import FormControl from "@mui/material/FormControl";
|
||||
import Link from "@mui/material/Link";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import MuiCard from "@mui/material/Card";
|
||||
import { styled } from "@mui/material/styles";
|
||||
import { useForm, Controller, SubmitHandler } from "react-hook-form";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { loginUser } from "../../../redux/slices/authSlice.ts";
|
||||
import ColorModeSelect from "../../../shared-theme/ColorModeSelect.tsx";
|
||||
import AppTheme from "../../../shared-theme/AppTheme.tsx";
|
||||
import ForgotPassword from "./ForgotPassword.tsx";
|
||||
import { toast } from "sonner";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const Card = styled(MuiCard)(({ theme }) => ({
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
padding: theme.spacing(4),
|
||||
gap: theme.spacing(2),
|
||||
margin: 'auto',
|
||||
[theme.breakpoints.up('sm')]: {
|
||||
maxWidth: '450px',
|
||||
},
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px',
|
||||
...theme.applyStyles('dark', {
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px',
|
||||
}),
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignSelf: "center",
|
||||
width: "100%",
|
||||
padding: theme.spacing(4),
|
||||
gap: theme.spacing(2),
|
||||
margin: "auto",
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
maxWidth: "450px",
|
||||
},
|
||||
boxShadow:
|
||||
"hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
|
||||
...theme.applyStyles("dark", {
|
||||
boxShadow:
|
||||
"hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
|
||||
}),
|
||||
}));
|
||||
|
||||
const SignInContainer = styled(Stack)(({ theme }) => ({
|
||||
height: 'calc((1 - var(--template-frame-height, 0)) * 100dvh)',
|
||||
minHeight: '100%',
|
||||
padding: theme.spacing(2),
|
||||
[theme.breakpoints.up('sm')]: {
|
||||
padding: theme.spacing(4),
|
||||
},
|
||||
'&::before': {
|
||||
content: '""',
|
||||
display: 'block',
|
||||
position: 'absolute',
|
||||
zIndex: -1,
|
||||
inset: 0,
|
||||
backgroundImage:
|
||||
'radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundImage:
|
||||
'radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))',
|
||||
}),
|
||||
},
|
||||
height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
|
||||
minHeight: "100%",
|
||||
padding: theme.spacing(2),
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
padding: theme.spacing(4),
|
||||
},
|
||||
"&::before": {
|
||||
content: '""',
|
||||
display: "block",
|
||||
position: "absolute",
|
||||
zIndex: -1,
|
||||
inset: 0,
|
||||
backgroundImage:
|
||||
"radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
|
||||
backgroundRepeat: "no-repeat",
|
||||
...theme.applyStyles("dark", {
|
||||
backgroundImage:
|
||||
"radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
|
||||
}),
|
||||
},
|
||||
}));
|
||||
interface ILoginForm {
|
||||
email: string;
|
||||
password: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
export default function Login(props: { disableCustomTheme?: boolean }) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
setError,
|
||||
} = useForm<ILoginForm>();
|
||||
const dispatch = useDispatch();
|
||||
const router = useNavigate();
|
||||
const handleClickOpen = () => {
|
||||
setOpen(true);
|
||||
};
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
setError,
|
||||
} = useForm<ILoginForm>();
|
||||
const dispatch = useDispatch();
|
||||
const router = useNavigate();
|
||||
const handleClickOpen = () => {
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => {
|
||||
try {
|
||||
const response = await dispatch(loginUser(data)).unwrap();
|
||||
if (response?.data?.token) {
|
||||
router('/panel/dashboard');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log('Login failed:', error);
|
||||
toast.error('Login failed: ' + error);
|
||||
}
|
||||
};
|
||||
const onSubmit: SubmitHandler<ILoginForm> = async (data: ILoginForm) => {
|
||||
try {
|
||||
const response = await dispatch(loginUser(data)).unwrap();
|
||||
if (response?.data?.token) {
|
||||
router("/panel/dashboard");
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log("Login failed:", error);
|
||||
toast.error("Login failed: " + error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AppTheme {...props}>
|
||||
<CssBaseline enableColorScheme />
|
||||
<SignInContainer direction="column" justifyContent="space-between">
|
||||
<ColorModeSelect
|
||||
sx={{ position: 'fixed', top: '1rem', right: '1rem' }}
|
||||
/>
|
||||
<Card variant="outlined">
|
||||
{/* <SitemarkIcon /> */}
|
||||
Digi-EV
|
||||
<Typography
|
||||
component="h1"
|
||||
variant="h4"
|
||||
sx={{ width: '100%', fontSize: 'clamp(2rem, 10vw, 2.15rem)' }}
|
||||
>
|
||||
Sign in
|
||||
</Typography>
|
||||
<Box
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
noValidate
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
width: '100%',
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="email">Email</FormLabel>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
defaultValue=""
|
||||
rules={{
|
||||
required: 'Email is required',
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message: 'Please enter a valid email address.',
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
error={!!errors.email}
|
||||
helperText={errors.email?.message}
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="your@email.com"
|
||||
autoComplete="email"
|
||||
autoFocus
|
||||
required
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
color={errors.email ? 'error' : 'primary'}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
return (
|
||||
<AppTheme {...props}>
|
||||
<CssBaseline enableColorScheme />
|
||||
<SignInContainer direction="column" justifyContent="space-between">
|
||||
<ColorModeSelect
|
||||
sx={{ position: "fixed", top: "1rem", right: "1rem" }}
|
||||
/>
|
||||
<Card variant="outlined">
|
||||
{/* <SitemarkIcon /> */}
|
||||
Digi-EV
|
||||
<Typography
|
||||
component="h1"
|
||||
variant="h4"
|
||||
sx={{
|
||||
width: "100%",
|
||||
fontSize: "clamp(2rem, 10vw, 2.15rem)",
|
||||
}}
|
||||
>
|
||||
Sign in
|
||||
</Typography>
|
||||
<Box
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
noValidate
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
width: "100%",
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="email">Email</FormLabel>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
defaultValue=""
|
||||
rules={{
|
||||
required: "Email is required",
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message:
|
||||
"Please enter a valid email address.",
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
error={!!errors.email}
|
||||
helperText={errors.email?.message}
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="your@email.com"
|
||||
autoComplete="email"
|
||||
autoFocus
|
||||
required
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
color={
|
||||
errors.email ? "error" : "primary"
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="password">Password</FormLabel>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
defaultValue=""
|
||||
rules={{
|
||||
required: 'Password is required',
|
||||
minLength: {
|
||||
value: 6,
|
||||
message: 'Password must be at least 6 characters long.',
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
error={!!errors.password}
|
||||
helperText={errors.password?.message}
|
||||
name="password"
|
||||
placeholder="••••••"
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
autoFocus
|
||||
required
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
color={errors.password ? 'error' : 'primary'}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="password">Password</FormLabel>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
defaultValue=""
|
||||
rules={{
|
||||
required: "Password is required",
|
||||
minLength: {
|
||||
value: 6,
|
||||
message:
|
||||
"Password must be at least 6 characters long.",
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
error={!!errors.password}
|
||||
helperText={errors.password?.message}
|
||||
name="password"
|
||||
placeholder="••••••"
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
autoFocus
|
||||
required
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
color={
|
||||
errors.password
|
||||
? "error"
|
||||
: "primary"
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormControlLabel
|
||||
control={<Checkbox value="remember" color="primary" />}
|
||||
label="Remember me"
|
||||
/>
|
||||
<ForgotPassword open={open} handleClose={handleClose} />
|
||||
<Button type="submit" fullWidth variant="contained">
|
||||
Sign in
|
||||
</Button>
|
||||
<Link
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={handleClickOpen}
|
||||
variant="body2"
|
||||
sx={{ alignSelf: 'center' }}
|
||||
>
|
||||
Forgot your password?
|
||||
</Link>
|
||||
</Box>
|
||||
<Divider>or</Divider>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<Typography sx={{ textAlign: 'center' }}>
|
||||
Don't have an account?{' '}
|
||||
<Link
|
||||
href="/auth/signup"
|
||||
variant="body2"
|
||||
sx={{ alignSelf: 'center' }}
|
||||
>
|
||||
Sign up
|
||||
</Link>
|
||||
</Typography>
|
||||
</Box>
|
||||
</Card>
|
||||
</SignInContainer>
|
||||
</AppTheme>
|
||||
);
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox value="remember" color="primary" />
|
||||
}
|
||||
label="Remember me"
|
||||
/>
|
||||
<ForgotPassword open={open} handleClose={handleClose} />
|
||||
<Button type="submit" fullWidth variant="contained">
|
||||
Sign in
|
||||
</Button>
|
||||
<Link
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={handleClickOpen}
|
||||
variant="body2"
|
||||
sx={{ alignSelf: "center" }}
|
||||
>
|
||||
Forgot your password?
|
||||
</Link>
|
||||
</Box>
|
||||
<Divider>or</Divider>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ textAlign: "center" }}>
|
||||
Don't have an account?{" "}
|
||||
<Link
|
||||
href="/auth/signup"
|
||||
variant="body2"
|
||||
sx={{ alignSelf: "center" }}
|
||||
>
|
||||
Sign up
|
||||
</Link>
|
||||
</Typography>
|
||||
</Box>
|
||||
</Card>
|
||||
</SignInContainer>
|
||||
</AppTheme>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,215 +1,294 @@
|
|||
import * as React from 'react';
|
||||
import { useForm, Controller, SubmitHandler } from 'react-hook-form';
|
||||
import Box from '@mui/material/Box';
|
||||
import Button from '@mui/material/Button';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import CssBaseline from '@mui/material/CssBaseline';
|
||||
import Divider from '@mui/material/Divider';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import FormLabel from '@mui/material/FormLabel';
|
||||
import FormControl from '@mui/material/FormControl';
|
||||
import Link from '@mui/material/Link';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import MuiCard from '@mui/material/Card';
|
||||
import { styled } from '@mui/material/styles';
|
||||
import AppTheme from '../../../shared-theme/AppTheme.tsx';
|
||||
import { GoogleIcon, FacebookIcon, SitemarkIcon } from './CustomIcons.tsx';
|
||||
import ColorModeSelect from '../../../shared-theme/ColorModeSelect.tsx';
|
||||
import MuiPhoneNumber from 'mui-phone-number';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { registerUser } from '../../../redux/slices/authSlice.ts';
|
||||
import { toast } from "react-toastify";
|
||||
import * as React from "react";
|
||||
import { useForm, Controller, SubmitHandler } from "react-hook-form";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
// import Checkbox from '@mui/material/Checkbox';
|
||||
// import CssBaseline from '@mui/material/CssBaseline';
|
||||
import Divider from "@mui/material/Divider";
|
||||
// import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import FormLabel from "@mui/material/FormLabel";
|
||||
import FormControl from "@mui/material/FormControl";
|
||||
import Link from "@mui/material/Link";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import MuiCard from "@mui/material/Card";
|
||||
import { styled } from "@mui/material/styles";
|
||||
import AppTheme from "../../../shared-theme/AppTheme.tsx";
|
||||
// import { GoogleIcon, FacebookIcon, SitemarkIcon } from './CustomIcons.tsx';
|
||||
import ColorModeSelect from "../../../shared-theme/ColorModeSelect.tsx";
|
||||
import MuiPhoneNumber from "mui-phone-number";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { registerUser } from "../../../redux/slices/authSlice.ts";
|
||||
import { toast } from "sonner";
|
||||
import { InputLabel, MenuItem, Select } from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const Card = styled(MuiCard)(({ theme }) => ({
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
padding: theme.spacing(4),
|
||||
gap: theme.spacing(2),
|
||||
margin: 'auto',
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px',
|
||||
[theme.breakpoints.up('sm')]: {
|
||||
width: '450px',
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px',
|
||||
}),
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignSelf: "center",
|
||||
width: "100%",
|
||||
padding: theme.spacing(4),
|
||||
gap: theme.spacing(2),
|
||||
margin: "auto",
|
||||
boxShadow:
|
||||
"hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
width: "450px",
|
||||
},
|
||||
...theme.applyStyles("dark", {
|
||||
boxShadow:
|
||||
"hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
|
||||
}),
|
||||
}));
|
||||
|
||||
const SignUpContainer = styled(Stack)(({ theme }) => ({
|
||||
height: 'calc((1 - var(--template-frame-height, 0)) * 100dvh)',
|
||||
minHeight: '100%',
|
||||
padding: theme.spacing(2),
|
||||
[theme.breakpoints.up('sm')]: {
|
||||
padding: theme.spacing(4),
|
||||
},
|
||||
'&::before': {
|
||||
content: '""',
|
||||
display: 'block',
|
||||
position: 'absolute',
|
||||
zIndex: -1,
|
||||
inset: 0,
|
||||
backgroundImage:
|
||||
'radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundImage:
|
||||
'radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))',
|
||||
}),
|
||||
},
|
||||
height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
|
||||
minHeight: "100%",
|
||||
padding: theme.spacing(2),
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
padding: theme.spacing(4),
|
||||
},
|
||||
"&::before": {
|
||||
content: '""',
|
||||
display: "block",
|
||||
position: "absolute",
|
||||
zIndex: -1,
|
||||
inset: 0,
|
||||
backgroundImage:
|
||||
"radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
|
||||
backgroundRepeat: "no-repeat",
|
||||
...theme.applyStyles("dark", {
|
||||
backgroundImage:
|
||||
"radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
|
||||
}),
|
||||
},
|
||||
}));
|
||||
interface IRegisterForm {
|
||||
name:string;
|
||||
email: string;
|
||||
password: string;
|
||||
phoneCountryCode:string;
|
||||
phoneNumber:number | null;
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
phone: string; // Changed to string to handle formatted phone numbers
|
||||
role: string;
|
||||
}
|
||||
|
||||
//Eknoor singh and jaanvi
|
||||
//date:- 13-Feb-2025
|
||||
//Implemented SignUp functionality which was static initially
|
||||
export default function SignUp(props: { disableCustomTheme?: boolean }) {
|
||||
const dispatch = useDispatch();
|
||||
const { control, handleSubmit, formState: { errors }, setValue } = useForm<IRegisterForm>({
|
||||
defaultValues: {
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
phoneCountryCode: '',
|
||||
phoneNumber: null,
|
||||
}
|
||||
});
|
||||
const [countryCode, setCountryCode] = React.useState('');
|
||||
const [phoneNumber, setPhoneNumber] = React.useState('');
|
||||
const dispatch = useDispatch();
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
setValue,
|
||||
} = useForm<IRegisterForm>({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
email: "",
|
||||
password: "",
|
||||
role: "",
|
||||
phone: "",
|
||||
},
|
||||
});
|
||||
|
||||
const extractCountryCodeAndNumber = (phone: string) => {
|
||||
// Match the country code (e.g., +91) and the rest of the number
|
||||
const match = phone.match(/^(\+\d{1,3})\s*(\d+.*)/);
|
||||
if (match) {
|
||||
return { countryCode: match[1], numberWithoutCountryCode: match[2] };
|
||||
}
|
||||
return { countryCode: '', numberWithoutCountryCode: phone };
|
||||
};
|
||||
const handleOnChange = (newPhone: string) => {
|
||||
const { countryCode, numberWithoutCountryCode } = extractCountryCodeAndNumber(newPhone);
|
||||
console.log("numberWithoutCountryCode",numberWithoutCountryCode);
|
||||
setPhoneNumber(numberWithoutCountryCode)
|
||||
setCountryCode(countryCode);
|
||||
};
|
||||
const navigate = useNavigate();
|
||||
const [phone, setPhone] = React.useState("");
|
||||
|
||||
const onSubmit : SubmitHandler<IRegisterForm>= async (data: any) => {
|
||||
const payload = {
|
||||
name: data.name,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
phoneCountryCode: countryCode,
|
||||
phoneNumber: phoneNumber,
|
||||
};
|
||||
try {
|
||||
await dispatch(registerUser(payload)).unwrap();
|
||||
} catch (error) {
|
||||
toast(error)
|
||||
console.log("error",error)
|
||||
}
|
||||
};
|
||||
const roleOptions = [
|
||||
{ value: "admin", label: "Admin" },
|
||||
{ value: "user", label: "User" },
|
||||
];
|
||||
// Enhanced email validation regex
|
||||
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
|
||||
|
||||
return (
|
||||
<AppTheme {...props}>
|
||||
{/* <CssBaseline enableColorScheme /> */}
|
||||
<ColorModeSelect sx={{ position: 'fixed', top: '1rem', right: '1rem' }} />/
|
||||
<SignUpContainer direction="column" justifyContent="space-between">
|
||||
<Card variant="outlined">
|
||||
Digi-EV
|
||||
<Typography
|
||||
component="h1"
|
||||
variant="h4"
|
||||
sx={{ width: '100%', fontSize: 'clamp(2rem, 10vw, 2.15rem)' }}
|
||||
>
|
||||
Sign up
|
||||
</Typography>
|
||||
<Box
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}
|
||||
>
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="name">Full name</FormLabel>
|
||||
<Controller
|
||||
name="name"
|
||||
control={control}
|
||||
rules={{ required: 'Name is required' }}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
id="name"
|
||||
fullWidth
|
||||
placeholder="Jon Snow"
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
const handlePhoneChange = (value: string) => {
|
||||
// Remove all non-numeric characters except + for country code
|
||||
const cleanedNumber = value.replace(/[^\d+]/g, "");
|
||||
setValue("phone", cleanedNumber);
|
||||
};
|
||||
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="email">Email</FormLabel>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Email is required',
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message: 'Please enter a valid email address.'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
id="email"
|
||||
fullWidth
|
||||
placeholder="your@email.com"
|
||||
error={!!errors.email}
|
||||
helperText={errors.email?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
const onSubmit: SubmitHandler<IRegisterForm> = async (data) => {
|
||||
try {
|
||||
// Validate email
|
||||
if (!emailRegex.test(data.email)) {
|
||||
toast.error("Please enter a valid email address");
|
||||
return;
|
||||
}
|
||||
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="password">Password</FormLabel>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Password is required',
|
||||
minLength: {
|
||||
value: 6,
|
||||
message: 'Password must be at least 6 characters long'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
id="password"
|
||||
fullWidth
|
||||
type="password"
|
||||
placeholder="••••••"
|
||||
error={!!errors.password}
|
||||
helperText={errors.password?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
<MuiPhoneNumber
|
||||
defaultCountry='in'
|
||||
onChange={handleOnChange}
|
||||
value={phoneNumber}
|
||||
/>
|
||||
// Validate phone number
|
||||
if (!data.phone || data.phone.length < 10) {
|
||||
toast.error("Please enter a valid phone number");
|
||||
return;
|
||||
}
|
||||
|
||||
{/* <FormControlLabel
|
||||
// Validate phone number
|
||||
const payload = {
|
||||
name: data.name.trim(),
|
||||
email: data.email.toLowerCase().trim(),
|
||||
password: data.password,
|
||||
phone: data.phone,
|
||||
role: data.role,
|
||||
};
|
||||
|
||||
await dispatch(registerUser(payload)).unwrap();
|
||||
navigate("/auth/login");
|
||||
toast.success("Registration successful!");
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || "Registration failed");
|
||||
console.error("Registration error:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AppTheme {...props}>
|
||||
{/* <CssBaseline enableColorScheme /> */}
|
||||
<ColorModeSelect
|
||||
sx={{ position: "fixed", top: "1rem", right: "1rem" }}
|
||||
/>
|
||||
<SignUpContainer direction="column" justifyContent="space-between">
|
||||
<Card variant="outlined">
|
||||
Digi-EV
|
||||
<Typography
|
||||
component="h1"
|
||||
variant="h4"
|
||||
sx={{
|
||||
width: "100%",
|
||||
fontSize: "clamp(2rem, 10vw, 2.15rem)",
|
||||
}}
|
||||
>
|
||||
Sign up
|
||||
</Typography>
|
||||
<Box
|
||||
component="form"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="name">Full name</FormLabel>
|
||||
<Controller
|
||||
name="name"
|
||||
control={control}
|
||||
rules={{ required: "Name is required" }}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
id="name"
|
||||
fullWidth
|
||||
placeholder="Jon Snow"
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="email">Email</FormLabel>
|
||||
<Controller
|
||||
name="email"
|
||||
control={control}
|
||||
rules={{
|
||||
required: "Email is required",
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message:
|
||||
"Please enter a valid email address.",
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
id="email"
|
||||
fullWidth
|
||||
placeholder="your@email.com"
|
||||
error={!!errors.email}
|
||||
helperText={errors.email?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="password">Password</FormLabel>
|
||||
<Controller
|
||||
name="password"
|
||||
control={control}
|
||||
rules={{
|
||||
required: "Password is required",
|
||||
minLength: {
|
||||
value: 6,
|
||||
message:
|
||||
"Password must be at least 6 characters long",
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextField
|
||||
{...field}
|
||||
id="password"
|
||||
fullWidth
|
||||
type="password"
|
||||
placeholder="••••••"
|
||||
error={!!errors.password}
|
||||
helperText={errors.password?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel htmlFor="phone">Phone Number</FormLabel>
|
||||
<MuiPhoneNumber
|
||||
defaultCountry="in"
|
||||
onChange={handlePhoneChange}
|
||||
value={control._formValues.phone}
|
||||
required
|
||||
error={!!errors.phone}
|
||||
helperText={errors.phone?.message}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<FormControl fullWidth>
|
||||
<InputLabel id="role-select-label">Role</InputLabel>
|
||||
<Controller
|
||||
name="role"
|
||||
control={control}
|
||||
rules={{ required: "Role is required" }}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
labelId="role-select-label"
|
||||
id="role-select"
|
||||
value={field.value}
|
||||
onChange={(e) =>
|
||||
setValue("role", e.target.value)
|
||||
}
|
||||
error={!!errors.role}
|
||||
>
|
||||
{roleOptions.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
>
|
||||
{option.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
{errors.role && (
|
||||
<Typography color="error" variant="caption">
|
||||
{errors.role.message}
|
||||
</Typography>
|
||||
)}
|
||||
</FormControl>
|
||||
|
||||
{/* <FormControlLabel
|
||||
control={
|
||||
<Controller
|
||||
name="allowExtraEmails"
|
||||
|
@ -222,14 +301,14 @@ const dispatch = useDispatch();
|
|||
label="I want to receive updates via email."
|
||||
/> */}
|
||||
|
||||
<Button type="submit" fullWidth variant="contained">
|
||||
Sign up
|
||||
</Button>
|
||||
</Box>
|
||||
{/* <Divider>
|
||||
<Button type="submit" fullWidth variant="contained">
|
||||
Sign up
|
||||
</Button>
|
||||
</Box>
|
||||
{/* <Divider>
|
||||
<Typography sx={{ color: 'text.secondary' }}>or</Typography>
|
||||
</Divider> */}
|
||||
{/* <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{/* <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<Button
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
|
@ -257,21 +336,27 @@ const dispatch = useDispatch();
|
|||
</Link>
|
||||
</Typography>
|
||||
</Box> */}
|
||||
<Divider>or</Divider>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<Typography sx={{ textAlign: 'center' }}>
|
||||
Already have an account?
|
||||
<Link
|
||||
href="/auth/login"
|
||||
variant="body2"
|
||||
sx={{ alignSelf: 'center' }}
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</Typography>
|
||||
</Box>
|
||||
</Card>
|
||||
</SignUpContainer>
|
||||
</AppTheme>
|
||||
);
|
||||
<Divider>or</Divider>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ textAlign: "center" }}>
|
||||
Already have an account?
|
||||
<Link
|
||||
href="/auth/login"
|
||||
variant="body2"
|
||||
sx={{ alignSelf: "center" }}
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</Typography>
|
||||
</Box>
|
||||
</Card>
|
||||
</SignUpContainer>
|
||||
</AppTheme>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -16,15 +16,15 @@ import {
|
|||
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { AppDispatch, RootState } from "../../redux/store/store";
|
||||
import { fetchAdminProfile } from "../../redux/slices/authSlice";
|
||||
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
|
||||
|
||||
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
|
||||
const { user, isLoading } = useSelector(
|
||||
(state: RootState) => state?.profileReducer
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -46,20 +46,6 @@ const ProfilePage = () => {
|
|||
);
|
||||
}
|
||||
|
||||
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>
|
||||
|
|
|
@ -1,9 +1,13 @@
|
|||
import { combineReducers } from "@reduxjs/toolkit";
|
||||
|
||||
import authReducer from "./slices/authSlice";
|
||||
import adminReducer from "./slices/adminSlice";
|
||||
import profileReducer from "./slices/profileSlice";
|
||||
|
||||
const rootReducer = combineReducers({
|
||||
authReducer,
|
||||
adminReducer,
|
||||
profileReducer
|
||||
});
|
||||
|
||||
export type RootState = ReturnType<typeof rootReducer>;
|
||||
|
|
154
src/redux/slices/adminSlice.ts
Normal file
154
src/redux/slices/adminSlice.ts
Normal file
|
@ -0,0 +1,154 @@
|
|||
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
||||
import http from "../../lib/https";
|
||||
import { toast } from "sonner";
|
||||
|
||||
// Interfaces
|
||||
interface User {
|
||||
token: string | null;
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
interface Admin {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
admins: Admin[];
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
// error: string | null;
|
||||
token: string | null;
|
||||
}
|
||||
|
||||
// Fetch Admin List
|
||||
export const adminList = createAsyncThunk<
|
||||
Admin[],
|
||||
void,
|
||||
{ rejectValue: string }
|
||||
>("FetchAdminList", async (_, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await http.get("auth/admin-list");
|
||||
return response?.data?.data;
|
||||
} catch (error: any) {
|
||||
toast.error("Error fetching users list" + error);
|
||||
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Delete Admin
|
||||
export const deleteAdmin = createAsyncThunk<
|
||||
string,
|
||||
string,
|
||||
{ rejectValue: string }
|
||||
>("deleteAdmin", async (id, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await http.delete(`auth/${id}/delete-admin`);
|
||||
toast.success(response.data?.message);
|
||||
return id;
|
||||
} catch (error: any) {
|
||||
toast.error("Error deleting the user" + error);
|
||||
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Update Admin
|
||||
export const updateAdmin = createAsyncThunk(
|
||||
"updateAdmin",
|
||||
async (
|
||||
{ id, name, role }: { id: any; name: string; role: string },
|
||||
{ rejectWithValue }
|
||||
) => {
|
||||
try {
|
||||
const response = await http.put(`auth/${id}/update-admin`, {
|
||||
name,
|
||||
role,
|
||||
});
|
||||
toast.success("Admin updated successfully");
|
||||
return response?.data;
|
||||
} catch (error: any) {
|
||||
toast.error("Error updating the user" + error);
|
||||
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const initialState: AuthState = {
|
||||
user: null,
|
||||
admins: [],
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
// error: null,
|
||||
token: null,
|
||||
};
|
||||
|
||||
const adminSlice = createSlice({
|
||||
name: "admin",
|
||||
initialState,
|
||||
reducers: {},
|
||||
extraReducers: (builder) => {
|
||||
builder
|
||||
.addCase(adminList.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
// state.error = null;
|
||||
})
|
||||
.addCase(
|
||||
adminList.fulfilled,
|
||||
(state, action: PayloadAction<Admin[]>) => {
|
||||
state.isLoading = false;
|
||||
state.admins = action.payload;
|
||||
}
|
||||
)
|
||||
.addCase(
|
||||
adminList.rejected,
|
||||
(state) => {
|
||||
state.isLoading = false;
|
||||
// state.error = action.payload || "An error occurred";
|
||||
}
|
||||
)
|
||||
.addCase(deleteAdmin.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
})
|
||||
.addCase(deleteAdmin.fulfilled, (state, action) => {
|
||||
state.isLoading = false;
|
||||
state.admins = state.admins.filter(
|
||||
(admin) => String(admin.id) !== String(action.payload)
|
||||
);
|
||||
})
|
||||
.addCase(deleteAdmin.rejected, (state) => {
|
||||
state.isLoading = false;
|
||||
})
|
||||
.addCase(updateAdmin.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
})
|
||||
.addCase(updateAdmin.fulfilled, (state, action) => {
|
||||
const updatedAdmin = action.payload;
|
||||
state.admins = state?.admins?.map((admin) =>
|
||||
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
|
||||
);
|
||||
state.isLoading = false;
|
||||
})
|
||||
.addCase(updateAdmin.rejected, (state) => {
|
||||
state.isLoading = false;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default adminSlice.reducer;
|
|
@ -1,19 +1,14 @@
|
|||
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
||||
import http from "../../lib/https";
|
||||
import { toast } from "react-toastify";
|
||||
import { toast } from "sonner";
|
||||
|
||||
// Define types for state
|
||||
//Eknoor singh
|
||||
//date:- 12-Feb-2025
|
||||
//Token for the user has been declared
|
||||
interface User {
|
||||
data: any;
|
||||
token: string | null;
|
||||
map(
|
||||
arg0: (
|
||||
admin: { name: any; role: any; email: any; phone: any },
|
||||
index: number
|
||||
) => { srno: number; name: any; role: any; email: any; phone: any }
|
||||
): unknown;
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
|
@ -26,6 +21,7 @@ interface Admin {
|
|||
name: string;
|
||||
role: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
|
@ -33,8 +29,9 @@ interface AuthState {
|
|||
admins: Admin[];
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: object | string | null;
|
||||
// error: object | string | null;
|
||||
token: string | null;
|
||||
role: string | null;
|
||||
}
|
||||
|
||||
// Async thunk for login
|
||||
|
@ -42,10 +39,13 @@ export const loginUser = createAsyncThunk<
|
|||
User,
|
||||
{ email: string; password: string },
|
||||
{ rejectValue: string }
|
||||
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
|
||||
>("LoginUser", async ({ email, password }, { rejectWithValue }) => {
|
||||
try {
|
||||
// this is endpoint not action name
|
||||
const response = await http.post("admin/login", {
|
||||
//use below commented endpoint if using deployed backend........
|
||||
// const response = await http.post("admin/login", {
|
||||
|
||||
const response = await http.post("auth/login", {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
@ -53,6 +53,8 @@ export const loginUser = createAsyncThunk<
|
|||
toast.success(response.data?.message);
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
toast.error("Error logging in the user" + error);
|
||||
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
|
@ -81,162 +83,49 @@ export const registerUser = createAsyncThunk<
|
|||
}
|
||||
});
|
||||
|
||||
//created by Eknoor and jaanvi
|
||||
//date: 10-Feb-2025
|
||||
//Fetching list of admins
|
||||
|
||||
export const adminList = createAsyncThunk<
|
||||
Admin[],
|
||||
void,
|
||||
{ rejectValue: string }
|
||||
>("/auth", async (_, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await http.get("/auth");
|
||||
console.log(response?.data?.data);
|
||||
return response?.data?.data?.map(
|
||||
(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) {
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
//created by Eknoor
|
||||
//date: 11-Feb-2025
|
||||
//function for deleting admin
|
||||
|
||||
export const deleteAdmin = createAsyncThunk<
|
||||
string,
|
||||
string,
|
||||
{ rejectValue: string }
|
||||
>("deleteAdmin", async (id, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await http.delete(`/auth/${id}`);
|
||||
toast.success(response.data?.message);
|
||||
return id;
|
||||
} catch (error: any) {
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export const updateAdmin = createAsyncThunk(
|
||||
"/auth/id",
|
||||
async (
|
||||
{ id, name, role }: { id: any; name: string; role: string },
|
||||
{ rejectWithValue }
|
||||
) => {
|
||||
try {
|
||||
const response = await http.put(`/auth/${id}`, { name, role });
|
||||
toast.success("Admin updated successfully");
|
||||
console.log(response?.data);
|
||||
return response?.data;
|
||||
} catch (error: any) {
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
//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 http?.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"
|
||||
);
|
||||
}
|
||||
});
|
||||
// TODO: create logout action and delete token then handle logout cases
|
||||
|
||||
const initialState: AuthState = {
|
||||
user: null,
|
||||
admins: [],
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
// error: null,
|
||||
//Eknoor singh
|
||||
//date:- 12-Feb-2025
|
||||
//initial state of token set to null
|
||||
token: null,
|
||||
role: null, // New field for role
|
||||
};
|
||||
|
||||
const authSlice = createSlice({
|
||||
name: "auth",
|
||||
initialState,
|
||||
reducers: {
|
||||
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");
|
||||
},
|
||||
},
|
||||
reducers: {},
|
||||
extraReducers: (builder) => {
|
||||
builder
|
||||
// Login
|
||||
.addCase(loginUser.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
state.error = null;
|
||||
// state.error = null;
|
||||
})
|
||||
.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
|
||||
state.user = action.payload.data;
|
||||
state.token = action.payload.data.token;
|
||||
})
|
||||
|
||||
.addCase(
|
||||
loginUser.rejected,
|
||||
(state, action: PayloadAction<string | undefined>) => {
|
||||
// (state, action: PayloadAction<string | undefined>) => {
|
||||
(state) => {
|
||||
state.isLoading = false;
|
||||
state.error = action.payload || "An error occurred";
|
||||
// state.error = action.payload || "An error occurred";
|
||||
}
|
||||
)
|
||||
// Register
|
||||
.addCase(registerUser.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
state.error = null;
|
||||
// state.error = null;
|
||||
})
|
||||
.addCase(
|
||||
registerUser.fulfilled,
|
||||
|
@ -250,85 +139,18 @@ const authSlice = createSlice({
|
|||
registerUser.rejected,
|
||||
(state, action: PayloadAction<string | undefined>) => {
|
||||
state.isLoading = false;
|
||||
state.error = action.payload || "An error occurred";
|
||||
// state.error = action.payload || "An error occurred";
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// created by Jaanvi and Eknoor
|
||||
//AdminList
|
||||
.addCase(adminList.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
state.error = null;
|
||||
})
|
||||
.addCase(
|
||||
adminList.fulfilled,
|
||||
(state, action: PayloadAction<Admin[]>) => {
|
||||
state.isLoading = false;
|
||||
state.admins = action.payload;
|
||||
}
|
||||
)
|
||||
// created by Jaanvi and Eknoor
|
||||
//AdminList
|
||||
|
||||
.addCase(
|
||||
adminList.rejected,
|
||||
(state, action: PayloadAction<string | undefined>) => {
|
||||
state.isLoading = false;
|
||||
state.error = action.payload || "An error occurred";
|
||||
}
|
||||
)
|
||||
|
||||
//created by Eknoor
|
||||
//date: 11-Feb-2025
|
||||
//cases for deleting admin
|
||||
.addCase(deleteAdmin.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
})
|
||||
.addCase(deleteAdmin.fulfilled, (state, action) => {
|
||||
state.isLoading = false;
|
||||
state.admins = state.admins.filter(
|
||||
(admin) => String(admin.id) !== String(action.payload)
|
||||
);
|
||||
})
|
||||
.addCase(deleteAdmin.rejected, (state, action) => {
|
||||
state.isLoading = false;
|
||||
state.error = action.payload || "Failed to delete admin";
|
||||
})
|
||||
.addCase(updateAdmin.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
state.error = null;
|
||||
})
|
||||
.addCase(updateAdmin.fulfilled, (state, action) => {
|
||||
const updatedAdmin = action.payload;
|
||||
state.admins = state?.admins?.map((admin) =>
|
||||
admin?.id === updatedAdmin?.id ? updatedAdmin : admin
|
||||
);
|
||||
|
||||
state.isLoading = false;
|
||||
})
|
||||
.addCase(updateAdmin.rejected, (state, action) => {
|
||||
state.isLoading = false;
|
||||
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";
|
||||
});
|
||||
//Eknoor singh
|
||||
//date:- 12-Feb-2025
|
||||
//Reducers for fetching profiles has been implemente
|
||||
},
|
||||
});
|
||||
|
||||
export const { logout } = authSlice.actions;
|
||||
// export const { logout } = authSlice.actions;
|
||||
export default authSlice.reducer;
|
||||
|
|
68
src/redux/slices/profileSlice.ts
Normal file
68
src/redux/slices/profileSlice.ts
Normal file
|
@ -0,0 +1,68 @@
|
|||
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import http from "../../lib/https";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface User {
|
||||
token: string | null;
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export const fetchAdminProfile = createAsyncThunk<
|
||||
User,
|
||||
void,
|
||||
{ rejectValue: string }
|
||||
>("GetAdminProfile", async (_, { rejectWithValue }) => {
|
||||
try {
|
||||
const token = localStorage?.getItem("authToken");
|
||||
if (!token) throw new Error("No token found");
|
||||
|
||||
const response = await http.get("/auth/profile");
|
||||
|
||||
if (!response.data?.data) throw new Error("Invalid API response");
|
||||
|
||||
return response.data.data;
|
||||
} catch (error: any) {
|
||||
toast.error("Error Fetching Profile" + error);
|
||||
return rejectWithValue(
|
||||
error?.response?.data?.message || "An error occurred"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const initialState: AuthState = {
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
};
|
||||
|
||||
const profileSlice = createSlice({
|
||||
name: "profile",
|
||||
initialState,
|
||||
reducers: {},
|
||||
extraReducers: (builder) => {
|
||||
builder
|
||||
.addCase(fetchAdminProfile.pending, (state) => {
|
||||
state.isLoading = true;
|
||||
})
|
||||
.addCase(fetchAdminProfile.fulfilled, (state, action) => {
|
||||
state.isLoading = false;
|
||||
state.user = action.payload;
|
||||
state.isAuthenticated = true;
|
||||
})
|
||||
.addCase(fetchAdminProfile.rejected, (state) => {
|
||||
state.isLoading = false;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default profileSlice.reducer;
|
|
@ -1,13 +1,9 @@
|
|||
import { configureStore } from '@reduxjs/toolkit';
|
||||
import authReducer from '../slices/authSlice.ts'
|
||||
import { configureStore } from "@reduxjs/toolkit";
|
||||
import rootReducer from "../reducers.ts";
|
||||
const store = configureStore({
|
||||
reducer: {
|
||||
auth: authReducer,
|
||||
},
|
||||
reducer: rootReducer,
|
||||
});
|
||||
|
||||
export type RootState = ReturnType<typeof store.getState>;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
export default store;
|
||||
|
||||
|
||||
|
|
|
@ -1,7 +1,16 @@
|
|||
import { Routes as BaseRoutes, Navigate, Route } from "react-router-dom";
|
||||
import {
|
||||
Routes as BaseRoutes,
|
||||
Navigate,
|
||||
Route,
|
||||
RouteProps,
|
||||
} from "react-router-dom";
|
||||
import React, { Suspense } from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
import { RootState } from "./redux/store/store";
|
||||
import LoadingComponent from "./components/Loading";
|
||||
import DashboardLayout from "./layouts/DashboardLayout";
|
||||
|
||||
// Page imports
|
||||
import Login from "./pages/Auth/Login";
|
||||
import SignUp from "./pages/Auth/SignUp";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
|
@ -9,27 +18,44 @@ import Vehicles from "./pages/Vehicles";
|
|||
import AdminList from "./pages/AdminList";
|
||||
import ProfilePage from "./pages/ProfilePage";
|
||||
|
||||
import SuperAdminRouter from "./superAdminRouter";
|
||||
|
||||
function ProtectedRoute({
|
||||
caps,
|
||||
component,
|
||||
}: {
|
||||
interface ProtectedRouteProps {
|
||||
caps: string[];
|
||||
component: React.ReactNode;
|
||||
}) {
|
||||
if (!localStorage.getItem("authToken"))
|
||||
return <Navigate to={`/auth/login`} replace />;
|
||||
|
||||
return component;
|
||||
}
|
||||
|
||||
interface SuperAdminRouteProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
// Protected Route Component
|
||||
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ caps, component }) => {
|
||||
if (!localStorage.getItem("authToken")) {
|
||||
return <Navigate to="/auth/login" replace />;
|
||||
}
|
||||
return <>{component}</>;
|
||||
};
|
||||
|
||||
// Super Admin Route Component
|
||||
const SuperAdminRoute: React.FC<SuperAdminRouteProps> = ({ children }) => {
|
||||
const userRole = useSelector(
|
||||
(state: RootState) => state.profileReducer.user?.role
|
||||
);
|
||||
|
||||
if (userRole !== "superadmin") {
|
||||
return <Navigate to="/panel/dashboard" replace />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
// Combined Router Component
|
||||
export default function AppRouter() {
|
||||
return (
|
||||
<Suspense fallback={<LoadingComponent />}>
|
||||
<BaseRoutes>
|
||||
{/* Default Route */}
|
||||
<Route element={<Navigate to="/auth/login" replace />} index />
|
||||
|
||||
{/* Auth Routes */}
|
||||
<Route path="/auth">
|
||||
<Route
|
||||
path=""
|
||||
|
@ -38,8 +64,18 @@ export default function AppRouter() {
|
|||
/>
|
||||
<Route path="login" element={<Login />} />
|
||||
<Route path="signup" element={<SignUp />} />
|
||||
<Route
|
||||
path="profile"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={<ProfilePage />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
|
||||
{/* Dashboard Routes */}
|
||||
<Route path="/panel" element={<DashboardLayout />}>
|
||||
<Route
|
||||
path="dashboard"
|
||||
|
@ -65,26 +101,17 @@ export default function AppRouter() {
|
|||
<ProtectedRoute
|
||||
caps={[]}
|
||||
component={
|
||||
//Eknoor singh and jaanvi
|
||||
//date:- 12-Feb-2025
|
||||
//Admin list put under protected route for specific use
|
||||
<SuperAdminRouter>
|
||||
<SuperAdminRoute>
|
||||
<AdminList />
|
||||
</SuperAdminRouter>
|
||||
</SuperAdminRoute>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route path="*" element={<>404</>} />
|
||||
</Route>
|
||||
<Route
|
||||
path="/auth/profile"
|
||||
element={
|
||||
<ProtectedRoute caps={[]} component={<ProfilePage />} />
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Catch-all Route */}
|
||||
<Route path="*" element={<>404</>} />
|
||||
</BaseRoutes>
|
||||
</Suspense>
|
||||
|
|
|
@ -1,25 +0,0 @@
|
|||
//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;
|
Loading…
Reference in a new issue