Skip to content

Commit

Permalink
Merge pull request #260 from visharma14/main
Browse files Browse the repository at this point in the history
Task Management api
  • Loading branch information
Open-Source-you authored Oct 30, 2024
2 parents 1ee6f4a + 0ec88a5 commit 6366fc6
Show file tree
Hide file tree
Showing 13 changed files with 228 additions and 5 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ A month-long celebration from October 1st to October 31st presented by [Digital
[https://hacktoberfest.digitalocean.com/](https://hacktoberfest.digitalocean.com/)

## Rules :fire:
To qualify for the __official limited edition Hacktoberfest shirt__, you must register [here](https://hacktoberfest.digitalocean.com/) and make four Pull Requests (PRs) between October 1-31, 2022 (in any time zone). PRs can be made to any public repository on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the __first 40,000__ participants who complete the challenge will earn a T-shirt.
To qualify for the __official limited edition Hacktoberfest shirt__, you must register [here](https://hacktoberfest.digitalocean.com/) and make four Pull Requests (PRs) between October 1-31, 2024 (in any time zone). PRs can be made to any public repository on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the __first 40,000__ participants who complete the challenge will earn a T-shirt.

## Steps to follow :scroll:

Expand All @@ -46,7 +46,7 @@ Star the repository by pressing the topmost-right button to start your wonderful

### 2. Fork it :fork_and_knife:

You can get your own fork/copy of [HacktoberFest-2024](https://github.com/Open-Source-you/Hackotberfest2022 by using the <a href="https://github.com/Open-Source-you/HacktoberFest2022/new/master?readme=1#fork-destination-box"><kbd><b>Fork</b></kbd></a> button.
You can get your own fork/copy of [HacktoberFest-2024](https://github.com/Open-Source-you/Hackotberfest2024 by using the <a href="https://github.com/Open-Source-you/HacktoberFest2024/new/master?readme=1#fork-destination-box"><kbd><b>Fork</b></kbd></a> button.


### 3. Clone it :busts_in_silhouette:
Expand All @@ -56,15 +56,15 @@ You can get your own fork/copy of [HacktoberFest-2024](https://github.com/Open-S
You need to clone or (download) it to local machine using

```sh
$ git clone https://github.com/Open-Source-you/Hackotberfest2022.git
$ git clone https://github.com/Open-Source-you/Hackotberfest2024.git
```

> This makes a local copy of the repository in your machine.
Once you have cloned the `Hacktoberfest-2024` repository in Github, move to that folder first using change directory command on Linux, Mac, and Windows(PowerShell to be used).

```sh
# This will change directory to a folder Hacktoberfest-2024
$ cd Hackotberfest2022
$ cd Hackotberfest2024
```

Move to this folder for all other commands.
Expand Down Expand Up @@ -122,7 +122,7 @@ $ git push origin main

### 6. Ready Steady Go... :turtle: :rabbit2:

Once you have completed these steps, you are ready to start contributing by checking our `Good First Issue` Issues and creating [pull requests](https://github.com/kishanrajput23/Hacktoberfest-2022/pulls).
Once you have completed these steps, you are ready to start contributing by checking our `Good First Issue` Issues and creating [pull requests](https://github.com/kishanrajput23/Hacktoberfest-2024/pulls).

### 7. Create a new branch :bangbang:

Expand Down
3 changes: 3 additions & 0 deletions TaskManagementApi/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.env
package-lock.json
14 changes: 14 additions & 0 deletions TaskManagementApi/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const express = require('express');
const bodyParser = require('body-parser');
const authRoutes = require('./routes/authRoutes');
const taskRoutes = require('./routes/taskRoutes');
const app = express();

app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/tasks', taskRoutes);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
18 changes: 18 additions & 0 deletions TaskManagementApi/config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const mysql = require('mysql2');
const dotenv = require('dotenv');

dotenv.config();

const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});

db.connect(err => {
if (err) throw err;
console.log('Database connected!');
});

module.exports = db;
29 changes: 29 additions & 0 deletions TaskManagementApi/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/user');

const register = (req, res) => {
const { username, password } = req.body;
const hashedPassword = bcrypt.hashSync(password, 10);

User.create(username, hashedPassword, (err, result) => {
if (err) return res.status(500).json(err);
res.status(201).json({ message: 'User created successfully!',result });
});
};

const login = (req, res) => {
const { username, password } = req.body;

User.findByUsername(username, (err, user) => {
if (err || !user) return res.status(404).json({ message: 'User not found!' });

const validPassword = bcrypt.compareSync(password, user.password);
if (!validPassword) return res.status(401).json({ message: 'Invalid password!' });

const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET);
res.json({ token });
});
};

module.exports = { register, login };
52 changes: 52 additions & 0 deletions TaskManagementApi/controllers/taskController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const Task = require('../models/task');

const createTask = (req, res) => {
const { title, description, userId } = req.body;

Task.create(title, description, userId, (err, result) => {
if (err) return res.status(500).json(err);
res.status(201).json({ message: 'Task created successfully!' });
});
};

const getTasks = (req, res) => {
const userId = req.user.id; // Assume user ID is added to req by auth middleware

Task.findAll(userId, (err, tasks) => {
if (err) return res.status(500).json(err);
res.json(tasks);
});
};

// Add updateTask and deleteTask similarly

const updateTask = (req, res) => {
const taskId = req.params.id; // Get the task ID from the request parameters
const { title, description } = req.body; // Extract title and description from the request body

// Validate if the taskId and required fields are provided
if (!taskId) {
return res.status(400).json({ message: "Task ID is required." });
}

Task.update(taskId, title, description, (err, result) => {
if (err) return res.status(500).json(err);

if (result.affectedRows === 0) {
return res.status(404).json({ message: "Task not found." });
}

res.json({ message: "Task updated successfully!" });
});
};

const deleteTasks = (req,res)=>{
const taskId = req.user.id;

Task.delete(taskId, (err, tasks) => {
if(err) return res.status(500).json(err);
res.json(tasks);
});
}

module.exports = { createTask, getTasks,updateTasks,deleteTasks };
15 changes: 15 additions & 0 deletions TaskManagementApi/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const jwt = require('jsonwebtoken');

const authenticate = (req, res, next) => {
const token = req.headers['authorization'];

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

jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) return res.status(401).json({ message: 'Unauthorized!' });
req.user = decoded;
next();
});
};

module.exports = { authenticate };
22 changes: 22 additions & 0 deletions TaskManagementApi/models/task.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const db = require('../config/db');

const Task = {
create: (title, description, userId, callback) => {
const sql = 'INSERT INTO tasks (title, description, user_id) VALUES (?, ?, ?)';
db.query(sql, [title, description, userId], callback);
},
findAll: (userId, callback) => {
const sql = 'SELECT * FROM tasks WHERE user_id = ?';
db.query(sql, [userId], callback);
},
update: (id, title, description, callback) => {
const sql = 'UPDATE tasks SET title = ?, description = ? WHERE id = ?';
db.query(sql, [title, description, id], callback);
},
delete: (id, callback) => {
const sql = 'DELETE FROM tasks WHERE id = ?';
db.query(sql, [id], callback);
},
};

module.exports = Task;
14 changes: 14 additions & 0 deletions TaskManagementApi/models/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const db = require('../config/db');

const User = {
create: (username, password, callback) => {
const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';
db.query(sql, [username, password], callback);
},
findByUsername: (username, callback) => {
const sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [username], callback);
},
};

module.exports = User;
23 changes: 23 additions & 0 deletions TaskManagementApi/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "task-management-api",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"dev": "nodemon app.js"

},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcrypt": "^5.1.1",
"body-parser": "^1.20.3",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"jsonwebtoken": "^9.0.2",
"mysql2": "^3.11.3"
}
}
8 changes: 8 additions & 0 deletions TaskManagementApi/routes/authRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const express = require('express');
const { register, login } = require('../controllers/authcontroller');
const router = express.Router();

router.post('/register', register);
router.post('/login', login);

module.exports = router;
11 changes: 11 additions & 0 deletions TaskManagementApi/routes/taskRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const express = require('express');
const { createTask, getTasks, updateTasks, deleteTasks } = require('../controllers/taskController');
const { authenticate } = require('../middlewares/authMiddleware');
const router = express.Router();

router.post('/', authenticate, createTask);
router.get('/', authenticate, getTasks);
router.post('/update', authenticate, updateTasks);
router.post('/delete',authenticate,deleteTasks);

module.exports = router;
14 changes: 14 additions & 0 deletions TaskManagementApi/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const db = require('../config/db');

const User = {
create: (username, password, callback) => {
const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';
db.query(sql, [username, password], callback);
},
findByUsername: (username, callback) => {
const sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [username], callback);
},
};

module.exports = User;

0 comments on commit 6366fc6

Please sign in to comment.