dev-jaanvi #1
|
@ -7,7 +7,7 @@ import TableContainer from "@mui/material/TableContainer"
|
||||||
import TableHead from "@mui/material/TableHead"
|
import TableHead from "@mui/material/TableHead"
|
||||||
import TableRow from "@mui/material/TableRow"
|
import TableRow from "@mui/material/TableRow"
|
||||||
import Paper, { paperClasses } from "@mui/material/Paper"
|
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 { useDispatch } from "react-redux"
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
|
|
|
@ -43,7 +43,9 @@ type PropType = {
|
||||||
|
|
||||||
export default function MenuContent({ hidden }: PropType) {
|
export default function MenuContent({ hidden }: PropType) {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const userRole = useSelector((state: RootState) => state.auth.user?.role);
|
const userRole = useSelector(
|
||||||
|
(state: RootState) => state.profile.user?.role
|
||||||
|
);
|
||||||
|
|
||||||
const mainListItems = [
|
const mainListItems = [
|
||||||
...baseMenuItems,
|
...baseMenuItems,
|
||||||
|
|
|
@ -11,7 +11,7 @@ import React, { useEffect } from "react";
|
||||||
import { ArrowLeftIcon, ArrowRightIcon } from "@mui/x-date-pickers";
|
import { ArrowLeftIcon, ArrowRightIcon } from "@mui/x-date-pickers";
|
||||||
import { AppDispatch, RootState } from "../../redux/store/store";
|
import { AppDispatch, RootState } from "../../redux/store/store";
|
||||||
import { Button } from "@mui/material";
|
import { Button } from "@mui/material";
|
||||||
import { fetchAdminProfile } from "../../redux/slices/authSlice";
|
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
|
||||||
|
|
||||||
const drawerWidth = 240;
|
const drawerWidth = 240;
|
||||||
|
|
||||||
|
@ -34,7 +34,7 @@ export default function SideMenu() {
|
||||||
//Dispatch is called with user from Authstate Interface
|
//Dispatch is called with user from Authstate Interface
|
||||||
|
|
||||||
const dispatch = useDispatch<AppDispatch>();
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
const { user } = useSelector((state: RootState) => state?.auth);
|
const { user } = useSelector((state: RootState) => state?.profile);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch(fetchAdminProfile());
|
dispatch(fetchAdminProfile());
|
||||||
|
|
|
@ -6,7 +6,7 @@ const http = axios.create({
|
||||||
http.interceptors.request.use((config) => {
|
http.interceptors.request.use((config) => {
|
||||||
const authToken = localStorage.getItem("authToken");
|
const authToken = localStorage.getItem("authToken");
|
||||||
if (authToken) {
|
if (authToken) {
|
||||||
config.headers.Authorization = authToken;
|
config.headers.Authorization = `Bearer ${authToken}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
|
|
|
@ -4,7 +4,7 @@ import AddEditCategoryModal from "../../components/AddEditCategoryModal";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import CustomTable, { Column } from "../../components/CustomTable";
|
import CustomTable, { Column } from "../../components/CustomTable";
|
||||||
import { useDispatch, useSelector } from "react-redux";
|
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
|
import { AppDispatch, RootState } from "../../redux/store/store"; // Import RootState for selector
|
||||||
|
|
||||||
export default function AdminList() {
|
export default function AdminList() {
|
||||||
|
@ -17,7 +17,7 @@ export default function AdminList() {
|
||||||
const dispatch = useDispatch<AppDispatch>();
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
|
|
||||||
// Fetching admin data from the Redux store
|
// Fetching admin data from the Redux store
|
||||||
const admins = useSelector((state: RootState) => state.auth.admins);
|
const admins = useSelector((state: RootState) => state.admin.admins);
|
||||||
|
|
||||||
// Dispatching the API call when the component mounts
|
// Dispatching the API call when the component mounts
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
|
@ -96,6 +96,10 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [phone, setPhone] = React.useState("");
|
const [phone, setPhone] = React.useState("");
|
||||||
|
|
||||||
|
const roleOptions = [
|
||||||
|
{ value: "admin", label: "Admin" },
|
||||||
|
{ value: "user", label: "User" }
|
||||||
|
];
|
||||||
// Enhanced email validation regex
|
// Enhanced email validation regex
|
||||||
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
|
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
|
||||||
|
|
||||||
|
@ -266,11 +270,14 @@ export default function SignUp(props: { disableCustomTheme?: boolean }) {
|
||||||
}
|
}
|
||||||
error={!!errors.role}
|
error={!!errors.role}
|
||||||
>
|
>
|
||||||
<MenuItem value="superadmin">
|
{roleOptions.map((option) => (
|
||||||
SuperAdmin
|
<MenuItem
|
||||||
|
key={option.value}
|
||||||
|
value={option.value}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
<MenuItem value="admin">Admin</MenuItem>
|
))}
|
||||||
<MenuItem value="user">User</MenuItem>
|
|
||||||
</Select>
|
</Select>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
|
@ -16,7 +16,7 @@ import {
|
||||||
|
|
||||||
import { useDispatch, useSelector } from "react-redux";
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
import { AppDispatch, RootState } from "../../redux/store/store";
|
import { AppDispatch, RootState } from "../../redux/store/store";
|
||||||
import { fetchAdminProfile } from "../../redux/slices/authSlice";
|
import { fetchAdminProfile } from "../../redux/slices/profileSlice";
|
||||||
|
|
||||||
const ProfilePage = () => {
|
const ProfilePage = () => {
|
||||||
//Eknoor singh
|
//Eknoor singh
|
||||||
|
@ -24,7 +24,7 @@ const ProfilePage = () => {
|
||||||
//Dispatch is called and user, isLoading, and error from Authstate Interface
|
//Dispatch is called and user, isLoading, and error from Authstate Interface
|
||||||
const dispatch = useDispatch<AppDispatch>();
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
const { user, isLoading, error } = useSelector(
|
const { user, isLoading, error } = useSelector(
|
||||||
(state: RootState) => state?.auth
|
(state: RootState) => state?.profile
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
@ -56,10 +56,6 @@ const ProfilePage = () => {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(user?.name);
|
|
||||||
console.log(user?.email);
|
|
||||||
console.log(user?.role);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container sx={{ py: 4 }}>
|
<Container sx={{ py: 4 }}>
|
||||||
<Typography variant="h4" gutterBottom>
|
<Typography variant="h4" gutterBottom>
|
||||||
|
|
|
@ -1,9 +1,13 @@
|
||||||
import { combineReducers } from "@reduxjs/toolkit";
|
import { combineReducers } from "@reduxjs/toolkit";
|
||||||
|
|
||||||
import authReducer from "./slices/authSlice";
|
import authReducer from "./slices/authSlice";
|
||||||
|
import adminReducer from "./slices/adminSlice";
|
||||||
|
import profileReducer from "./slices/profileSlice";
|
||||||
|
|
||||||
const rootReducer = combineReducers({
|
const rootReducer = combineReducers({
|
||||||
authReducer,
|
authReducer,
|
||||||
|
adminReducer,
|
||||||
|
profileReducer
|
||||||
});
|
});
|
||||||
|
|
||||||
export type RootState = ReturnType<typeof rootReducer>;
|
export type RootState = ReturnType<typeof rootReducer>;
|
||||||
|
|
155
src/redux/slices/adminSlice.ts
Normal file
155
src/redux/slices/adminSlice.ts
Normal file
|
@ -0,0 +1,155 @@
|
||||||
|
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
||||||
|
import http from "../../lib/https";
|
||||||
|
import { toast } from "react-toastify";
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
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) {
|
||||||
|
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) {
|
||||||
|
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, action: PayloadAction<string | undefined>) => {
|
||||||
|
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, 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 =
|
||||||
|
typeof action.payload === "string"
|
||||||
|
? action.payload
|
||||||
|
: "Something went wrong while updating Admin!";
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default adminSlice.reducer;
|
|
@ -7,6 +7,7 @@ import { toast } from "react-toastify";
|
||||||
//date:- 12-Feb-2025
|
//date:- 12-Feb-2025
|
||||||
//Token for the user has been declared
|
//Token for the user has been declared
|
||||||
interface User {
|
interface User {
|
||||||
|
data: any;
|
||||||
token: string | null;
|
token: string | null;
|
||||||
map(
|
map(
|
||||||
arg0: (
|
arg0: (
|
||||||
|
@ -43,10 +44,10 @@ export const loginUser = createAsyncThunk<
|
||||||
User,
|
User,
|
||||||
{ email: string; password: string },
|
{ email: string; password: string },
|
||||||
{ rejectValue: string }
|
{ rejectValue: string }
|
||||||
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
|
>("LoginUser", async ({ email, password }, { rejectWithValue }) => {
|
||||||
try {
|
try {
|
||||||
// this is endpoint not action name
|
// this is endpoint not action name
|
||||||
const response = await http.post("admin/login", {
|
const response = await http.post("auth/login", {
|
||||||
email,
|
email,
|
||||||
password,
|
password,
|
||||||
});
|
});
|
||||||
|
@ -82,112 +83,6 @@ 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 = {
|
const initialState: AuthState = {
|
||||||
user: null,
|
user: null,
|
||||||
admins: [],
|
admins: [],
|
||||||
|
@ -204,15 +99,6 @@ const authSlice = createSlice({
|
||||||
name: "auth",
|
name: "auth",
|
||||||
initialState,
|
initialState,
|
||||||
reducers: {
|
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");
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
extraReducers: (builder) => {
|
extraReducers: (builder) => {
|
||||||
builder
|
builder
|
||||||
|
@ -224,9 +110,10 @@ const authSlice = createSlice({
|
||||||
.addCase(loginUser.fulfilled, (state, action) => {
|
.addCase(loginUser.fulfilled, (state, action) => {
|
||||||
state.isLoading = false;
|
state.isLoading = false;
|
||||||
state.isAuthenticated = true;
|
state.isAuthenticated = true;
|
||||||
state.user = action.payload; // Fix: Extract correct payload
|
state.user = action.payload.data;
|
||||||
state.token = action.payload.token; // Store token in Redux
|
state.token = action.payload.data.token;
|
||||||
})
|
})
|
||||||
|
|
||||||
.addCase(
|
.addCase(
|
||||||
loginUser.rejected,
|
loginUser.rejected,
|
||||||
(state, action: PayloadAction<string | undefined>) => {
|
(state, action: PayloadAction<string | undefined>) => {
|
||||||
|
@ -253,83 +140,16 @@ const authSlice = createSlice({
|
||||||
state.isLoading = false;
|
state.isLoading = false;
|
||||||
state.error = action.payload || "An error occurred";
|
state.error = action.payload || "An error occurred";
|
||||||
}
|
}
|
||||||
)
|
);
|
||||||
|
|
||||||
// created by Jaanvi and Eknoor
|
// created by Jaanvi and Eknoor
|
||||||
//AdminList
|
//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;
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
.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
|
//Eknoor singh
|
||||||
//date:- 12-Feb-2025
|
//date:- 12-Feb-2025
|
||||||
//Reducers for fetching profiles has been implemented
|
//Reducers for fetching profiles has been implemente
|
||||||
.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";
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export const { logout } = authSlice.actions;
|
// export const { logout } = authSlice.actions;
|
||||||
export default authSlice.reducer;
|
export default authSlice.reducer;
|
||||||
|
|
71
src/redux/slices/profileSlice.ts
Normal file
71
src/redux/slices/profileSlice.ts
Normal file
|
@ -0,0 +1,71 @@
|
||||||
|
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
|
||||||
|
import http from "../../lib/https";
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
token: string | null;
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
phone: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
user: User | null;
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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", {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.data?.data) throw new Error("Invalid API response");
|
||||||
|
|
||||||
|
return response.data.data;
|
||||||
|
} catch (error: any) {
|
||||||
|
return rejectWithValue(error?.response?.data?.message || "An error occurred");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const initialState: AuthState = {
|
||||||
|
user: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
isLoading: false,
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const profileSlice = createSlice({
|
||||||
|
name: "profile",
|
||||||
|
initialState,
|
||||||
|
reducers: {
|
||||||
|
},
|
||||||
|
extraReducers: (builder) => {
|
||||||
|
builder
|
||||||
|
.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";
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default profileSlice.reducer;
|
|
@ -1,8 +1,12 @@
|
||||||
import { configureStore } from '@reduxjs/toolkit';
|
import { configureStore } from '@reduxjs/toolkit';
|
||||||
import authReducer from '../slices/authSlice.ts'
|
import authReducer from '../slices/authSlice.ts'
|
||||||
|
import adminReducer from "../slices/adminSlice.ts"
|
||||||
|
import profileReducer from "../slices/profileSlice.ts"
|
||||||
const store = configureStore({
|
const store = configureStore({
|
||||||
reducer: {
|
reducer: {
|
||||||
auth: authReducer,
|
auth: authReducer,
|
||||||
|
admin: adminReducer,
|
||||||
|
profile: profileReducer
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -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 React, { Suspense } from "react";
|
||||||
|
import { useSelector } from "react-redux";
|
||||||
|
import { RootState } from "./redux/store/store";
|
||||||
import LoadingComponent from "./components/Loading";
|
import LoadingComponent from "./components/Loading";
|
||||||
import DashboardLayout from "./layouts/DashboardLayout";
|
import DashboardLayout from "./layouts/DashboardLayout";
|
||||||
|
|
||||||
|
// Page imports
|
||||||
import Login from "./pages/Auth/Login";
|
import Login from "./pages/Auth/Login";
|
||||||
import SignUp from "./pages/Auth/SignUp";
|
import SignUp from "./pages/Auth/SignUp";
|
||||||
import Dashboard from "./pages/Dashboard";
|
import Dashboard from "./pages/Dashboard";
|
||||||
|
@ -9,27 +18,44 @@ import Vehicles from "./pages/Vehicles";
|
||||||
import AdminList from "./pages/AdminList";
|
import AdminList from "./pages/AdminList";
|
||||||
import ProfilePage from "./pages/ProfilePage";
|
import ProfilePage from "./pages/ProfilePage";
|
||||||
|
|
||||||
import SuperAdminRouter from "./superAdminRouter";
|
interface ProtectedRouteProps {
|
||||||
|
|
||||||
function ProtectedRoute({
|
|
||||||
caps,
|
|
||||||
component,
|
|
||||||
}: {
|
|
||||||
caps: string[];
|
caps: string[];
|
||||||
component: React.ReactNode;
|
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.profile.user?.role
|
||||||
|
);
|
||||||
|
|
||||||
|
if (userRole !== "superadmin") {
|
||||||
|
return <Navigate to="/panel/dashboard" replace />;
|
||||||
|
}
|
||||||
|
return <>{children}</>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Combined Router Component
|
||||||
export default function AppRouter() {
|
export default function AppRouter() {
|
||||||
return (
|
return (
|
||||||
<Suspense fallback={<LoadingComponent />}>
|
<Suspense fallback={<LoadingComponent />}>
|
||||||
<BaseRoutes>
|
<BaseRoutes>
|
||||||
|
{/* Default Route */}
|
||||||
<Route element={<Navigate to="/auth/login" replace />} index />
|
<Route element={<Navigate to="/auth/login" replace />} index />
|
||||||
|
|
||||||
|
{/* Auth Routes */}
|
||||||
<Route path="/auth">
|
<Route path="/auth">
|
||||||
<Route
|
<Route
|
||||||
path=""
|
path=""
|
||||||
|
@ -38,8 +64,18 @@ export default function AppRouter() {
|
||||||
/>
|
/>
|
||||||
<Route path="login" element={<Login />} />
|
<Route path="login" element={<Login />} />
|
||||||
<Route path="signup" element={<SignUp />} />
|
<Route path="signup" element={<SignUp />} />
|
||||||
|
<Route
|
||||||
|
path="profile"
|
||||||
|
element={
|
||||||
|
<ProtectedRoute
|
||||||
|
caps={[]}
|
||||||
|
component={<ProfilePage />}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
|
{/* Dashboard Routes */}
|
||||||
<Route path="/panel" element={<DashboardLayout />}>
|
<Route path="/panel" element={<DashboardLayout />}>
|
||||||
<Route
|
<Route
|
||||||
path="dashboard"
|
path="dashboard"
|
||||||
|
@ -65,26 +101,17 @@ export default function AppRouter() {
|
||||||
<ProtectedRoute
|
<ProtectedRoute
|
||||||
caps={[]}
|
caps={[]}
|
||||||
component={
|
component={
|
||||||
//Eknoor singh and jaanvi
|
<SuperAdminRoute>
|
||||||
//date:- 12-Feb-2025
|
|
||||||
//Admin list put under protected route for specific use
|
|
||||||
<SuperAdminRouter>
|
|
||||||
<AdminList />
|
<AdminList />
|
||||||
</SuperAdminRouter>
|
</SuperAdminRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Route path="*" element={<>404</>} />
|
<Route path="*" element={<>404</>} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route
|
|
||||||
path="/auth/profile"
|
|
||||||
element={
|
|
||||||
<ProtectedRoute caps={[]} component={<ProfilePage />} />
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
|
|
||||||
|
{/* Catch-all Route */}
|
||||||
<Route path="*" element={<>404</>} />
|
<Route path="*" element={<>404</>} />
|
||||||
</BaseRoutes>
|
</BaseRoutes>
|
||||||
</Suspense>
|
</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