forked from cs4241-21a/a3-persistence
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.improved.js
More file actions
162 lines (141 loc) · 4.55 KB
/
Copy pathserver.improved.js
File metadata and controls
162 lines (141 loc) · 4.55 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
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
require('dotenv').config()
const path = require('path')
const fs = require('fs')
const express = require('express')
const app = express()
const { Db } = require('mongodb')
const cookieSession = require('cookie-session')
const passport = require('passport');
const mongodbclient = require( './services/mongodb-service.js' )
var favicon = require('serve-favicon')
var compression = require('compression')
var morgan = require('morgan')
require('./services/passport-service.js')
const validateLoginMiddleware = require('./services/passport-auth.js')
const port = 3000
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
app.use(morgan('combined', { stream: accessLogStream }))
app.use(express.json())
app.use(cookieSession({
name: 'github-user',
keys: [process.env.cookieKey1, process.env.cookieKey2],
maxAge: 24 * 60 * 60 * 1000
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(compression())
app.get('/auth/login', (req, res) => {
console.log("Redirecting to login page /auth/login")
res.sendFile(path.join(__dirname, '/public/login.html'));
})
app.get('/auth/github', passport.authenticate('github', {
scope: [ 'user:email' ]
}));
app.get('/auth/github/callback', passport.authenticate('github', {
failureRedirect: '/auth/error'
}), function(req, res) {
res.redirect('/');
});
app.get('/auth/error', (req, res) => {
res.writeHeader( 400, { 'Content-Type': 'text/plain' })
res.end("Could not authenticate you with GitHub, error from OAuth2")
})
app.get('/auth/getUserID', validateLoginMiddleware, (req, res) => {
res.writeHeader( 200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ 'username': req.user.emails[0].value , 'status': 200}))
})
app.get('/', validateLoginMiddleware, (req, res) => {
console.log('Getting /')
res.sendFile(path.join(__dirname, '/private/main.html'));
})
app.get('/me', validateLoginMiddleware, (req, res) => {
console.log('Getting /me')
res.sendFile(path.join(__dirname, '/private/yourdata.html'));
})
app.get('/api/lostitems', validateLoginMiddleware, (req, res) => {
mongodbclient.getLostItems()
.then(e => {
sendData(res, e)
})
})
app.get('/api/founditems', validateLoginMiddleware, (req, res) => {
mongodbclient.getFoundItems()
.then(e => {
sendData(res, e)
})
})
app.post('/api/update', validateLoginMiddleware, (req, res) => {
mongodbclient.getElement(req.body._id)
.then(item => {
if (!item) {
res.writeHead( 404, "Invalid item in database", {'Content-Type': 'text/plain' })
res.end()
return;
}
if (req.user.emails[0].value === item.emailme) {
mongodbclient.update(req.body)
.then(e => {
if (e === false) {
res.writeHead( 404, "Invalid UID", {'Content-Type': 'text/plain' })
res.end()
} else {
res.writeHead( 200, "OK", {'Content-Type': 'text/plain' })
res.end()
}
})
} else {
res.writeHead( 403, "Unauthorized", {'Content-Type': 'text/plain' })
res.end()
}
})
})
app.post('/api/create', validateLoginMiddleware, (req, res) => {
let data = req.body
let filtered = {
'item' : data.item,
'when' : data.when,
'where' : data.where,
'description' : data.description,
'photo' : data.photo,
'emailme' : data.emailme,
'timestamp' : Date.now()
}
let collection = "lostItems"
if (data.found === true) { collection = "foundItems"; }
mongodbclient.create(collection, filtered)
.then(e => {
if (e) {
res.writeHeader( 200 )
res.end()
} else {
res.writeHeader( 404 )
res.end()
}
})
})
app.post('/api/delete', validateLoginMiddleware, (req, res) => {
mongodbclient.delete(req.body._id)
.then((e) => {
if (e) {
res.writeHead( 200, "OK", {'Content-Type': 'text/plain' })
res.end()
} else {
res.writeHead( 404, "UID not found", {'Content-Type': 'text/plain' })
res.end()
}
})
})
const sendData = function( response, data ) {
for (let i = 0; i < data.length; i++) {
let timestampDate = new Date(data[i].timestamp)
let elapsed = ((Date.now() - timestampDate) / (24 * 60 * 60 * 1000));
data[i].created = Math.round(elapsed)
}
response.writeHeader( 200, { 'Content-Type': 'application/json' })
response.end(JSON.stringify(data))
}
let listener = app.listen(process.env.PORT || port, (e) => {
console.log(`Example app listening at http://localhost:${listener.address().port}`)
})