-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodbtest.js
77 lines (71 loc) · 1.51 KB
/
mongodbtest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const { UserModel, TodoModel } = require("./db");
const jwt = require("jsonwebtoken");
const JWT_SECERT = "JOKER";
mongoose.connect(
"mongodb+srv://admin:admin%[email protected]/todo-app-aadi_DB",
);
app.use(express.json());
app.post("/signup", async function (req, res) {
const { email, password, name } = req.body;
await UserModel.create({
email,
password,
name,
});
res.json({
msg: "You are sighned up successfully",
});
});
app.post("/signin", async function (req, res) {
const { email, password } = req.body;
const user = await UserModel.findOne({ email, password });
if (user) {
const token = jwt.sign(
{
id: user._id.toString(),
},
JWT_SECERT,
);
res.json({
token: token,
});
} else {
res.json({
message: "Invalid Credentials",
});
}
});
function Auth(req, res, next) {
const token = req.headers.token;
const decodedData = jwt.verify(token, JWT_SECERT);
if (decodedData) {
req.userId = decodedData.id;
next();
} else {
res.status(403).json({
message: "Invalid Token",
});
}
}
app.post("/todo", Auth, async function (req, res) {
const UserId = req.userId;
const { title } = req.body;
await TodoModel.create({
title,
UserId,
});
res.json({
userId: UserId,
});
});
app.get("/todos", Auth, async function (req, res) {
const userId = req.userId;
const todos = await TodoModel.find({ UserId: userId });
res.json({
todos,
});
});
app.listen(3000);