Skip to content

Abhishek(mern) #2

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
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
101 changes: 0 additions & 101 deletions README.md

This file was deleted.

3 changes: 3 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PORT=3000
DB_CONNECT=mongodb+srv://abhisheksathyan483:abhi123@cluster0.rijsl.mongodb.net/
JWT_SECRET=user-secret
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
32 changes: 32 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@



const dotenv = require('dotenv');
dotenv.config(); // to use environment variables
const express = require('express')
const cors = require('cors');

const connectToDb = require('./db/db')
const app = express()

const userRoutes = require('./routes/user.routes');

const producerRoutes = require('./routes/producer.routes');


connectToDb();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true}));


app.use('/users' , userRoutes);
app.use('/producers' , producerRoutes);

app.get('/' , (req , res) => {
res.send("hello world")
});


module.exports = app;
71 changes: 71 additions & 0 deletions backend/controllers/producer.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const Producer = require('../models/producer.model');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

exports.signup = async (req, res) => {
try {
const { name, email, password } = req.body;

console.log("Producer Signup Request:", req.body);

const existingProducer = await Producer.findOne({ email });
if (existingProducer) {
return res.status(400).json({ message: "Producer already exists" });
}

const hashedPassword = await bcrypt.hash(password, 10);
const newProducer = new Producer({ name, email, password: hashedPassword });
await newProducer.save();

const token = jwt.sign({ userId: newProducer._id }, process.env.JWT_SECRET || "secret", {
expiresIn: "1h",
});

res.status(201).json({ message: "Producer created successfully", token });
} catch (error) {
console.error("Signup Error:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
};
exports.login = async (req, res) => {
try {
const { email, password } = req.body;

console.log("Producer Login Request:", req.body);

// Validate input fields
if (!email || !password) {
return res.status(400).json({ message: "Email and password are required" });
}

// Check if producer exists
const existingProducer = await Producer.findOne({ email });
if (!existingProducer) {
return res.status(401).json({ message: "Invalid email or password" });
}

// Validate password
const isPasswordValid = await bcrypt.compare(password, existingProducer.password);
if (!isPasswordValid) {
return res.status(401).json({ message: "Invalid email or password" });
}

// Generate JWT token
const token = jwt.sign(
{ userId: existingProducer._id },
process.env.JWT_SECRET || "your_default_secret", // Ensure a fallback secret
{ expiresIn: "1h" }
);

// Return response with token and user info
res.status(200).json({
message: "Login successful",
token,
user: { id: existingProducer._id, email: existingProducer.email }
});

} catch (error) {
console.error("Login Error:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
};
68 changes: 68 additions & 0 deletions backend/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const User = require('../models/user.model');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

exports.signup = async (req, res) => {
try {
const { name, email, password } = req.body;

console.log("Signup request received:", req.body);

// Check if user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: "User already exists" });
}

// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);

// Create new user
const newUser = new User({
name,
email,
password: hashedPassword
});

// Save user to database
await newUser.save();

// Generate JWT Token
const token = jwt.sign({ userId: newUser._id }, process.env.JWT_SECRET || "your_jwt_secret", { expiresIn: "1h" });

res.status(201).json({ message: "User created successfully", token });
} catch (error) {
console.error("Signup Error:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
};

// User login
exports.login = async (req, res) => {
try {
const { email, password } = req.body;

// Check if user exists
const consumer = await User.findOne({ email });
if (!consumer) {
return res.status(400).json({ message: "Invalid email or password" });
}

// Compare passwords
const isPasswordValid = await bcrypt.compare(password, consumer.password);
if (!isPasswordValid) {
return res.status(400).json({ message: "Invalid email or password" });
}

// Generate JWT token
const token = jwt.sign(
{ consumerId: consumer._id },
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);

res.status(200).json({ token, message: "Login successful" });
} catch (error) {
res.status(500).json({ message: "Server error", error });
}
};
11 changes: 11 additions & 0 deletions backend/db/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const mongoose = require('mongoose');


function connectToDb() {
mongoose.connect(process.env.DB_CONNECT)
.then(() => console.log("Connected to DB"))
.catch(err => console.error("Database connection error:", err));
}


module.exports = connectToDb;
28 changes: 28 additions & 0 deletions backend/models/producer.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const mongoose = require('mongoose');

const producerSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});

const Producer = mongoose.model('Producer', producerSchema);

module.exports = Producer;
28 changes: 28 additions & 0 deletions backend/models/user.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const mongoose = require('mongoose');

const consumerSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});

const Consumer = mongoose.model('Consumer', consumerSchema);

module.exports = Consumer;
Loading