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

Integrated backend with frontend login and register functionality #43

Merged
merged 3 commits into from
Oct 3, 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
1 change: 1 addition & 0 deletions backend/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const config = {
port: process.env.PORT || 3000,
mongodbUri: process.env.MONGODB_URI,
jwtSecret: process.env.JWT_SECRET,
nodeEnv: process.env.NODE_ENV,
};

export default config;
3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@
"whatwg-url": "^13.0.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"keywords": [],
"author": "",
Expand Down
4 changes: 2 additions & 2 deletions backend/utils/authFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export const verifyToken = async (token) => {
export const addCookie = (res, name, value) => {
res.cookie(name, value, {
httpOnly: true,
secure: config.env === 'production',
sameSite: 'none'
secure: true,
sameSite: 'none',
});
}

Expand Down
50 changes: 48 additions & 2 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react'
import React, { useEffect } from 'react'
import Herosection from './Pages/Herosection'
import LoginPage from './Pages/LoginPage';
import Register from './Pages/Register';
Expand All @@ -16,6 +16,12 @@ function App() {
<Route path="/" element={<Herosection />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<Register />} />

{/* This route is just for testing protected routes it can be removed later when there is a route other than login or signup */}
<Route element={<ProtectedRoute />}>
<Route path="/logged-in" element={<div className='flex items-end p-10 justify-center w-screen h-screen'><h1 className='text-7xl text-red-500'>Logged in</h1></div>} />
</Route>

</Routes>
</Router>

Expand All @@ -27,4 +33,44 @@ function App() {
)
}

export default App
export default App;

import { useNavigate, Outlet } from 'react-router-dom';

export function ProtectedRoute() {
const navigate = useNavigate();

// Async function to verify the token
const verifyToken = async () => {
try {
const res = await fetch('http://localhost:3000/auth/verify', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include'
});

const data = await res.json();
console.log('Token Verification error:', data.error); // For debugging

if (data.error || res.status === 400 || res.status === 500) {
navigate('/login');
}

if (res.status === 400 || res.status === 500) {
navigate('/login');
}
} catch (error) {
console.error('Error verifying token:', error);
navigate('/login');
}
};

useEffect(() => {
verifyToken();
}, [navigate]);

// If everything is fine, render the protected content
return <Outlet />;
}
51 changes: 43 additions & 8 deletions frontend/src/Pages/LoginPage.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,48 @@
import React, { useState } from 'react';
import logo from '../assets/stationsaarthi.svg'; // Import your logo
import { useNavigate } from 'react-router-dom';

const Login = () => {
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

const navigate = useNavigate();

const handleLogin = (e) => {
e.preventDefault();
// Handle login logic

// Fetch the login API from the backend
fetch('http://localhost:3000/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password
}),
credentials: 'include'
})
.then(res => {
// Check if the response is OK (status 200-299)
if (res.ok) {
return res.json(); // Parse the JSON data if response is successful
} else {
// If the response is not OK, throw an error to be caught later
throw new Error(`Login failed! Status: ${res.status}`);
}
})
.then(data => {
// Handle the response data if login is successful
console.log('Login successful:', data);
setTimeout(() => {
navigate('/logged-in');
}, 500); // Short delay to allow the cookie to propagate
})
.catch(error => {
// Handle errors like incorrect login or network issues
console.error('Login failed:', error);
});
};

return (
Expand All @@ -21,15 +56,15 @@ const Login = () => {

{/* Login Form */}
<form onSubmit={handleLogin} className="bg-white p-8 rounded-lg shadow-lg w-full max-w-md">
{/* Username Input */}
{/* Email Input */}
<div className="mb-6">
<label className="block text-gray-700 font-semibold mb-2" htmlFor="username">Username</label>
<label className="block text-gray-700 font-semibold mb-2" htmlFor="email">Email</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter your username"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300"
required
/>
Expand Down
42 changes: 40 additions & 2 deletions frontend/src/Pages/Register.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import logo from '../assets/stationsaarthi.svg'; // Import your logo

const Register = () => {
Expand All @@ -7,9 +8,46 @@ const Register = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

const navigate = useNavigate();

const handleRegister = (e) => {
e.preventDefault();
// Handle registration logic here

// Fetch the register API from the backend
fetch('http://localhost:3000/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
phoneNumber,
email,
password
}),
credentials: 'include'
})
.then(res => {
// Check if the response is OK (status 200-299)
if (res.ok) {
// If the response is successful, return the JSON data
return res.json();
} else {
// If the response is not OK, throw an error to be caught later
throw new Error(`HTTP error! status: ${res.status}`);
}
})
.then(data => {
// Handle the response data if successful
console.log('Registration successful:', data);
setTimeout(() => {
navigate('/logged-in');
}, 500); // Short delay to allow the cookie to propagate
})
.catch(error => {
// Handle errors such as invalid response or network issues
console.error('Registration failed:', error);
});
};

return (
Expand Down Expand Up @@ -99,4 +137,4 @@ const Register = () => {
);
};

export default Register;
export default Register;
Loading