Skip to content

Commit

Permalink
Added backend logic using express
Browse files Browse the repository at this point in the history
tarunkumar2005 committed Oct 18, 2024
1 parent 533ff1a commit d8d4390
Showing 11 changed files with 1,373 additions and 0 deletions.
3 changes: 3 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MONGO_URI=your_mongo_uri
JWT_SECRET=your_jwt_secret
PORT=5000
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
11 changes: 11 additions & 0 deletions backend/config/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const dotenv = require('dotenv');

dotenv.config();

const config = {
mongoURI: process.env.MONGO_URI,
jwtSecret: process.env.JWT_SECRET,
port: process.env.PORT || 5000,
};

module.exports = config;
17 changes: 17 additions & 0 deletions backend/config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose = require('mongoose');
const config = require('./config'); // Import config

const connectDB = async () => {
try {
await mongoose.connect(config.mongoURI, { // Use config for mongoURI
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB connected');
} catch (error) {
console.error('MongoDB connection failed:', error.message);
process.exit(1);
}
};

module.exports = connectDB;
52 changes: 52 additions & 0 deletions backend/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const User = require('../models/User');
const { hashPassword, comparePassword, createToken, addCookie, deleteCookie, verifyToken } = require('../utils/authUtils');

exports.signup = async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await hashPassword(password);
const newUser = new User({ username, password: hashedPassword });

try {
await newUser.save();
const token = createToken(newUser._id); // Create token after user creation
addCookie(res, 'token', token); // Add cookie with the token
res.status(201).json({ message: 'User created' });
} catch (error) {
res.status(400).json({ message: error.message });
}
};

exports.login = async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });

if (!user || !(await comparePassword(password, user.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const token = createToken(user._id);
addCookie(res, 'token', token); // Add cookie with the token
res.status(200).json({ message: 'Login successful' });
};

// Logout function to clear the cookie
exports.logout = (req, res) => {
deleteCookie(res, 'token'); // Clear the token cookie
res.status(200).json({ message: 'Logout successful' });
};

// Verify function to check the token and return user ID
exports.verifyToken = (req, res) => {
const token = req.cookies.token; // Get token from cookies

if (!token) {
return res.status(401).json({ message: 'No token provided' });
}

try {
const decoded = verifyToken(token); // Verify the token
res.status(200).json({ userId: decoded.id }); // Return user ID
} catch (error) {
res.status(401).json({ message: 'Invalid token' });
}
};
24 changes: 24 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const express = require('express');
const connectDB = require('./config/db');
const authRoutes = require('./routes/authRoutes');
const cookieParser = require('cookie-parser');
const config = require('./config/config'); // Import config
const cors = require('cors'); // Import CORS

const app = express();
connectDB();

// CORS configuration
app.use(cors({
origin: 'http://your-frontend-domain.com', // Replace with your frontend URL
credentials: true, // Allow credentials (cookies) to be sent
}));

app.use(express.json());
app.use(cookieParser());
app.use('/api/auth', authRoutes);

const PORT = config.port; // Use config for port
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
8 changes: 8 additions & 0 deletions backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
});

module.exports = mongoose.model('User', userSchema);
1,193 changes: 1,193 additions & 0 deletions backend/package-lock.json

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.7.2"
}
}
11 changes: 11 additions & 0 deletions backend/routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const express = require('express');
const { signup, login, logout, verifyToken } = require('../controllers/authController');

const router = express.Router();

router.post('/signup', signup);
router.post('/login', login);
router.post('/logout', logout);
router.get('/verify', verifyToken); // New verification route

module.exports = router;
32 changes: 32 additions & 0 deletions backend/utils/authUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs'); // Import bcrypt
const config = require('../config/config'); // Import config

exports.createToken = (userId) => {
return jwt.sign({ id: userId }, config.jwtSecret, { expiresIn: '1h' }); // Use config for jwtSecret
};

exports.verifyToken = (token) => {
return jwt.verify(token, config.jwtSecret); // Use config for jwtSecret
};

// New utility function to hash a password
exports.hashPassword = async (password) => {
const salt = await bcrypt.genSalt(10);
return await bcrypt.hash(password, salt);
};

// New utility function to compare a password with a hashed password
exports.comparePassword = async (password, hashedPassword) => {
return await bcrypt.compare(password, hashedPassword);
};

// New utility function to add a cookie
exports.addCookie = (res, name, value, options = {}) => {
res.cookie(name, value, { httpOnly: true, ...options });
};

// New utility function to delete a cookie
exports.deleteCookie = (res, name) => {
res.clearCookie(name);
};

0 comments on commit d8d4390

Please sign in to comment.