-
Notifications
You must be signed in to change notification settings - Fork 119
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #331 from divyansh-2005/intial-backend
Initial backed
- Loading branch information
Showing
8 changed files
with
1,614 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,19 @@ | ||
# Node.js dependencies | ||
node_modules/ | ||
|
||
# Logs | ||
logs/ | ||
*.log | ||
|
||
# Environment variables | ||
.env | ||
|
||
# Optional npm cache directory | ||
.npm/ | ||
|
||
# Optional eslint cache | ||
.eslintcache | ||
|
||
# Operating system files | ||
.DS_Store | ||
Thumbs.db |
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,107 @@ | ||
## Backend | ||
Uses Express js | ||
|
||
## Features | ||
|
||
- User Sign-Up | ||
- User Login | ||
- User Logout | ||
- Protected Routes | ||
|
||
|
||
### Installation | ||
|
||
1. **Clone the repository:** | ||
|
||
```bash | ||
git clone https://github.com/SUGAM-ARORA/UniCollab | ||
cd backend | ||
``` | ||
|
||
2. **Install dependencies:** | ||
|
||
```bash | ||
npm install | ||
``` | ||
|
||
3. **Create a `.env` file in the root directory with the following contents:** | ||
|
||
```env | ||
PORT=5000 | ||
MONGODB_URI=mongodb://localhost:27017/mydatabase | ||
JWT_SECRET=your_jwt_secret | ||
``` | ||
|
||
4. **Start the application:** | ||
|
||
```bash | ||
node index.js | ||
``` | ||
|
||
The server will start on `http://localhost:5000`. | ||
|
||
### API Endpoints | ||
|
||
- **Sign-Up** | ||
|
||
``` | ||
POST /auth/signup | ||
``` | ||
|
||
**Body:** | ||
```json | ||
{ | ||
"username": "yourusername", | ||
"email": "your.email@example.com", | ||
"password": "yourpassword" | ||
} | ||
``` | ||
|
||
- **Login** | ||
|
||
``` | ||
POST /auth/login | ||
``` | ||
|
||
**Body:** | ||
```json | ||
{ | ||
"email": "your.email@example.com", | ||
"password": "yourpassword" | ||
} | ||
``` | ||
|
||
**Response:** | ||
- Sets a cookie named `token` with the JWT. | ||
|
||
- **Logout** | ||
|
||
``` | ||
POST /auth/logout | ||
``` | ||
|
||
**Response:** | ||
- Clears the `token` cookie. | ||
|
||
- **Protected Route** | ||
|
||
``` | ||
GET /protected | ||
``` | ||
|
||
**Headers:** | ||
- Requires `token` cookie set. | ||
|
||
**Response:** | ||
```json | ||
{ | ||
"message": "Hello <username>, this is a protected route." | ||
} | ||
``` | ||
|
||
|
||
## Contributing | ||
|
||
Contributions are welcome! Please open an issue or submit a pull request if you would like to contribute. | ||
|
||
|
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,28 @@ | ||
require('dotenv').config(); | ||
const express = require('express'); | ||
const mongoose = require('mongoose'); | ||
const cookieParser = require('cookie-parser'); | ||
|
||
const app = express(); | ||
const port = process.env.PORT || 5000; | ||
|
||
app.use(express.json()); | ||
app.use(express.urlencoded({ extended: true })); | ||
app.use(cookieParser()); | ||
|
||
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) | ||
.then(() => console.log('MongoDB connected')) | ||
.catch(err => console.error('MongoDB connection error:', err)); | ||
|
||
const authRoutes = require('./routes/auth'); | ||
const authMiddleware = require('./middleware/auth'); | ||
|
||
app.use('/auth', authRoutes); | ||
|
||
app.get('/protected', authMiddleware, (req, res) => { | ||
res.send(`Hello ${req.user.username}, this is a protected route.`); | ||
}); | ||
|
||
app.listen(port, () => { | ||
console.log(`Server is running on http://localhost:${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,17 @@ | ||
const jwt = require('jsonwebtoken'); | ||
const User = require('../models/user'); | ||
|
||
const auth = async (req, res, next) => { | ||
const token = req.cookies.token; | ||
if (!token) return res.status(401).send('Access denied. No token provided.'); | ||
|
||
try { | ||
const decoded = jwt.verify(token, process.env.JWT_SECRET); | ||
req.user = await User.findById(decoded.id); | ||
next(); | ||
} catch (ex) { | ||
res.status(400).send('Invalid token.'); | ||
} | ||
}; | ||
|
||
module.exports = auth; |
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,26 @@ | ||
const mongoose = require('mongoose'); | ||
const bcrypt = require('bcryptjs'); | ||
|
||
const userSchema = new mongoose.Schema({ | ||
username: { type: String, required: true, unique: true }, | ||
email: { type: String, required: true, unique: true }, | ||
password: { type: String, required: true } | ||
}); | ||
|
||
userSchema.pre('save', async function (next) { | ||
if (!this.isModified('password')) return next(); | ||
try { | ||
const salt = await bcrypt.genSalt(10); | ||
this.password = await bcrypt.hash(this.password, salt); | ||
next(); | ||
} catch (error) { | ||
next(error); | ||
} | ||
}); | ||
|
||
userSchema.methods.comparePassword = function (candidatePassword) { | ||
return bcrypt.compare(candidatePassword, this.password); | ||
}; | ||
|
||
const User = mongoose.model('User', userSchema); | ||
module.exports = User; |
Oops, something went wrong.