Skip to content

Commit

Permalink
add event verification
Browse files Browse the repository at this point in the history
  • Loading branch information
haseebzaki-07 committed Oct 29, 2024
1 parent 161b615 commit 4704cdd
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 20 deletions.
1 change: 0 additions & 1 deletion backend/controller/customer.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ async function loginCustomer(req, res) {
process.env.JWT_SECRET,
{ expiresIn: "1h" } // Expires in 1 hour
);

res.json({
message: "Login successful",
token,
Expand Down
48 changes: 33 additions & 15 deletions backend/middlewares/authCustomer.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,42 @@
const jwt = require("jsonwebtoken");
const logger = require("../config/logger");
const config = require("../config/secret");
const Customer = require("../models/customer.model");
// Assuming the Customer model is located here

const authenticateCustomer = (req, res, next) => {
const authenticateCustomer = async (req, res, next) => {
const token = req.header("Authorization")?.split(" ")[1]; // Expecting "Bearer <token>"

if (token) {
jwt.verify(token, config.JWT_SECRET, (err, user) => {
if (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ message: "Token expired" });
}
return res.status(403).json({ message: "Invalid token" });
}
req.user = user;
logger.info(`Customer authenticated: ${JSON.stringify(user.username)}`);
next();
});
} else {
res.sendStatus(401); // Unauthorized
if (!token) {
return res.status(401).json({ message: "Authorization token is missing" });
}

try {
// Verify token
const decoded = jwt.verify(token, config.JWT_SECRET);

// Retrieve user from database to check verification status
const user = await Customer.findById(decoded.sub);

if (!user) {
return res.status(404).json({ message: "User not found" });
}

if (!user.isVerified) {
return res.status(403).json({ message: "Account not verified" });
}

// If verified, attach user to request and proceed
req.user = user;
logger.info(`Customer authenticated: ${user.name}`);
next();

} catch (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ message: "Token expired" });
}
logger.error("Token verification failed:", err);
return res.status(403).json({ message: "Invalid token" });
}
};

Expand Down
7 changes: 4 additions & 3 deletions backend/routes/eventRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
getEvents,
deleteEvent,
} = require("../controller/event.controller");
const authenticateCustomer = require("../middlewares/authCustomer");

const router = express.Router();

Expand All @@ -24,8 +25,8 @@ router.get("/", async (req, res) => {
res.status(500).json({ error: "Internal server error" });
}
});
router.post("/create", createEvent);
router.get("/all", getEvents);
router.get("/delete", deleteEvent);
router.post("/create",authenticateCustomer, createEvent);
router.get("/all",authenticateCustomer, getEvents);
router.get("/delete",authenticateCustomer, deleteEvent);

module.exports = router;
16 changes: 15 additions & 1 deletion frontend/src/components/Pages/Event.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import game from '../../assets/Boardgames/carrom.gif';
import spin from '../../assets/Boardgames/spin.gif';
import MainHOC from '../MainHOC';
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
import { useNavigate } from 'react-router-dom';
import Cookies from 'js-cookie';
const months = [
'January',
'February',
Expand All @@ -31,6 +33,18 @@ const months = [
function Event() {
const [events, setEvents] = useState([]);
const [error, setError] = useState(null);
const navigate = useNavigate();



const handleRegisterClick = () => {
const isAuthenticated = Boolean(Cookies.get('authToken'));

if (!isAuthenticated) {
alert("Please sign in to register for the event.");
navigate('/login');
}
};
useEffect(() => {
const fetchData = async () => {
try {
Expand Down Expand Up @@ -183,7 +197,7 @@ function Event() {
))}
</div>
<div className="text-center mt-4">
<button className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
<button onClick={handleRegisterClick} className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
Register for Event
</button>
</div>
Expand Down

0 comments on commit 4704cdd

Please sign in to comment.