-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex2.js
More file actions
105 lines (89 loc) · 2.07 KB
/
index2.js
File metadata and controls
105 lines (89 loc) · 2.07 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const express = require("express");
const { TodoModel, UserModel } = require("./db2");
const mongoose = require("mongoose");
const { auth, JWT_SECRET } = require("./auth2");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
mongoose.connect("");
const app = express();
app.use(express.json());
const PORT = 3000;
app.post("/signup", async (req, res) => {
const email = req.body.email;
const password = req.body.password;
const name = req.body.name;
const age = req.body.age;
let errorThrown = false;
try {
const hashedPass = await bcrypt.hash(password, 5);
await UserModel.create({
name: name,
age: age,
email: email,
password: hashedPass,
});
} catch (e) {
console.log("Error while entering in the DB");
res.json({
message: "User already exists",
});
errorThrown = true;
}
if (!errorThrown) {
res.json({
message: "You're Signed Up",
});
}
});
app.post("/login", async (req, res) => {
const email = req.body.email;
const password = req.body.password;
const response = await UserModel.findOne({
email: email,
});
if (!response) {
res.status(403).json({
message: "User does not exist in our DB",
});
return;
}
const passwordMatch = await bcrypt.compare(password, response.password);
if (passwordMatch) {
const token = jwt.sign(
{
id: response._id.toString(),
},
JWT_SECRET
);
res.json({
token,
});
} else {
res.status(403).json({
message: "Incorrect creds",
});
}
});
app.post("/todos", auth, async (req, res) => {
const userId = req.userId;
const description = req.body.description;
const done = req.body.done;
await TodoModel.create({
userId,
description,
done,
});
res.json({
message: "Todo created",
});
});
app.get("/todos", auth, async (req, res) => {
const userId = req.userId;
const todos = await TodoModel.find({
userId,
});
res.json({ todos });
});
app.listen(PORT, (req, res) => {
console.log(`The app is running on port: ${PORT}`);
});