-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (85 loc) · 2.43 KB
/
Copy pathindex.js
File metadata and controls
102 lines (85 loc) · 2.43 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
const express = require("express");
const { authMiddleware } = require("./middleware");
const jwt = require("jsonwebtoken");
const { todoModel, userModel } = require("./models");
const app = express()
app.use(express.json());
app.post("/signup", async (req, res) => {
const username = req.body.username;
const password = req.body.password;
const existingUser = await userModel.findOne({
username: username,
password: password
});
if (existingUser) {
res.status(403).json({
message: "User with this username already exists"
})
return
}
const newUser = await userModel.create({
username: username,
password: password
})
res.json({
id: newUser._id
})
})
app.post("/signin", async (req, res) => {
const username = req.body.username;
const password = req.body.password;
const userExists = await userModel.findOne({
username: username,
password: password
});
if (!userExists) {
res.status(403).json({
message: "Incorrect credentials"
})
}
const token = jwt.sign({
userId: userExists.id
}, "secret123123");
res.json({
token
})
})
//TODO: Finish all the endpoints from here, migrate them from in memory to mongodb
app.post("/todo", authMiddleware, (req, res) => {
const userId = req.userId;
const title = req.body.title;
const description = req.body.description;
TODOS.push({
id: CURRENT_TODO_ID++,
title: title,
description: description,
userId: userId
})
res.json({
message: "Todo made"
})
})
// harkirats id might send a request to delete mark zuckerbergs todo id.
app.delete("/todo/:todoId", authMiddleware, (req, res) => {
const userId = req.userId;
const todoId = parseInt(req.params.todoId); /// string
const doesUserOwnTodo = TODOS.find(t => t.id === todoId && t.userId === userId);
if (doesUserOwnTodo) {
TODOS = TODOS.filter(t => t.id === todoId);
res.json({
message: "Deleted"
})
} else {
res.status(411).json({
message: "Either todo doesnt exist or this is not your todo"
})
}
})
app.get("/todos", authMiddleware, (req, res) => {
const userId = req.userId;
const userTodos = TODOS.filter(t => t.userId === userId);
res.json({
todos: userTodos
})
})
app.listen(3000);