Repository navigation
Expand file tree
/
Copy pathinit_admin.js
More file actions
58 lines (50 loc) · 2.06 KB
/
Copy pathinit_admin.js
File metadata and controls
58 lines (50 loc) · 2.06 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
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcryptjs');
const path = require('path');
const crypto = require('crypto');
// DB_PATH is where the database really lives: C:\ProgramData\... on Windows,
// /data on Docker. Only a copy installed before that change keeps it beside
// the code, which is why the fallback is still here.
const fs = require('fs');
const dbPath = path.resolve(process.env.DB_PATH || path.join(__dirname, 'database.sqlite'));
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new sqlite3.Database(dbPath);
const adminId = process.argv[2];
const adminName = process.argv[3];
const adminEmail = process.argv[4];
const adminPassword = process.argv[5];
const port = process.argv[6];
if (!adminId || !adminName || !adminEmail || !adminPassword || !port) {
console.error("Usage: node init_admin.js <admin_id> <admin_name> <admin_email> <admin_password> <port>");
process.exit(1);
}
db.serialize(() => {
// 0. Ensure tables exist
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
emp_id TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
email TEXT,
password TEXT NOT NULL,
role TEXT DEFAULT 'employee'
)`);
// 1. Store Port in a config/settings table
db.run(`CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)`);
db.run(`INSERT OR REPLACE INTO settings (key, value) VALUES ('port', ?)`, [port]);
// 2. Clear old admins and insert new admin
db.run(`DELETE FROM users WHERE role = 'admin' OR role = 'super_admin' OR emp_id = ?`, [adminId]);
const hash = bcrypt.hashSync(adminPassword, 10);
db.run(`INSERT INTO users (emp_id, name, email, password, role) VALUES (?, ?, ?, ?, 'admin')`,
[adminId, adminName, adminEmail, hash], function(err) {
if (err) {
console.error("Failed to insert admin:", err);
process.exit(1);
} else {
console.log("Admin account successfully created.");
db.close();
}
});
});