Skip to content

Commit

Permalink
login functionality and CORS:
Browse files Browse the repository at this point in the history
- Corrected passport authentication flow for login route.
- Fixed CORS setup to handle credentials in frontend requests.
- Implemented session handling for login and signup at (/signup)and(/login).
- Updated API endpoints to return appropriate error messages and status codes
  • Loading branch information
parassareen4 committed Dec 5, 2024
1 parent ffb20f3 commit b2000a3
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 3 deletions.
1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"express-session": "^1.18.1",
Expand Down
7 changes: 4 additions & 3 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
require('dotenv').config();
const cors = require('cors');

// Passport configuration
require('./config/passportConfig');

const app = express();

// CORS configuration
app.use(cors('*'));

// Middleware
app.use(bodyParser.json());

app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}));

app.use(passport.initialize());
app.use(passport.session());

Expand All @@ -29,7 +31,6 @@ app.use('/api/auth', authRoutes);
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {}).then(() => {
console.log('Connected to MongoDB');

app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});
Expand Down
79 changes: 79 additions & 0 deletions src/Routes/Login/Login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import React, { useState, ChangeEvent, FormEvent } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom"; // Import the hook for navigation

interface LoginFormData {
email: string;
password: string;
}

const Login: React.FC = () => {
const [formData, setFormData] = useState<LoginFormData>({ email: "", password: "" });
const [message, setMessage] = useState<string>("");

const navigate = useNavigate(); // Initialize the navigate hook

const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};

const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
try {
const response = await axios.post(
"http://localhost:5000/api/auth/login", // Backend endpoint
formData,

);
setMessage(response.data.message); // Show success message from backend

// Navigate to /home if login is successful
if (response.data.message === 'Login successful') {
navigate("/home");
}
} catch (error: any) {
setMessage(error.response?.data?.message || "Something went wrong");
}
};

return (
<div className="max-w-md mt-12 mx-auto bg-white p-8 rounded-lg shadow-md">
<h2 className="text-2xl font-semibold text-center mb-6">Login</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<input
type="email"
name="email"
placeholder="Email"
value={formData.email}
onChange={handleChange}
required
className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<input
type="password"
name="password"
placeholder="Password"
value={formData.password}
onChange={handleChange}
required
className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white py-3 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Login
</button>
</form>
{message && <p className="text-center text-red-500 mt-4">{message}</p>}
</div>
);
};

export default Login;

5 changes: 5 additions & 0 deletions src/Routes/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import Home from "../pages/Home/Home"; // Import the Home component
import About from "../pages/About/About"; // Import the About component
import Contact from "../pages/Contact/Contact"; // Import the Contact component
import Contributors from "../pages/Contributors/Contributors";
import Signup from "./Signup/Signup.tsx";
import Login from "./Login/Login.tsx";


const Router = () => {
return (
<Routes>
{/* Redirect from root (/) to the home page */}
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
<Route path="/" element={<Navigate to="/home" replace />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
Expand Down
89 changes: 89 additions & 0 deletions src/Routes/Signup/Signup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React, { useState, ChangeEvent, FormEvent } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

interface SignUpFormData {
username: string;
email: string;
password: string;
}

const SignUp: React.FC = () => {
const [formData, setFormData] = useState<SignUpFormData>({ username: "", email: "", password: "" });
const [message, setMessage] = useState<string>("");

const navigate = useNavigate();

const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};

const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
try {
const response = await axios.post(
"http://localhost:5000/api/auth/signup", // Backend endpoint
formData // Include cookies for session
);
setMessage(response.data.message); // Show success message from backend

// Navigate to login page after successful signup
if (response.data.message === 'User created successfully') {
navigate("/login");
}
} catch (error: any) {
setMessage(error.response?.data?.message || "Something went wrong");
}
};

return (
<div className="mt-12 max-w-md mx-auto bg-white p-8 rounded-lg shadow-md">
<h2 className="text-2xl font-semibold text-center mb-6">Sign Up</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<input
type="text"
name="username"
placeholder="Username"
value={formData.username}
onChange={handleChange}
required
className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<input
type="email"
name="email"
placeholder="Email"
value={formData.email}
onChange={handleChange}
required
className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<input
type="password"
name="password"
placeholder="Password"
value={formData.password}
onChange={handleChange}
required
className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white py-3 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Sign Up
</button>
</form>
{message && <p className="text-center text-red-500 mt-4">{message}</p>}
</div>
);
};

export default SignUp;

0 comments on commit b2000a3

Please sign in to comment.