-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathauth.js
More file actions
84 lines (68 loc) · 2.22 KB
/
auth.js
File metadata and controls
84 lines (68 loc) · 2.22 KB
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
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import crypto from 'crypto';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const userFilePath = path.join(__dirname, 'fb_data', 'users.json');
const initUserFile = () => {
if (!fs.existsSync(path.join(__dirname, 'fb_data'))) {
fs.mkdirSync(path.join(__dirname, 'fb_data'), { recursive: true });
}
if (!fs.existsSync(userFilePath)) {
const defaultPassword = 'admin';
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(defaultPassword, salt, 1000, 64, 'sha512').toString('hex');
const users = [{
username: 'admin',
salt,
hash
}];
fs.writeFileSync(userFilePath, JSON.stringify(users, null, 2));
console.log('Created users.json with default account: admin/admin');
}
};
initUserFile();
const getUsers = () => {
try {
const data = fs.readFileSync(userFilePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error reading users.json:', error);
return [];
}
};
export const addUser = (username, password) => {
const users = getUsers();
if (users.some(user => user.username === username)) {
return false;
}
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, 1000, 64, 'sha512').toString('hex');
users.push({ username, salt, hash });
fs.writeFileSync(userFilePath, JSON.stringify(users, null, 2));
return true;
};
export const validateUser = (username, password) => {
const users = getUsers();
const user = users.find(user => user.username === username);
if (!user) {
return false;
}
const hash = crypto.pbkdf2Sync(password, user.salt, 1000, 64, 'sha512').toString('hex');
return user.hash === hash;
};
export const authMiddleware = (req, res, next) => {
if (req.session && req.session.authenticated) {
return next();
}
res.redirect('/admin-login');
};
export const publicRoutes = [
'/admin-login',
'/api/accounts',
'/api/sendMessage',
'/api/sendImageToUser',
'/api/sendImagesToUser',
'/login'
];