-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
243 lines (208 loc) · 8.99 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
const express = require('express')
const session = require('express-session')
const mysql = require('mysql2')
const bodyParser = require('body-parser')
const fs = require('fs')
const https = require('https')
const bcrypt = require('bcrypt')
const request = require('request')
const csrf = require('csurf')
const { check } = require('express-validator')
const speakeasy = require('speakeasy')
const QRCode = require('qrcode');
require('dotenv').config()
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
const rounds = 12;
const path = require('path');
var csrfProtect = csrf({ cookie: false });
const app = express()
app.use(session({
secret: process.env.SALT,
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrf());
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'login.html')));
app.get('/register.html', (req, res) => res.sendFile(path.join(__dirname, 'register.html')));
app.get('/passchange.html', (req, res) => res.sendFile(path.join(__dirname, 'passchange.html')));
app.get('/token', csrfProtect, (req, res) => res.json({ csrfToken: req.csrfToken() }));
app.post('/reg', [
check('username').isLength({ min: 3 }).trim().escape(),
check('email').isEmail().normalizeEmail()
], csrfProtect, async (req, res) => {
if (req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
return res.json({ "responseCode": 1, "responseDesc": "Please select captcha" });
}
var secretKey = process.env.KEY;
var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;
request(verificationUrl, async (error, response, body) => {
body = JSON.parse(body);
if (body.success !== undefined && !body.success) {
return res.json({ "responseCode": 1, "responseDesc": "Failed captcha verification" });
}
let username = req.body.username;
let password = req.body.password;
let repeatpass = req.body.repeatpass;
if (password === repeatpass) {
try {
var hashpass = await bcrypt.hash(password, rounds)
} catch (error) {
console.log(error)
}
}
let email = req.body.email;
let sql = 'SELECT email FROM accounts WHERE email = ?';
let inserts = [email];
sql = mysql.format(sql, inserts);
if (email && username && (password === repeatpass)) {
connection.query(sql, function (error, results, fields) {
if (results.length > 0) {
res.send('That email is already registered!');
} else {
let sql = 'SELECT username FROM accounts WHERE username = ?';
let inserts = [username];
sql = mysql.format(sql, inserts);
connection.query(sql, function (error, results, fields) {
if (results.length > 0) {
res.send('That username is already registered!');
} else {
let sql = 'INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)';
let inserts = [username, hashpass, email];
sql = mysql.format(sql, inserts);
connection.query(sql, function (error, results, fields) {
res.send('Registered successfully! <a href="/">Login</a>');
})
}
})
}
})
}
});
});
app.post('/pass', csrfProtect, async (req, res) => {
var currPass = req.body.currPass;
var password = req.body.password;
try {
var hashpass = await bcrypt.hash(password, rounds)
} catch (error) {
console.log(error)
}
let sql = 'SELECT * FROM accounts WHERE username = ?';
let inserts = [req.session.username];
sql = mysql.format(sql, inserts);
if (hashpass) {
connection.query(sql, async (error, results, fields) => {
if (results.length > 0) {
await bcrypt.compare(currPass, results[0].password, function (err, result) {
let sql = 'UPDATE accounts SET password = ? WHERE username = ?';
let inserts = [hashpass, req.session.username];
sql = mysql.format(sql, inserts);
connection.query(sql, function (error, results, fields) {
res.send('Password changed! Re-login <a href="/">Login</a>');
})
});
}
})
}
});
app.post('/auth', [
check('username').isLength({ min: 3 }).trim().escape(),
check('code').isNumeric().escape()
], csrfProtect, async (request, response) => {
let username = request.body.username;
var password = request.body.password;
var code = request.body.code;
try {
var hashpass = await bcrypt.hash(password, rounds)
} catch (error) {
console.log(error)
}
let sql = 'SELECT * FROM accounts WHERE username = ?';
let inserts = [username];
sql = mysql.format(sql, inserts);
if (username && hashpass) {
connection.query(sql, async (error, results, fields) => {
if (results.length > 0) {
if (results[0].secret) {
var secret = results[0].secret;
if (speakeasy.totp.verify({
secret: secret,
encoding: 'base32',
token: code
})) {
try {
await bcrypt.compare(password, results[0].password, function (err, result) {
if (result) {
request.session.loggedin = true;
request.session.username = username;
response.redirect('/home');
}
});
} catch (error) {
console.log(error)
}
} else {
response.send('Code is wrong!')
}
} else {
try {
await bcrypt.compare(password, results[0].password, function (err, result) {
if (result) {
request.session.loggedin = true;
request.session.username = username;
response.redirect('/home');
}
});
} catch (error) {
console.log(error)
}
}
} else {
response.send('Incorrect Username and/or Password!');
}
});
} else {
response.send('Please enter Username and Password!');
}
});
app.get('/2fa', csrfProtect, (req, res) => {
var secret = speakeasy.generateSecret({ length: 20 });
let sql = 'SELECT username FROM accounts WHERE username = ?';
let inserts = [req.session.username];
sql = mysql.format(sql, inserts);
connection.query(sql, function (error, results, fields) {
if (results.length > 0) {
let sql = 'UPDATE accounts SET secret = ? WHERE username = ?';
let inserts = [secret.base32, req.session.username];
sql = mysql.format(sql, inserts);
connection.query(sql, function (error, results, fields) {
QRCode.toDataURL(secret.otpauth_url, function (err, image_data) {
res.send('<img src="' + image_data + '" alt="QRCode">')
});
})
}
})
});
app.get('/home', function (request, response) {
if (request.session.loggedin) {
response.send('Welcome back, ' + request.session.username + '!'
+ '<form action="/passchange.html" style="margin-top: 2vh;"><input type="submit" value="Change Password"/></form>'
+ '<form action="/2fa" style="margin-top: 2vh;"><input type="submit" value="2FA"/></form>');
} else {
response.send('Please login to view this page!');
}
});
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
}, app)
.listen(3000, function () {
console.log('App listening on port 3000! Go to https://localhost:3000/')
})