-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
346 lines (305 loc) · 10.2 KB
/
App.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
const express = require('express');
const session = require('express-session');
const SQLiteStore = require('connect-sqlite3')(session);
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt');
const CryptoJS = require('crypto-js');
const { body, validationResult } = require('express-validator');
const validator = require('validator');
const crypto = require('crypto');
const app = express();
const port = 3000;
app.use(express.static(__dirname + '/public'));
// Set up the database
const db = new sqlite3.Database('./passwords.db');
// Create users and passwords tables if they don't exist
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
email TEXT UNIQUE,
password TEXT
)`);
db.run(`CREATE TABLE IF NOT EXISTS passwords (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
website TEXT,
username TEXT,
password TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
)`);
});
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(session({
store: new SQLiteStore({ db: 'sessions.db', dir: './' }),
secret: process.env.SESSION_SECRET || 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 // 1 day
}
}));
app.set('view engine', 'ejs');
const encryptionKey = process.env.ENCRYPTION_KEY || 'your-secret-encryption-key';
// Middleware for input sanitization
const sanitizeInputs = (req, res, next) => {
for (let key in req.body) {
if (typeof req.body[key] === 'string') {
req.body[key] = validator.escape(req.body[key].trim());
}
}
next();
};
app.use(sanitizeInputs);
// Middleware to check token
const checkToken = (req, res, next) => {
if (!req.session.user) {
return res.status(401).json({ success: false, message: 'Unauthorized' });
}
const providedToken = req.body.token || req.query.token;
if (providedToken !== req.session.user.token) {
return res.status(403).json({ success: false, message: 'Invalid token' });
}
next();
};
// Password strength check
function isPasswordStrong(password) {
const minLength = 8;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumbers = /\d/.test(password);
const hasNonalphas = /\W/.test(password);
return password.length >= minLength && hasUpperCase && hasLowerCase && hasNumbers && hasNonalphas;
}
// Generate random password
function generateRandomPassword(length = 12) {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]:;?><,./-=";
let password = "";
for (let i = 0; i < length; i++) {
password += charset.charAt(Math.floor(Math.random() * charset.length));
}
return password;
}
// Routes
app.get('/', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
db.all('SELECT * FROM passwords WHERE user_id = ?', [req.session.user.id], (err, passwords) => {
if (err) {
return res.status(500).send('Error occurred');
}
const decryptedPasswords = passwords.map(pw => ({
...pw,
password: CryptoJS.AES.decrypt(pw.password, encryptionKey).toString(CryptoJS.enc.Utf8)
}));
res.render('home', { user: req.session.user, passwords: decryptedPasswords });
});
});
app.get('/login', (req, res) => {
res.render('login');
});
app.post('/login', [
body('email').isEmail().normalizeEmail(),
body('password').notEmpty(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
db.get('SELECT * FROM users WHERE email = ?', [email], (err, user) => {
if (err) {
return res.status(500).send('Error occurred');
}
if (!user) {
return res.status(400).send('User not found');
}
bcrypt.compare(password, user.password, (err, result) => {
if (result) {
const token = crypto.randomBytes(32).toString('hex');
req.session.user = { id: user.id, username: user.username, email: user.email, token: token };
res.json({ success: true, token: token }); // Send token to client
} else {
res.status(400).json({ success: false, message: 'Invalid credentials' });
}
});
});
});
app.get('/register', (req, res) => {
res.render('register');
});
app.post('/register', [
body('username').isLength({ min: 3 }).trim().escape(),
body('email').isEmail().normalizeEmail(),
body('password').custom(value => {
if (!isPasswordStrong(value)) {
throw new Error('Password does not meet strength requirements');
}
return true;
}),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { username, email, password } = req.body;
bcrypt.hash(password, 10, (err, hash) => {
if (err) {
return res.status(500).send('Error occurred');
}
db.run('INSERT INTO users (username, email, password) VALUES (?, ?, ?)', [username, email, hash], (err) => {
if (err) {
return res.status(400).send('Username or email already exists');
}
res.redirect('/login');
});
});
});
app.post('/add-credentials', checkToken, [
body('site').notEmpty().trim().escape(),
body('username').notEmpty().trim().escape(),
body('password').notEmpty(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log('Validation errors:', errors.array());
return res.status(400).json({ errors: errors.array() });
}
const { site, username, password } = req.body;
const encryptedPassword = CryptoJS.AES.encrypt(password, encryptionKey).toString();
console.log('Adding credential for user:', req.session.user.id);
db.run('INSERT INTO passwords (user_id, website, username, password) VALUES (?, ?, ?, ?)',
[req.session.user.id, site, username, encryptedPassword],
function(err) {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ success: false, message: 'Error occurred' });
}
console.log('Credential added, rows affected:', this.changes);
res.json({ success: true });
}
);
});
app.post('/edit-credential', checkToken, [
body('id').isInt(),
body('site').notEmpty().trim().escape(),
body('username').notEmpty().trim().escape(),
body('password').notEmpty(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { id, site, username, password } = req.body;
const encryptedPassword = CryptoJS.AES.encrypt(password, encryptionKey).toString();
db.run('UPDATE passwords SET website = ?, username = ?, password = ? WHERE id = ? AND user_id = ?',
[site, username, encryptedPassword, id, req.session.user.id],
(err) => {
if (err) {
return res.status(500).json({ success: false, message: 'Error occurred' });
}
res.json({ success: true });
}
);
});
app.post('/remove-credential', checkToken, [
body('id').isInt(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { id } = req.body;
db.run('DELETE FROM passwords WHERE id = ? AND user_id = ?',
[id, req.session.user.id],
(err) => {
if (err) {
return res.status(500).json({ success: false, message: 'Error occurred' });
}
res.json({ success: true });
}
);
});
app.post('/change-password', checkToken, [
body('currentPassword').notEmpty(),
body('newPassword').custom(value => {
if (!isPasswordStrong(value)) {
throw new Error('New password does not meet strength requirements');
}
return true;
}),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { currentPassword, newPassword } = req.body;
db.get('SELECT * FROM users WHERE id = ?', [req.session.user.id], (err, user) => {
if (err) {
return res.status(500).send('Error occurred');
}
bcrypt.compare(currentPassword, user.password, (err, result) => {
if (result) {
bcrypt.hash(newPassword, 10, (err, hash) => {
if (err) {
return res.status(500).send('Error occurred');
}
db.run('UPDATE users SET password = ? WHERE id = ?', [hash, req.session.user.id], (err) => {
if (err) {
return res.status(500).send('Error occurred');
}
res.send('Password updated successfully');
});
});
} else {
res.status(400).send('Incorrect current password');
}
});
});
});
app.post('/remove-credential', checkToken, [
body('id').isInt(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log('Validation errors:', errors.array());
return res.status(400).json({ success: false, errors: errors.array() });
}
const { id } = req.body;
console.log('Removing credential:', id, 'for user:', req.session.user.id);
db.run('DELETE FROM passwords WHERE id = ? AND user_id = ?',
[id, req.session.user.id],
function(err) {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ success: false, message: 'Error occurred' });
}
console.log('Rows affected:', this.changes);
if (this.changes === 0) {
return res.status(404).json({ success: false, message: 'Credential not found or not owned by user' });
}
res.json({ success: true });
}
);
});
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).send('Error occurred');
}
res.redirect('/login');
});
});
app.get('/generate-password', (req, res) => {
const password = generateRandomPassword();
res.json({ password });
});
app.listen(port, () => {
console.log(`Password manager running at http://localhost:${port}`);
});