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

Implement all improvement given in class #2

Open
wants to merge 1 commit 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.env
5 changes: 3 additions & 2 deletions auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ function auth(req, res, next) {

const response = jwt.verify(token, JWT_SECRET);


if (response) {
req.userId = token.userId;
req.userId = response.userId;
next();
} else {
res.status(403).json({
message: "Incorrect creds"
message: "Incorrect credentials"
})
}
}
Expand Down
31 changes: 23 additions & 8 deletions db.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
const mongoose = require("mongoose");

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const User = new Schema({
name: String,
email: {type: String, unique: true},
password: String
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
minlength: [6, 'Password must be at least 6 characters long'],
}
}, {
timestamps: true
});

const Todo = new Schema({
userId: ObjectId,
title: String,
done: Boolean
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: String,
done: { type: Boolean, default: false }
}, {
timestamps: true
});

const UserModel = mongoose.model('users', User);
const TodoModel = mongoose.model('todos', Todo);

module.exports = {
UserModel,
TodoModel
UserModel,
TodoModel
}
219 changes: 169 additions & 50 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,83 +1,202 @@
const express = require("express");
const mongoose = require("mongoose");
const { UserModel, TodoModel } = require("./db");
const { auth, JWT_SECRET } = require("./auth");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
require("dotenv").config();

mongoose.connect(process.env.MONGODB_URI)
.then(() => {
console.log('Successfully connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});

mongoose.connect("")

const app = express();
app.use(express.json());

app.post("/signup", async function(req, res) {
const email = req.body.email;
const password = req.body.password;
const name = req.body.name;
app.post("/signup", async function (req, res) {
const { email, password, name } = req.body;

await UserModel.create({
email: email,
password: password,
name: name
});

res.json({
message: "You are signed up"
})
if (!email || !password) {
return res.status(400).json({
message: "Email and password are required"
});
}

try {
// Check if email already exists
const existingUser = await UserModel.findOne({ email: email });
if (existingUser) {
return res.status(400).json({
message: "Email already exists"
});
}

// Hash password
const hashedPassword = await bcrypt.hash(password, 10);

const newUser = await UserModel.create({
email: email,
password: hashedPassword,
name: name
});

res.status(201).json({
message: "You are signed up",
});
} catch (error) {
console.error(error);
return res.status(500).json({
message: "Internal server error. Please try again later."
});
}
});


app.post("/signin", async function(req, res) {
app.post("/signin", async function (req, res) {
const email = req.body.email;
const password = req.body.password;

const response = await UserModel.findOne({
email: email,
password: password,
});
try {
const foundEmail = await UserModel.findOne({ email: email });

if (!foundEmail) {
return res.status(400).json({
message: "Email not found"
});
}

const matchPassword = await bcrypt.compare(password, foundEmail.password);

if (!matchPassword) {
return res.status(400).json({
message: "Invalid credentials"
});
}

if (matchPassword) {
const token = jwt.sign({
userId: foundEmail._id.toString()
}, JWT_SECRET);

res.json({
token
})
} else {
res.status(403).json({
message: "Incorrect credentials"
})
}
} catch (error) {
console.error(error);
res.status(500).json({
message: 'Internal server error'
});
}
});


app.post("/todo", auth, async function (req, res) {
const userId = req.userId;
const title = req.body.title;
const done = req.body.done;

if (response) {
const token = jwt.sign({
id: response._id.toString()
}, JWT_SECRET);
try {
await TodoModel.create({
userId,
title,
done
});

res.json({
token
})
} else {
res.status(403).json({
message: "Incorrect creds"
message: "Todo created"
})
} catch (error) {
console.error(error);
res.status(500).json({
message: 'Internal server error'
});
}
});

// Mark a todo as done api
app.patch('/todos/:id/done', auth, async (req, res) => {
const todoId = req.params.id;

app.post("/todo", auth, async function(req, res) {
const userId = req.userId;
const title = req.body.title;
const done = req.body.done;
try {
const updatedTodo = await TodoModel.findByIdAndUpdate(
todoId,
{ done: true },
{ new: true }
);

await TodoModel.create({
userId,
title,
done
});
if (!updatedTodo) {
return res.status(404).json({
message: 'Todo not found'
});
}

res.json({
message: "Todo created"
})
res.json({
message: 'Todo marked as done',
todo: updatedTodo
});
} catch (error) {
console.error(error);
res.status(500).json({
message: 'Internal server error'
});
}
});

// Endpoint to mark a todo as not done (undo)
app.patch('/todos/:id/undone', async (req, res) => {
const todoId = req.params.id;

app.get("/todos", auth, async function(req, res) {
const userId = req.userId;
try {
const updatedTodo = await TodoModel.findByIdAndUpdate(
todoId,
{ done: false },
{ new: true }
);

const todos = await TodoModel.find({
userId
});
if (!updatedTodo) {
return res.status(404).json({
message: 'Todo not found'
});
}

res.json({
todos
})
res.json({
message: 'Todo marked as not done',
todo: updatedTodo
});
} catch (error) {
console.error(error);
res.status(500).json({
message: 'Internal server error'
});
}
});


app.get("/todos", auth, async function (req, res) {
const userId = req.userId;
try {
const todos = await TodoModel.find({ userId });
res.status(200).json({
todos
});
} catch (error) {
console.error(error);
res.status(500).json({
message: 'Internal server error'
});
}
});

app.listen(3000);
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
Loading