forked from cs4241-21a/a4-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
169 lines (145 loc) · 5.47 KB
/
server.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
const express = require("express"),
bodyParser = require("body-parser"),
cookie = require('cookie-session'),
path = require('path'),
app = express(),
mongodb = require("mongodb"),
favicon = require('serve-favicon'),
serveStatic = require('serve-static'),
morgan = require('morgan');
var ObjectId = require('mongodb').ObjectId;
//Serve favicon using middleware
app.use(favicon(__dirname + '/build/assets/open-book.png'));
//Serve static files using middleware
app.use(serveStatic(path.join(__dirname, 'build')))
//create a token
morgan.token('body', function(req, res) {
return [
JSON.stringify(req.body)
]
})
//create logger using morgan middleware
app.use(morgan(':method :url :status :res[content-length] - :response-time ms :body'))
const uri =
"mongodb+srv://tester:[email protected]/myFirstDatabase?retryWrites=true&w=majority";
const client = new mongodb.MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
let collection = null;
client.connect()
.then(() => {
// will create collection if it doesn't exist
return client.db("data").collection("data");
})
.then(__collection => {
// store reference to collection
collection = __collection
// blank query returns all documents
return collection.find({}).toArray()
})
app.post("/reviews", bodyParser.json(), (request, response) => {
if (collection !== null) {
collection
.find({ "user": request.body.user })
.toArray()
.then(result => response.json(result))
.catch(err => console.log(err));
}
});
app.post("/addUser", bodyParser.json(), (request, response) => {
if (collection !== null) {
collection
.find({ "username": request.body.username })
.toArray()
.then(result => {
if (result.length === 0) {
collection.insertOne(request.body)
.then(insertResponse => collection.findOne(insertResponse.insertedId))
.then(findResponse => {
response.json({ "newUser": "1" })
});
} else {
response.json({ "newUser": "0" })
}
})
.catch(err => console.log(err));
}
});
// use express.urlencoded to get data sent by default form actions
// or GET requests
app.use(express.urlencoded({ extended: true }))
// The keys are used for encryption and should be changed
app.use(cookie({
name: 'session',
keys: ['key123456', 'key234567']
}))
app.post('/login', (request, response) => {
// express.urlencoded will put your key value pairs
// into an object, where the key is the name of each
// form field and the value is whatever the user entered
collection.find({ "username": request.body.username }).toArray(function(err, results) {
if (err) {
console.log(err);
} else {
if (results[0] === undefined) {
request.session.login = false
// username incorrect, redirect back to login page
response.sendFile(__dirname + '/build/login-failed.html')
} else if (results[0].password === request.body.password) {
// define a variable that we can check in other middleware
// the session object is added to our requests by the cookie-session middleware
request.session.login = true
// since login was successful, send the user to the main content
response.redirect('main.html')
} else {
request.session.login = false
// password incorrect, redirect back to login page
response.sendFile(__dirname + '/build/login-failed.html')
}
}
})
})
// add some middleware that always sends unauthenicated users to the login page
app.use(function(request, response, next) {
if (request.session.login === true)
next()
else
response.sendFile(__dirname + '/build/login-failed.html')
})
app.post("/add", bodyParser.json(), (request, response) => {
console.log("body:", request.body);
collection.insertOne(request.body)
.then(insertResponse => collection.findOne(insertResponse.insertedId))
.then(findResponse => {
collection
.find({ "user": request.body.user })
.toArray()
.then(result => response.json(result))
.catch(err => console.log(err));
});
});
app.post("/remove", bodyParser.json(), (request, response) => {
collection
.deleteOne({ _id: ObjectId(request.body._id) })
.then(result => {
collection
.find({ "user": request.body.user })
.toArray()
.then(result => response.json(result))
.catch(err => console.log(err));
});
});
app.post('/update', bodyParser.json(), (request, response) => {
console.log("id: ", request.body._id)
collection
.findOneAndUpdate({ _id: ObjectId(request.body._id) }, { $set: { review: request.body.review, user: request.body.user } })
.then(result => {
collection
.find({ "user": request.body.user })
.toArray()
.then(result => response.json(result))
.catch(err => console.log(err));
});
});
app.listen(8080)