forked from PriyaGhosal/BuddyTrail
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
1 parent
533ff1a
commit d8d4390
Showing
11 changed files
with
1,373 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.env |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' }); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |