-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (73 loc) · 1.81 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
const express = require("express");
const { UserModel, TodoModel} = require("./db");
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const JWT_SECRET = "asd123";
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;
await UserModel.create({
email: email,
password: password,
name: name
});
res.json({
message: "You have signed-up"
})
});
app.post("/signin", async function (req, res) {
const email = req.body.email;
const password = req.body.password;
const user = await UserModel.findOne({
email: email,
password: password
});
if(user) {
const token = jwt.sign({
userId: user._id.toString()
}, JWT_SECRET);
res.json({
token: token
})
} else {
res.status(403).json({
message: "Incorrect Credentials"
})
}
});
app.post("/todo", auth, function (req, res) {
const userId = req.userId;
const title = req.body.title;
TodoModel.create({
title: title,
userId: userId
});
res.json({
message: "Todo Created"
});
});
app.get("/todos", auth, async function (req, res) {
const userId = req.userId;
const user = await UserModel.find({
userId
})
res.json({
});
});
function auth(req, res, next) {
const token = req.headers.token;
const decodedData = jwt.verify(token, JWT_SECRET);
if(decodedData) {
req.userId = decodedData.userId;
next();
} else {
res.status(403).json({
message: "Incorrect Credentials"
})
}
}
app.listen(3000);