auth.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import bcrypt from 'bcryptjs';
  2. import fs from 'fs-extra';
  3. import path from 'path';
  4. import { fileURLToPath } from 'url';
  5. const __filename = fileURLToPath(import.meta.url);
  6. const __dirname = path.dirname(__filename);
  7. const USERS_FILE = path.join(__dirname, 'users.json');
  8. // Default admin user - change this password!
  9. const DEFAULT_ADMIN = {
  10. username: 'admin',
  11. password: 'admin123', // This will be hashed
  12. role: 'admin'
  13. };
  14. // Initialize users file if it doesn't exist
  15. async function initializeUsers() {
  16. try {
  17. if (!(await fs.pathExists(USERS_FILE))) {
  18. const hashedPassword = await bcrypt.hash(DEFAULT_ADMIN.password, 10);
  19. const users = {
  20. admin: {
  21. username: DEFAULT_ADMIN.username,
  22. passwordHash: hashedPassword,
  23. role: DEFAULT_ADMIN.role,
  24. createdAt: new Date().toISOString()
  25. }
  26. };
  27. await fs.writeJSON(USERS_FILE, users, { spaces: 2 });
  28. console.log('🔐 Created default admin user (username: admin, password: admin123)');
  29. console.log('⚠️ IMPORTANT: Change the default password immediately!');
  30. }
  31. } catch (error) {
  32. console.error('Error initializing users:', error);
  33. }
  34. }
  35. // Load users from file
  36. async function loadUsers() {
  37. try {
  38. if (await fs.pathExists(USERS_FILE)) {
  39. return await fs.readJSON(USERS_FILE);
  40. }
  41. return {};
  42. } catch (error) {
  43. console.error('Error loading users:', error);
  44. return {};
  45. }
  46. }
  47. // Save users to file
  48. async function saveUsers(users) {
  49. try {
  50. await fs.writeJSON(USERS_FILE, users, { spaces: 2 });
  51. } catch (error) {
  52. console.error('Error saving users:', error);
  53. throw error;
  54. }
  55. }
  56. // Authenticate user
  57. export async function authenticateUser(username, password) {
  58. try {
  59. const users = await loadUsers();
  60. const user = users[username];
  61. if (!user) {
  62. return null;
  63. }
  64. const isValidPassword = await bcrypt.compare(password, user.passwordHash);
  65. if (!isValidPassword) {
  66. return null;
  67. }
  68. // Return user without password hash
  69. return {
  70. username: user.username,
  71. role: user.role,
  72. createdAt: user.createdAt
  73. };
  74. } catch (error) {
  75. console.error('Error authenticating user:', error);
  76. return null;
  77. }
  78. }
  79. // Get user by username (without password)
  80. export async function getUserByUsername(username) {
  81. try {
  82. const users = await loadUsers();
  83. const user = users[username];
  84. if (!user) {
  85. return null;
  86. }
  87. return {
  88. username: user.username,
  89. role: user.role,
  90. createdAt: user.createdAt
  91. };
  92. } catch (error) {
  93. console.error('Error getting user:', error);
  94. return null;
  95. }
  96. }
  97. // Change user password
  98. export async function changeUserPassword(username, oldPassword, newPassword) {
  99. try {
  100. const users = await loadUsers();
  101. const user = users[username];
  102. if (!user) {
  103. return { success: false, message: 'User not found' };
  104. }
  105. const isValidOldPassword = await bcrypt.compare(oldPassword, user.passwordHash);
  106. if (!isValidOldPassword) {
  107. return { success: false, message: 'Current password is incorrect' };
  108. }
  109. const hashedNewPassword = await bcrypt.hash(newPassword, 10);
  110. users[username].passwordHash = hashedNewPassword;
  111. users[username].updatedAt = new Date().toISOString();
  112. await saveUsers(users);
  113. return { success: true, message: 'Password changed successfully' };
  114. } catch (error) {
  115. console.error('Error changing password:', error);
  116. return { success: false, message: 'Failed to change password' };
  117. }
  118. }
  119. // Initialize users on module load
  120. await initializeUsers();