Skip to content

Commit

Permalink
Merge pull request #331 from divyansh-2005/intial-backend
Browse files Browse the repository at this point in the history
Initial backed
  • Loading branch information
SUGAM-ARORA authored Jun 19, 2024
2 parents c2baf0f + b45458d commit 0d8e66e
Show file tree
Hide file tree
Showing 8 changed files with 1,614 additions and 0 deletions.
19 changes: 19 additions & 0 deletions BACKEND/.gitignore
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
107 changes: 107 additions & 0 deletions BACKEND/README.md
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.


28 changes: 28 additions & 0 deletions BACKEND/index.js
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}`);
});
17 changes: 17 additions & 0 deletions BACKEND/middleware/auth.js
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;
26 changes: 26 additions & 0 deletions BACKEND/models/user.js
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;
Loading

0 comments on commit 0d8e66e

Please sign in to comment.