-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
327 lines (282 loc) · 8.57 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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
var express = require('express');
var cookieParser = require('cookie-parser')
var session = require('express-session')
var bodyParser = require('body-parser')
var jsonfile = require('jsonfile')
var Grant = require('grant-express')
var morgan = require('morgan')
var request = require('request');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var CONFIGURATION = require('./config.json')[process.env.NODE_ENV || 'dev'];
var authUrl = CONFIGURATION.microauth._host
var mdb_url
var dbName = "IT2901"
updateServiceIP("mongodb", formatMongoURL)
var indexer_url
updateServiceIP("indexer", formatIndexerURL)
var subsite = CONFIGURATION.server.subsite
CONFIGURATION.microauth.key = process.env.PUBLISHING_MICROAUTH_CLIENT_ID
CONFIGURATION.microauth.secret = process.env.PUBLISHING_MICROAUTH_SECRET
var grant = new Grant(CONFIGURATION)
var app = express();
app.use(session({ secret: 'topkek' }))
app.use(grant)
app.use(bodyParser.urlencoded({ extended: true }));
app.use( bodyParser.json() );
app.use(morgan('dev'));
app.use(cookieParser());
var REQUIRE_AUTH = {
LIST: false,
DETAIL: false,
SAVE: true,
DELETE: true
}
var REDIRECT_TO_AUTHORIZE = true;
function formatMongoURL(ip) {
mdb_url = "mongodb://" + ip + ":27017/" + dbName
}
function formatIndexerURL(ip) {
indexer_url = "http://" + ip
}
function updateServiceIP(serviceName, callback) {
request('http://127.0.0.1:9001/' + serviceName, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body.replace(/"/g, ""))
}
})
}
function isCredentialExpired(oauth2) {
return oauth2.issued_at + oauth2.expires_in < Date.now()
}
function requiresAuthentication(req) {
var authorizationHeader = req.get('Authorization');
if (req.session.oauth2) {
if (!isCredentialExpired(req.session.oauth2)) {
return false
}
} else if (authorizationHeader !== "" && authorizationHeader !== undefined) {
request.get({
uri: authUrl + 'verify/',
headers: {'Authorization': authorizationHeader},
},
function (err, response, body) {
console.log(err, body)
if (err !== null || response.statusCode !== 200) {
return true
} else {
return false
}
}
)
} else {
return true
}
}
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post("/save_article", function (req, res) {
if (REQUIRE_AUTH.SAVE) {
if (requiresAuthentication(req)) {
if (REDIRECT_TO_AUTHORIZE) {
req.session.next = subsite + req.url
res.redirect('/connect/microauth')
return
} else {
res.sendStatus(401, 'You need to be authenticated to do this action.')
return
}
}
}
try {
updateServiceIP("mongodb", formatMongoURL)
updateServiceIP("indexer", formatIndexerURL)
MongoClient.connect(mdb_url, function(err, db) {
assert.equal(null, err);
db.collection("publishing").insertOne(req.body, function(err, result) {
assert.equal(err, null);
var options = {
uri: indexer_url,
method: 'POST',
json: {
"task": 'publishedArticle',
"articleID": result.insertedId.toHexString()
}
};
request.post(options, function(err,httpResponse,body) {
if (err != null) {
console.log("Could not update indexer.");
console.log(err.message);
}
});
});
});
res.sendStatus(204);
success = true;
}
catch (err) {
res.sendStatus(500);
console.log(err.message);
}
});
app.get('/done', function (req, res) {
var err = req.query.error
if (err) {
res.send(JSON.stringify(err))
return
}
var oauth2 = {
access_token: req.query.raw.access_token,
refresh_token: req.query.raw.refresh_token,
scope: req.query.raw.scope,
expires_in: req.query.raw.expires_in,
token_type: req.query.raw.token_type,
issued_at: Date.now()
}
req.session.oauth2 = oauth2;
if (req.session.next) {
res.redirect(req.session.next)
} else {
res.send(JSON.stringify('You have authorized Content:Publishing to use your credentials on your behalf,' +
' for posting content.'));
}
})
app.get("/list", function (req, res) {
if (REQUIRE_AUTH.LIST) {
if (requiresAuthentication(req)) {
if (REDIRECT_TO_AUTHORIZE) {
var next = subsite + req.url
if (req.cookies["next"]) {
next = req.cookies["next"]
}
req.session.next = next
res.redirect('/connect/microauth')
res.redirect('/connect/microauth')
return
} else {
res.sendStatus(401, 'You need to be authenticated to do this action.')
return
}
}
}
try {
updateServiceIP("mongodb", formatMongoURL)
MongoClient.connect(mdb_url, function(err, db) {
assert.equal(null, err);
var art_list = db.collection('publishing').find().toArray(function(err, documents) {
var art_list = [];
for (i = 0; i < documents.length; i++) {
art_list.push({id:documents[i]._id.toHexString(), title:documents[i].title, description:documents[i].description});
}
db.close();
list_response = {list: art_list};
res.send(JSON.stringify(list_response));
});
});
}
catch (err) {
res.sendStatus(500);
console.log(err.message);
}
});
app.get("/article/*", function (req, res) {
try {
var article_name = req.url.substr(-24);
var new_id = new ObjectId(article_name);
updateServiceIP("mongodb", formatMongoURL)
MongoClient.connect(mdb_url, function(err, db) {
assert.equal(null, err);
db.collection('publishing').findOne({"_id":new_id}, function(err, doc){
article_start = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>";
article_mid = "</title></head><body>";
article_end = "</body></html>";
res.send(article_start+doc.title+article_mid+doc.article+article_end);
});
});
}
catch (err) {
res.sendStatus(500);
console.log(err.message);
}
});
app.options("/article_json/*", function (req, res) {
try {
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.sendStatus(204);
}
catch (err) {
res.sendStatus(500);
console.log(err.message);
}
});
app.get("/article_json/*", function (req, res) {
try {
var article_name = req.url.substr(-24);
var new_id = new ObjectId(article_name);
updateServiceIP("mongodb", formatMongoURL)
MongoClient.connect(mdb_url, function(err, db) {
assert.equal(null, err);
db.collection('publishing').findOne({"_id":new_id}, function(err, doc){
res.send(JSON.stringify(doc));
});
});
}
catch (err) {
res.sendStatus(500);
console.log(err.message);
}
});
app.get("/authorize_me", function (req, res) {
if (requiresAuthentication(req)) {
if (req.cookies["next"]) {
req.session.next = req.cookies["next"]
}
res.redirect('/connect/microauth')
return
} else {
res.sendStatus(200);
return
}
})
app.delete("/article_json/*", function (req, res) {
if (REQUIRE_AUTH.DELETE) {
if (requiresAuthentication(req)) {
if (REDIRECT_TO_AUTHORIZE) {
req.session.next = subsite + req.url
res.redirect('/connect/microauth')
return
} else {
res.sendStatus(401, 'You need to be authenticated to do this action.')
return
}
}
}
try {
var article_name = req.url.substr(-24);
var new_id = new ObjectId(article_name);
updateServiceIP("mongodb", formatMongoURL)
updateServiceIP("indexer", formatIndexerURL)
MongoClient.connect(mdb_url, function(err, db) {
assert.equal(null, err);
db.collection('publishing').remove({"_id":new_id});
request.post(indexer_url, {task : "removedArticle" , articleID : article_name}, function(err,httpResponse,body) {
if (err != null) {
console.log("Could not update indexer.");
console.log(err.message);
}
});
});
res.sendStatus(204);
}
catch (err) {
res.sendStatus(500);
console.log(err.message);
}
});
app.listen(3000, function () {
console.log("Publishing app listening on port 3000!");
});