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

implemeted improvement #1

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 .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MONGO_URI=
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.env
28 changes: 15 additions & 13 deletions auth.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@

const jwt = require("jsonwebtoken");
const JWT_SECRET = "s3cret";

function auth(req, res, next) {
const token = req.headers.authorization;
const token = req.headers.authorization;

const response = jwt.verify(token, JWT_SECRET);
if (!token) {
return res.status(401).json({ message: "No token provided" });
}

if (response) {
req.userId = token.userId;
next();
} else {
res.status(403).json({
message: "Incorrect creds"
})
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.userId = decoded.id;
next();
} catch (error) {
res.status(403).json({ message: "Invalid token" });
}
}

module.exports = {
auth,
JWT_SECRET
}
auth,
JWT_SECRET
};
33 changes: 25 additions & 8 deletions db.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

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,
}
});

User.pre('save', async function(next) {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 10);
}
next();
});

const Todo = new Schema({
userId: ObjectId,
title: String,
done: Boolean
userId: { type: ObjectId, ref: 'User' },
title: String,
done: Boolean,
createdAt: { type: Date, default: Date.now },
dueDate: Date
});

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

module.exports = {
UserModel,
TodoModel
}
UserModel,
TodoModel
};
179 changes: 124 additions & 55 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,81 +3,150 @@ const { UserModel, TodoModel } = require("./db");
const { auth, JWT_SECRET } = require("./auth");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const { z } = require("zod");
const env = require("dotenv")
env.config()

mongoose.connect("")
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.error("Could not connect to MongoDB", err));

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;

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

res.json({
message: "You are signed up"
})
const UserSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
name: z.string()
});

const SignInSchema = z.object({
email: z.string().email(),
password: z.string()
});

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,
});
const TodoSchema = z.object({
title: z.string(),
done: z.boolean(),
dueDate: z.string().datetime().optional()
});

if (response) {
const token = jwt.sign({
id: response._id.toString()
}, JWT_SECRET);
const UpdateTodoSchema = z.object({
done: z.boolean()
});

res.json({
token
})
} else {
res.status(403).json({
message: "Incorrect creds"
})
app.post("/signup", async function (req, res) {
try {
const { email, password, name } = UserSchema.parse(req.body);

const user = new UserModel({
email,
password,
name
});

await user.save();

res.json({ message: "You are signed up" });
} catch (error) {
if (error) {
return res.status(400).json({ message: "Invalid input", errors: error.message });
}
if (error.code === 11000) {
return res.status(400).json({ message: "Email already exists" });
}
res.status(500).json({ message: "An error occurred", error: error.message });
}
});

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

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

if (!user) {
return res.status(403).json({ message: "Incorrect credentials" });
}

const isMatch = await bcrypt.compare(password, user.password);

if (!isMatch) {
return res.status(403).json({ message: "Incorrect credentials" });
}

app.post("/todo", auth, async function(req, res) {
const userId = req.userId;
const title = req.body.title;
const done = req.body.done;
const token = jwt.sign({ id: user._id.toString() }, JWT_SECRET);

await TodoModel.create({
userId,
title,
done
});
res.json({ token });
} catch (error) {
if (error ) {
return res.status(400).json({ message: "Invalid input", errors: error.message });
}
res.status(500).json({ message: "An error occurred", error: error.message });
}
});

res.json({
message: "Todo created"
})
app.post("/todo", auth, async function (req, res) {
try {
const userId = req.userId;
const { title, done, dueDate } = TodoSchema.parse(req.body);

const todo = await TodoModel.create({
userId,
title,
done,
dueDate: dueDate ? new Date(dueDate) : undefined
});

res.json({ message: "Todo created", todo });
} catch (error) {
if (error) {
return res.status(400).json({ message: "Invalid input", errors: error.errors });
}
res.status(500).json({ message: "An error occurred", error: error.message });
}
});

app.get("/todos", auth, async function (req, res) {
try {
const userId = req.userId;

app.get("/todos", auth, async function(req, res) {
const userId = req.userId;
const todos = await TodoModel.find({ userId });

const todos = await TodoModel.find({
userId
});
res.json({ todos });
} catch (error) {
res.status(500).json({ message: "An error occurred", error: error.message });
}
});

res.json({
todos
})
app.put("/todo/:id", auth, async function (req, res) {
try {
const todoId = req.params.id;
const { done } = UpdateTodoSchema.parse(req.body);

const todo = await TodoModel.findOneAndUpdate(
{ _id: todoId, userId: req.userId },
{ done },
{ new: true }
);

if (!todo) {
return res.status(404).json({ message: "Todo not found" });
}

res.json({ message: "Todo updated", todo });
} catch (error) {
if (error) {
return res.status(400).json({ message: "Invalid input", errors: error.message });
}
res.status(500).json({ message: "An error occurred", error: error.message });
}
});

app.listen(3000);
app.use((req, res) => {
res.send("may be wrong route/method")
})

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

Loading