-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (77 loc) · 2.9 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
const express = require('express');
const mysql = require('mysql');
const bodyParser = require("body-parser");
const genericWebsite = require('@srnd/codecup-genericwebsite');
const port = process.env.PORT || 8080;
const flag = process.env.FLAG || 'test';
const tpl = genericWebsite.randomTemplate(flag);
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// connection deets
const db_config = {
host : 'localhost',
user : 'sqli-user',
password : 'sKLngsJkZjy&rFHUzFATDJsCFx~e5QucuTde3Rkcextw&Ahg92t9QW^aZDdNuL4y%rzPs',
database : 'SqliDB'
};
var connection = mysql.createConnection(db_config);
connection.connect(function(err) { // start connection
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
function handleDisconnect() { // handles any disconnects from mysql
connection = mysql.createConnection(db_config);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
app.get('/', (req, res) => { // simple search form
res.send(tpl('Search', `
<h1>Search the Database</h1>
<form action = "/result" method = "POST">
<input type = "text" name = "search" align = "justify"/><br><br>
<input type = "submit" value="Search" />
</form>
<footer>
<p>Contact: Hege Refsnes</p>
</footer>
<div style="height: 150px"></div>`));
});
app.post('/result', function(req,res) {
var search = req.body.search;
var sql = `SELECT * FROM users WHERE User='${search}';`; // SQL query syntax checking for matching user
connection.query(sql, function(err, results, fields){ // do the query
if (err) handleDisconnect();
if (results) {
res.render("/www/views/user-list.ejs", { userData: results }, function(err,html){ // render output as table
if (err) throw err;
res.send(tpl('Result', `
<h1>Search the Database</h1>
<form action = "/result" method = "POST">
<input type = "text" name = "search" align = "justify"/><br><br>
<input type = "submit" value="Search" />
</form>`+ html + `<footer>
<p>Contact: Hege Refsnes</p>
</footer>
<div style="height: 150px"></div>`));
});
} else {
res.send(tpl('Fail', 'Your query failed <br><b>SELECT * FROM users WHERE User=\'' + search + '\';</b> <br>' + err)); // display failed sql query
}
});
});
app.listen(port, () => console.log(`Listening on http://0.0.0.0:${port}/`));