Skip to content

Commit

Permalink
added logs page and checkDomain function
Browse files Browse the repository at this point in the history
  • Loading branch information
sangam2109 committed Jul 6, 2024
1 parent c1cfc70 commit 883fe10
Show file tree
Hide file tree
Showing 14 changed files with 205 additions and 454 deletions.
6 changes: 4 additions & 2 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ const cors = require("cors");
const bodyParser = require("body-parser");
const connectToMongo = require("./db").db;
const app = express();
const checkDomain=require('./middleware/checkDomain.js')
app.use(cors());
// Connect to MongoDB
connectToMongo();

// Middleware to parse URL-encoded bodies
app.use(bodyParser.json({ limit: "5mb" }));
app.use(bodyParser.urlencoded({ limit: "5mb", extended: true }));

app.use(checkDomain)
//User Routes
const userProfileRoutes = require("./routes/UserProfileData/UserData");
const authRoute = require("./routes/Authentication/Auth");
Expand All @@ -28,7 +29,7 @@ const placementData = require("./routes/UserProfileData/PlacementData");
const adminControl = require("./routes/adminControlRoutes/adminControl");
const test = require("./routes/test.js");
const certificate = require('./routes/getCertificate.js')

const Logs = require('./routes/Logs/getLogs.js')

app.use("/api/userprofiles", userProfileRoutes);
app.use("/api/tr101", tr101);
Expand All @@ -43,6 +44,7 @@ app.use("/api/password", passwordResetRoute);
app.use("/api/admin", adminControl);
app.use("/api/test", test);
app.use("/api/certificate", certificate);
app.use("/api/logs", Logs);
// Start the server
const port = process.env.PORT;
app.listen(port, () => {
Expand Down
17 changes: 17 additions & 0 deletions backend/middleware/checkDomain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// middleware/checkDomain.js

function checkDomain(req, res, next) {
const allowedDomain = 'gne1.gndec.ac.in';
const origin = req.get('Origin') || req.get('Referer');

if (origin) {
const url = new URL(origin);
if (url.hostname === allowedDomain) {
return next();
}
}

res.status(403).json({ message: 'Forbidden' });
}

module.exports = checkDomain;
24 changes: 24 additions & 0 deletions backend/middleware/isSuperAdmin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const jwt = require('jsonwebtoken')
const JWT_Token = process.env.JWT_TOKEN;

function isAdmin(req, res, next) {
// Get the authentication token from the request headers
const token = req.header('auth-token')
if (!token) {
return res.status(401).json({ message: 'Authentication token not provided' });
}
try {
// Verify the token and decode its payload
const decodedToken = jwt.verify(token, JWT_Token);

// Check if the user role is "admin"
if (decodedToken.user.role !== 'superadmin') {
return res.status(403).json({ message: 'You are not authorized to access this resource' });
}
// User is authorized, proceed to the next middleware or route handler
next();
} catch (error) {
return res.status(401).json({ message: 'Invalid authentication token' });
}
}
module.exports = isAdmin;
23 changes: 23 additions & 0 deletions backend/routes/Logs/getLogs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const express = require('express');
const router = express.Router();
const Logs = require('../../models/logs')
const fetchuser = require("../../middleware/fetchUser");
const isSuperAdmin = require("../../middleware/isSuperAdmin");

router.get('/getalllogs', fetchuser, isSuperAdmin, async (req, res) => {
try {

const allLogs = await Logs.find({})
if (!allLogs) {
return res.status(404).json({ success: false, message: 'Logs not found' });
}
return res.status(200).json({ success: true, data: allLogs });

}
catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});

module.exports = router;
6 changes: 3 additions & 3 deletions backend/routes/adminControlRoutes/adminControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ const express = require("express");
const adminControl = require("../../models/adminControl");
const router = express.Router();
const fetchuser = require("../../middleware/fetchUser");
const isAdmin = require("../../middleware/isAdmin");
const isSuperAdmin = require("../../middleware/isSuperAdmin");
const { SignUp } = require("../../models/UserInfo");
const logEntry = require('../../models/logs')
const getUserCrn = require('../../utils/getAdminDetails')

router.post("/trainingNames", fetchuser, isAdmin, async (req, res) => {
router.post("/trainingNames", fetchuser, isSuperAdmin, async (req, res) => {
try {
const {
Training_No,
Expand Down Expand Up @@ -75,7 +75,7 @@ router.get("/trainingNames", async (req, res) => {
}
});

router.get("/getBatches", fetchuser, isAdmin, async (req, res) => {
router.get("/getBatches", fetchuser, isSuperAdmin, async (req, res) => {
try {
// Fetch all users
const users = await SignUp.find({ role: "user" }).select(
Expand Down
4 changes: 3 additions & 1 deletion backend/routes/getUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const fetchuser = require('../middleware/fetchUser');
const isAdmin = require('../middleware/isAdmin');
const logEntry = require('../models/logs')
const getUserCrn = require('../utils/getAdminDetails')
const isSuperAdmin = require('../middleware/isSuperAdmin');

router.get('/getuser/:crn', fetchuser, async (req, res) => {
try {
const crn = req.params.crn;
Expand All @@ -20,7 +22,7 @@ router.get('/getuser/:crn', fetchuser, async (req, res) => {
res.status(500).json({ success: false, message: 'Internal server error occurred' });
}
});
router.get('/getallusers', fetchuser, isAdmin, async (req, res) => {
router.get('/getallusers', fetchuser, isSuperAdmin, async (req, res) => {
try {
// Fetch all users
const users = await SignUp.find({ role: 'user' }).select('-password -tr101.certificate -tr102.certificate -tr103.certificate -tr104.certificate -placementData.appointmentLetter -placementData.gateCertificate');
Expand Down
40 changes: 30 additions & 10 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ import Navbar from "./Components/Navbar/Navbar";
import PlacementForm from "./pages/PlacementInput";
import Training101 from "./pages/Training";
import ProtectedRoute from "./Components/ProtectedRoute";
import Admin from "./pages/AdminDashboard/AdminDashboard";
import PlacementStats from "./pages/Placement Graphs/PlacementStats";
import TrainingNames from "./pages/TrainingNamesController/TrainingNames";
import Footer from "./Components/Footer";
import EditProfile from "./pages/EditProfile/EditProfile";
import StudentData from "./pages/StudentData/StudentData";
import Logs from "./pages/Logs/Logs";

class App extends Component {
render() {
Expand All @@ -27,21 +27,41 @@ class App extends Component {
<Routes>
{/* Redirect to the dashboard if user is authenticated */}
<Route path="/" element={<Navigate to="/home" />} />
<Route path="/signup" element={<Signup />} />
<Route path="/verify" element={<Verify />} />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<ProtectedRoute path="/signup" component={Signup} />} />
<Route path="/verify" element={<ProtectedRoute path="/verify" component={Verify} />} />
<Route path="/login" element={<ProtectedRoute path="/login" component={Login} />} />
<Route path="/forgotpassword" element={<ProtectedRoute path="/forgotpassword" component={ForgotPassword} />} />



// user routes
<Route path="/home" element={<ProtectedRoute path="/home" component={Home} />} />
<Route path='/placement' element={<ProtectedRoute path="/placement" component={PlacementForm} />} />
<Route path='/tr' element={<ProtectedRoute path="/tr" component={Training101} />} />
<Route path="/dashboard" element={<ProtectedRoute path="/dashboard" component={DashBoard} />} />

//superadmin route
<Route path='/superadmin/trainingNames' element={<ProtectedRoute path="/superadmin/trainingNames" component={TrainingNames} />} />
<Route path='/superadmin/studentData' element={<ProtectedRoute path="/superadmin/studentData" component={TrainingNames} />} />
<Route
path="/superadmin/logs"
element={
<ProtectedRoute path="/superadmin/logs" component={Logs} />
}
/>

//superadmin and admin route
<Route path='/superadmin/studentData' element={<ProtectedRoute path="/superadmin/studentData" component={StudentData} />} />

<Route path='/admin/editProfile' element={<ProtectedRoute path="/admin/editProfile" component={EditProfile} />} />

<Route path='/tr' element={<ProtectedRoute path="/tr" component={Training101} />} />

<Route path="/superadmin" element={<ProtectedRoute path="/superadmin" component={SuperAdminForm} />} />

<Route path="/superadmin/placementStats" element={<ProtectedRoute path="/superadmin/placementStats" component={PlacementStats} />} />
<Route path="/admin" element={<ProtectedRoute path="/admin" component={Admin} />} />
<Route path="/dashboard" element={<ProtectedRoute path="/dashboard" component={DashBoard} />} />
<Route path="/forgotpassword" element={<ForgotPassword />} />

//not mentioned paths re routed to
<Route path="*" element={<Navigate to="/" />} />


</Routes>
<Footer />
</BrowserRouter>
Expand Down
79 changes: 51 additions & 28 deletions client/src/Components/ProtectedRoute.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,68 +2,91 @@ import React from "react";
import { jwtDecode } from "jwt-decode";
import { Navigate } from "react-router-dom";
import SuperAdmin from "../pages/SuperAdminDashboard/SuperAdmin";
import Admin from "../pages/AdminDashboard/AdminDashboard";
import Home from "../pages/Home";
import PlacementStats from "../pages/Placement Graphs/PlacementStats";
import TrainingNames from "../pages/TrainingNamesController/TrainingNames";
import EditProfile from "../pages/EditProfile/EditProfile";
import StudentData from "../pages/StudentData/StudentData";
import Dashboard from '../pages/DashBoard'
import Placement from "../pages/PlacementInput"
import Training from "../pages/Training"
import Signup from "../pages/Authentication/Signup";
import Login from "../pages/Authentication/Login";
import Verify from "../pages/Authentication/Verify";
import ForgotPassword from "../pages/Authentication/Forgotpassword"
import Logs from "../pages/Logs/Logs";

const ProtectedRoute = ({ component: Component, path, ...rest }) => {
const authToken = localStorage.getItem("authtoken");

if (!authToken) {
return <Navigate to="/login" replace />;
if (path === "/signup") {
return <Signup />
}
else if (path === "/login") {
return <Login />
}
else if (path === "/verify") {
return <Verify />
}
else if (path === "/forgotpassword") {
return <ForgotPassword />
}
else {
return <Navigate to="/login" replace />;
}

} else {
try {
const decodedToken = jwtDecode(authToken);
const userRole = decodedToken.user.role;

if (path === "/" && userRole) {
return <Navigate to="/" replace />;
if (userRole === "superadmin") {
if (path === "/superadmin/trainingNames") {
return <TrainingNames />;
}
if (path === "/superadmin/logs") {
return <Logs />;
}
}

if (path === "/login" && userRole) {
return <Navigate to="/home" replace />;
}
if (userRole === 'superadmin' || userRole === 'admin') {
if (path === '/superadmin') {
return <SuperAdmin />;
}
if (path === '/admin/editProfile') {
else if (path === '/admin/editProfile') {
return <EditProfile />
}
if (path === '/superadmin/studentData') {
else if (path === '/superadmin/studentData') {
return <StudentData />
}
if (path === "/superadmin/placementStats") {
else if (path === "/superadmin/placementStats") {
return <PlacementStats />;
}
else {
return <Navigate to="/superadmin" replace />;
}
}
// Check if the user is authenticated and has the required role
if (userRole === "superadmin") {
if (path === "/superadmin/trainingNames") {
return <TrainingNames />;
if (userRole === "user") {
if (path === '/dashboard') {
return <Dashboard />
}

// Redirect superadmin to home if trying to access admin or superadmin route
else {
return <SuperAdmin />;
else if (path === '/placement') {
return <Placement />;
}

} else {
// Redirect to home or another appropriate route if the user doesn't have the required role
if (
path === "/admin" ||
path === "/superadmin" ||
path === "/superadmin/placementStats" ||
path === "/superadmin/trainingNames" ||
path === "/admin/editProfile"
) {
else if (path === '/tr') {
return <Training />;
}
else if (path === '/home') {
return <Home />;
}
return <Component {...rest} />;
else {
return <Navigate to="/home" replace />;
}
}


} catch (error) {
// If there's an error decoding the token, redirect to login
console.error("Error decoding token:", error);
Expand Down
Loading

0 comments on commit 883fe10

Please sign in to comment.