-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
257 lines (196 loc) · 7.18 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
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
/**
* LinkedDataViz
* Node proxy server
* Receive query from HTML page, send query to SPARQL endpoint, apply transformation,
*
* Yun Tian - Olivier Corby - Marco Winckler (2019-2020)
* Aline Menin - Maroua Tikat (2020-2022)
* Aline Menin (2023-present)
**/
const fs = require('fs');
const fileUpload = require('express-fileupload');
const express = require('express');
const back = require('express-back');
const bodyParser = require('body-parser');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const path = require('path');
const cors = require('cors');
const morgan = require('morgan');
const _ = require('lodash');
const https = require('https')
//// Data tools ////
const { Users, Data, SPARQLRequest } = require('./servertools');
const users = new Users()
const data = new Data()
const sparql = new SPARQLRequest()
const prefix = '/ldviz'
const app = express()
// Pour accepter les connexions cross-domain (CORS)
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");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
app.use(express.json({limit: '50mb'}));
//add other middleware
app.use(cors());
app.use(morgan('dev'));
app.use(fileUpload());
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(prefix, express.static(path.join(__dirname, 'public')))
app.use(express.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret: "Your secret key",
resave: false, // Do not save session if unmodified
saveUninitialized: true, // Save uninitialized sessions
cookie: {
maxAge: 30 * 60 * 1000, // 30 minutes
secure: false // Set to true if using HTTPS
}
}));
app.set('trust proxy', 1); // Trust the first proxy
app.use(back());
////////////// login routes ///////////////////////////
// login page
app.get(prefix + '/login', function (req, res) {
res.render('login')
})
// Login route
app.post(prefix + '/login', async (req, res) => {
const user = await users.findUser(req)
console.log(req.query, req.body)
let result = {... req.query}
if (user) {
req.session.user = { id: user.id, username: user.username };
result.message = 'Login successful'
result.sessionId = req.sessionID
res.send(result)
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
// Middleware to check if user is authenticated
function isAuthenticated(req, res, next) {
if (req.session.user) {
next();
} else {
res.status(401).json({ message: 'Unauthorized: Please log in' });
}
}
// Logout route
app.post(prefix + '/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).json({ message: 'Logout failed' });
}
res.send({ message: 'Logout successful' });
});
});
/////////// end login routes //////////////////////////
////// Pages /////////
// home page
app.get(prefix + '/', async function (req, res) {
let endpoints = fs.readFileSync('data/analysis/endpoints.json')
endpoints = JSON.parse(endpoints)
let result = fs.readFileSync('data/analysis/results.json')
result = JSON.parse(result)
let pagedata = await data.load(req)
pagedata.endpoints = endpoints
pagedata.result = result
pagedata.sessionID = req.session.user ? req.sessionID : null
res.render("about", pagedata)
})
// LDViz about page
app.get(prefix + '/editor', async function (req, res) {
//await users.checkConnection(req)
let pagedata = await data.load(req)
pagedata.sessionID = req.session.user ? req.sessionID : null
res.render("index", pagedata)
})
app.get(prefix + '/dataviz', async function (req, res) {
//await users.checkConnection(req)
let pagedata = await data.load(req)
pagedata.sessionID = req.session.user ? req.sessionID : null
res.render("dataviz", pagedata)
})
// generic page which url is set when changing the href of the page
// :page = covid, hal, ldviz
// :action = newQuery, edit, clone
app.get(prefix + '/editor/:action/', async function(req, res){
const params = req.params;
const queryId = req.query.queryId;
let result = await data.load(req)
result.existingQuery = result.queries.filter(d => d.id == queryId)[0] || {}
result.action = params.action
result.sessionID = req.session.user ? req.sessionID : null
res.render("index", result)
})
/// Display results of a query in SPARQL json format /////
// INFO: not being used anymore
app.get(prefix + '/results/', async function(req, res){
let existingQuery = req.query.id ? await data.getQuery(req.query.id) : null
let querydata = existingQuery || req.query
res.render("results", { queryData: querydata })
})
//////// POST routes //////////////
app.post(prefix + '/upload', (req, res) => {
// Get the file that was set to our field named "image"
const { image } = req.files;
// If no image submitted, exit
if (!image) return res.sendStatus(400);
// Move the uploaded image to our upload folder
image.mv(__dirname + '/public/images/dataviz/' + image.name);
res.sendStatus(200);
});
/**
* Manages queries or dataviz on disk
* @param action The action to be performed : "add" new data, "edit" existing data, or "delete" a data record
* @param file The json file to be modified: queries or dataviz
*/
app.post(prefix + '/:action/:file', async function (req, res) {
console.log(req.params.action, req.params.file)
let response;
switch(req.params.action) {
case 'add':
response = await data.addToFile(req.body, req.params.file)
break;
case 'edit':
response = await data.update(req.body, req.params.file)
break;
case 'delete':
response = await data.delete(req.body.id, req.params.file)
break;
}
if (response && response.message) {
res.sendStatus(response.code)
return;
}
res.sendStatus(200);
})
// SPARQL request
app.post(prefix + '/sparql', async function (req, res) {
res.send(await sparql.sendRequest(req.body.query, req.body.endpoint))
})
const port = 8040 // verify the availability of this port on the server
const portHTTPS = 8043
app.listen(port, async () => { console.log(`HTTP Server started at port ${port}.`) })
try {
let folderpath = '/etc/httpd/certificate/exp_20250808/'
var privateKey = fs.readFileSync( folderpath + 'dataviz_i3s_unice_fr.key' );
var certificate = fs.readFileSync( folderpath + 'dataviz_i3s_unice_fr_cert.crt' );
var ca = fs.readFileSync( folderpath + 'dataviz_i3s_unice_fr_AC.cer' );
var options = {key: privateKey, cert: certificate, ca: ca};
https.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen( portHTTPS, async () => { console.log(`HTTPS Server started at port ${portHTTPS}.`) } );
} catch(e) {
console.log("Could not start HTTPS server")
}