-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
103 lines (93 loc) · 3.02 KB
/
database.js
File metadata and controls
103 lines (93 loc) · 3.02 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
98
99
100
101
102
103
const crypto = require("crypto");
require("dotenv").config();
const dbConfig = {
type: process.env.DB_TYPE || "sqlite",
sqlite: {
path: process.env.DBPATH || "./test.db"
},
mysql: {
host: process.env.DB_HOST || "localhost",
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "",
database: process.env.DB_NAME || "xjauth",
port: process.env.DB_PORT || 3306
}
};
function initDatabase() {
if (dbConfig.type === "mysql") {
return initMySQLDatabase();
} else {
return initSQLiteDatabase();
}
}
function initSQLiteDatabase() {
const Database = require("better-sqlite3");
const db = new Database(dbConfig.sqlite.path);
db.exec(`
CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
salt TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
console.log(`SQLite database "${dbConfig.sqlite.path}" initialized.`);
return {
type: "sqlite",
db: db,
get: (sql, params = []) => db.prepare(sql).get(params),
run: (sql, params = []) => db.prepare(sql).run(params)
};
}
function initMySQLDatabase() {
const mysql = require("mysql2/promise");
const pool = mysql.createPool({
...dbConfig.mysql,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
async function createTable() {
const connection = await pool.getConnection();
try {
await connection.execute(`
CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
salt VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
console.log(`MySQL database "${dbConfig.mysql.database}" initialized.`);
} catch (error) {
console.error("Error creating table:", error);
throw error;
} finally {
connection.release();
}
}
createTable();
return {
type: "mysql",
pool: pool,
get: async (sql, params = []) => {
const [rows] = await pool.execute(sql, params);
return rows[0];
},
run: async (sql, params = []) => {
const [result] = await pool.execute(sql, params);
return result;
}
};
}
function md5hash(password, salt = "") {
return crypto.createHash("md5").update(password + salt).digest("hex");
}
function generateSalt(length = 16) {
return crypto.randomBytes(Math.ceil(length / 2)).toString("hex").slice(0, length);
}
module.exports = { initDatabase, md5hash, generateSalt };