Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solved all the assignments of middlewares of week-4 #91

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions week-4/hard/database/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();

// Connect to MongoDB
mongoose.connect('your-mongodb-url');

// Define schemas
mongoose.connect(process.env.MONGODB_URL)
.then(() => console.log("Connected to MongoDB"))
.catch((error) => console.error("MongoDB connection error:", error));

// Defining user schemas
const UserSchema = new mongoose.Schema({
// Schema definition here
username: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});

// Defining todo schemas
const TodoSchema = new mongoose.Schema({
// Schema definition here
description: { type: String, required: true },
complete: { type: Boolean, default: false },
userid: { type: mongoose.Schema.ObjectId, ref: 'User' }
});

const User = mongoose.model('User', UserSchema);
Expand All @@ -19,4 +27,4 @@ const Todo = mongoose.model('Todo', TodoSchema);
module.exports = {
User,
Todo
}
};
103 changes: 98 additions & 5 deletions week-4/hard/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,108 @@
const express = require("express");
const dotenv = require("dotenv");
dotenv.config();

const { z } = require('zod');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const app = express();
const port = process.env.PORT;
const { User, Todo } = require('./database/index');
const auth = require('./middleware/user');

app.use(express.json());

app.get("/healthy", (req, res)=> res.send("I am Healthy"));
app.get("/healthy", (req, res) => res.send("I am Healthy"));

// POST endpoint to signup
app.post('/signup', async (req, res) => {
const requiredBody = z.object({
username: z.string().min(3).max(32),
email: z.string().min(5).max(50).email(),
password: z.string().min(6).max(100).regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%&*-])[A-Za-z\d!@#$%&*-]{8,}$/)
});

const requiredDataBody = requiredBody.safeParse(req.body);

if (!requiredDataBody.success) {
return res.status(403).json({
msg: "Incorrect credential",
error: requiredDataBody.error
});
}

const { username, email, password } = req.body;

const userExistOrNot = await User.findOne({ email });

if (userExistOrNot) {
return res.status(409).json({
msg: `User already exists with this email: ${email}`
});
}

const hashPassword = await bcrypt.hash(password, 10);

try {
await User.create({ username, email, password: hashPassword });
res.status(201).json({ msg: "Account created successfully" });
} catch (error) {
res.status(500).json({ msg: error.message });
}
});

// POST endpoint to signin
app.post('/signin', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(403).json({ msg: "Please provide email and password" });
}

try {
const user = await User.findOne({ email });

if (!user) {
return res.status(404).json({ msg: `User does not exist with this email: ${email}` });
}

const passMatch = await bcrypt.compare(password, user.password);
if (passMatch) {
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
return res.status(200).json({ token });
} else {
return res.status(403).json({ msg: "Password is incorrect" });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});

// POST endpoint to add todo
app.post('/todo', auth, async (req, res) => {
const { description, completed } = req.body;
const id = req.id;

if (description === undefined || completed === undefined) {
return res.status(400).json({ msg: "Please provide description and completed" });
}

try {
await Todo.create({ description, complete: completed, userid: id });
res.status(201).json({ msg: "Todo added successfully" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});

// start writing your routes here
// GET endpoint to get all todos
app.get('/todos', auth, async (req, res) => {
const id = req.id;

app.listen(port, ()=> console.log(`server is running at http://localhost:${port}`));
try {
const userTodos = await Todo.find({ userid: id });
res.status(200).json(userTodos);
} catch (error) {
res.status(500).json({ msg: error.message });
}
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
23 changes: 21 additions & 2 deletions week-4/hard/middleware/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');

dotenv.config();

function userMiddleware(req, res, next) {
// Implement user auth logic
const token = req.headers.token;
if (!token) {
return res.status(403).json({
msg: "Access token is missing"
});
}
try {
const verified = jwt.verify(token, process.env.JWT_SECRET);
req.id = verified.id;
next();
} catch (error) {
res.status(401).json({
error: "Invalid token"
});
}
}

module.exports = userMiddleware;
module.exports = userMiddleware;
Loading