forked from ChickenAI/multizlogin
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathauth.js
More file actions
97 lines (78 loc) · 2.73 KB
/
auth.js
File metadata and controls
97 lines (78 loc) · 2.73 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
85
86
87
88
89
90
91
92
93
94
95
96
97
// auth.js - Quản lý xác thực người dùng
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);
// Đường dẫn đến file lưu thông tin đăng nhập
const userFilePath = path.join(__dirname, 'zalo_data', 'users.json');
// Tạo file users.json nếu chưa tồn tại
const initUserFile = () => {
if (!fs.existsSync(path.join(__dirname, 'zalo_data'))) {
fs.mkdirSync(path.join(__dirname, 'zalo_data'), { recursive: true });
}
if (!fs.existsSync(userFilePath)) {
// Tạo mật khẩu mặc định 'admin' cho người dùng 'admin'
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('Đã tạo file users.json với tài khoản mặc định: admin/admin');
}
};
// Khởi tạo file người dùng
initUserFile();
// Đọc dữ liệu người dùng từ file
const getUsers = () => {
try {
const data = fs.readFileSync(userFilePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Lỗi khi đọc file users.json:', error);
return [];
}
};
// Thêm người dùng mới
export const addUser = (username, password) => {
const users = getUsers();
// Kiểm tra nếu username đã tồn tại
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;
};
// Xác thực người dùng
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;
};
// Middleware xác thực cho các route
export const authMiddleware = (req, res, next) => {
// Kiểm tra nếu đã đăng nhập (thông qua session)
if (req.session && req.session.authenticated) {
return next();
}
// Chuyển hướng về trang đăng nhập
res.redirect('/admin-login');
};
// Danh sách các route công khai (không cần xác thực)
export const publicRoutes = ['/admin-login', '/api'];