Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: routes are Secured in wrong Way And Causing a Lot of problem #356 #369

Merged
merged 3 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions server/config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/studentLoginInfo');
const Canteen = require('../models/canteenLoginInfo');

passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
},
async (accessToken, refreshToken, profile, done) => {
try {
let user = await User.findOne({ googleId: profile.id });
if (!user) {
user = await User.create({
googleId: profile.id,
name: profile.displayName,
email: profile.emails[0].value,
});
}
return done(null, user);
} catch (error) {
return done(error, null);
}
}));

passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (error) {
done(error, null);
}
});

module.exports = passport;
40 changes: 31 additions & 9 deletions server/controllers/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ exports.studentSignup = async (req, res) => {
console.log("This is jwt", process.env.JWT_SECRET);
try {
console.log(req.body);
const { name, email, collegeName, accountType, password, confirmPassword } =
await req.body;
const { name, email, collegeName, accountType, password, confirmPassword } = req.body;

if (password !== confirmPassword) {
return res.status(400).json({
Expand All @@ -28,14 +27,12 @@ exports.studentSignup = async (req, res) => {
});
}

const existingUser = await User.findOne({
email,
});
const existingUser = await User.findOne({ email });

if (existingUser) {
return res.status(400).json({
success: false,
message: "User alredy exist",
message: "User already exists",
});
}

Expand All @@ -59,17 +56,42 @@ exports.studentSignup = async (req, res) => {
password: hashedPassword,
});

await user.save();
const payload = {
email: user.email,
id: user._id,
accountType: user.accountType,
};

let token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "2h",
});

// creating a session
const session = new Session({
userId: user._id,
token,
});
await session.save();

user.password = undefined;

res.cookie("token", token, {
httpOnly: true,
secure: true,
maxAge: 3600000,
});

return res.status(200).json({
success: true,
message: "User created succesfully",
message: "User created successfully",
token,
user,
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "USer can not be registred",
message: "User cannot be registered",
});
}
};
Expand Down
74 changes: 58 additions & 16 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import './App.css';
import { Route, Routes } from 'react-router-dom';
import { Route, Routes, Navigate } from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import Signup from './pages/Signup';
Expand All @@ -14,13 +14,9 @@ import Loader from './components/Loader/Loader';
import ForgotPassword from './pages/ForgotPassword';
import ResetPassword from './pages/ResetPassword';
import { ThemeProvider } from './themeContext';

import ContactUs from './pages/ContactUs';

import { AuthProvider } from './authContext'
import EditProfile from './pages/EditProfile';


const Layout = ({ children }) => {
return (
<div className="bg-cover bg-center min-h-screen bg-gradient-to-t from-blue-950 via-blue-950 to-gray-900 bg-no-repeat dark:bg-none">
Expand All @@ -30,32 +26,78 @@ const Layout = ({ children }) => {
};

function App() {
const usertoken = localStorage.getItem('usertoken');
const token = localStorage.getItem('token');
const canteenId = localStorage.getItem('canteenId');
const hasAnyToken = token || usertoken;

// Check if either token is undefined and redirect to login if true
if (usertoken === undefined || token === undefined) {
localStorage.removeItem('usertoken');
localStorage.removeItem('token');
window.location.href = "/login"; // Redirect to login page
return null; // Render nothing else
}

return (
<AuthProvider>
<ThemeProvider>
<div className=''>
<Routes>
<Route path='/' element={<Login />} />
<Route path='/home' element={<Layout><Home /></Layout>} />
<Route path='/forgotPassword' element={<ForgotPassword />} />
<Route path='/api/v1/newPassword/:id/:token' element={<ResetPassword />} />
<Route path='/login' element={<Login />} />
<Route path='/signup' element={<Signup />} />
<Route path='/contact' element={<ContactUs />} />

<Route path='/forgotPassword' element={<ForgotPassword/>} />
<Route path='/api/v1/newPassword/:id/:token' element={<ResetPassword/>} />
{token ? (
<Route path='/section/:_id' element={<Layout><SectionPage /></Layout>} />
) : (
<Route path='/section/:_id' element={<Navigate to='/' />} />
)}

{token ? (
<Route path='/edit-profile/:_id' element={<Layout><EditProfile /></Layout>} />
) : (
<Route path='/edit-profile/:_id' element={<Navigate to='/' />} />
)}

{usertoken ? (
<Route path='/home' element={<Layout><Home /></Layout>} />
) : (
<Route path='/home' element={<Navigate to='/' />} />
)}

{usertoken ? (
<Route path='/menu/:_id' element={<Layout><MenuPage /></Layout>} />
) : (
<Route path='/menu/:_id' element={<Navigate to='/' />} />
)}

{hasAnyToken ? (
<Route path='/about' element={<Layout><About /></Layout>} />
) : (
<Route path='/about' element={token ? <Navigate to={`/section/${canteenId}`} /> : <Navigate to='/home' />} />
)}

{hasAnyToken ? (
<Route path='/rateus' element={<Layout><Rateus /></Layout>} />
) : (
<Route path='/rateus' element={token ? <Navigate to={`/section/${canteenId}`} /> : <Navigate to='/home' />} />
)}

{hasAnyToken ? (
<Route path='/news' element={<Layout><News /></Layout>} />
) : (
<Route path='/news' element={token ? <Navigate to={`/section/${canteenId}`} /> : <Navigate to='/home' />} />
)}

<Route path='/about' element={<Layout><About /></Layout>} />
<Route path='/rateus' element={<Layout><Rateus /></Layout>} />
<Route path='/section/:_id' element={<Layout><SectionPage /></Layout>} />
<Route path="/menu/:_id" element={<Layout><MenuPage /></Layout>} />
<Route path='/news' element={<Layout><News /></Layout>} />
<Route path='/loader' element={<Layout><Loader /></Layout>} />
<Route path="/edit-profile/:_id" element={<Layout><EditProfile /></Layout>} />

<Route path="*" element={<Layout><NotFound /></Layout>} />
</Routes>
</div>
</ThemeProvider>
</AuthProvider>
);
}

Expand Down
24 changes: 24 additions & 0 deletions src/components/Modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Modal.js
import React from 'react';

const Modal = ({ show, onClose, children }) => {
if (!show) {
return null;
}

return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 rounded shadow-lg w-80">
<button
className="absolute top-2 right-2 text-gray-600 hover:text-gray-800"
onClick={onClose}
>
&times;
</button>
{children}
</div>
</div>
);
};

export default Modal;
2 changes: 1 addition & 1 deletion src/pages/About.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { useNavigate } from "react-router-dom";

const About = () => {
const navigate = useNavigate()
const { isAuthenticated } = localStorage.getItem('token');
// const { isAuthenticated } = localStorage.getItem('token');
const [loading,setLoading] = useState(false);

useEffect(() => {
Expand Down
19 changes: 10 additions & 9 deletions src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,11 @@ function Login() {
async function submitHandler(event) {
event.preventDefault();

// const apiUrl =
// formData.accountType === "User"
// ? `${process.env.REACT_APP_BASE_URL}/studentLogin`
// : `${process.env.REACT_APP_BASE_URL}/canteenLogin`;
const apiUrl =
formData.accountType === "User"
? `${process.env.REACT_APP_BASE_URL}/studentLogin`
: `${process.env.REACT_APP_BASE_URL}/canteenLogin`;

const apiUrl = 'http://localhost:8000/api/v1/studentLogin'

try {
const response = await axios.post(apiUrl, formData);
Expand All @@ -75,14 +74,16 @@ function Login() {
}

if (formData.accountType === "User") {

navigate("/home");
localStorage.setItem("token", response.data.token);
localStorage.setItem("usertoken", response.data.token)
window.location.href='/home'



} else {
localStorage.setItem("canteenId", response.data.cantId);
localStorage.setItem("token", response.data.token);

navigate(`/section/${response.data.cantId}`);
window.location.href=`/section/${response.data.cantId}`;

}

Expand Down
6 changes: 1 addition & 5 deletions src/pages/News.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ function News() {
const [articles, setArticles] = useState([]);
const [loading, setLoading] = useState(false);

useEffect(() => {
if(!isAuthenticated){
navigate('/')
}
}, [])


const fetchNews = async (query) => {
try {
Expand Down
14 changes: 8 additions & 6 deletions src/pages/Signup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,14 @@ function Signup() {
toast.success("Account Created Successfully!");

if (formData.accountType === "User") {
navigate("/");
} else {
const token = response.data.token;
localStorage.setItem("token", token);
localStorage.setItem("canteenId", response.data.cantId);
navigate(`/section/${response.data.cantId}`);
localStorage.setItem("usertoken", response.data.token);
window.location.href="/home";
}
if (formData.accountType === "Canteen") {
localStorage.setItem("userId", response.data.user);
localStorage.setItem("token", response.data.token);
window.location.href=`/section/${response.data.cantId}`;

}
} catch (error) {
const errorMessage = error.response?.data?.message || "Failed to create account. Please try again.";
Expand Down