This commit is contained in:
waveringana 2022-12-13 19:51:36 +00:00
parent 119ea24597
commit 8cfb867499
2 changed files with 61 additions and 57 deletions

View file

@ -17,7 +17,8 @@ import authRouter from "./routes/auth";
import indexRouter from "./routes/index";
import adduserRouter from "./routes/adduser";
import {db, expire, createUser, MediaRow} from "./types/db";
import {db, expire, createDatabase, updateDatabase, MediaRow} from "./types/db";
import e from "express";
const app = express();
const server = http.createServer(app);
@ -66,66 +67,25 @@ function onError(error: any) {
}
}
db.serialize(function() {
// Check if there is an existing DB or not
// Check if the database is empty
db.get("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table'", function(err, row) {
if (row.count === 0) createDatabase;
});
//Update old databases, Current version is 2
// Check if there is an existing DB or not
// Old database is version 1 without username support for images and expire support for users
// Because ver 1 does not have user_version set, we can safely assume that it is ver 1
db.get("SELECT * FROM sqlite_master WHERE name ='users' and type='table'", async (err, row) => {
if (!row) createDatabase(2);
else updateDBfrom1to2();
});
function updateDBfrom1to2 () {
db.get("PRAGMA user_version", (err: Error, row: any) => {
if (row && row.user_version) {
const version = row.user_version;
if (version != 2) console.log("DATABASE IS OUTDATED");
//updateDatabase();
} else {
//Old database is version 1 without username support for images and expire support for users
//Because ver 1 does not have user_version set, we can safely assume that it is ver 1
updateDatabase(1, 2);
}
});
createUser("admin", process.env.EBPASS || "changeme");
});
function createDatabase(version: number){
// create the database schema for the embedders app
console.log("Creating database");
db.run("CREATE TABLE IF NOT EXISTS users ( \
id INTEGER PRIMARY KEY, \
username TEXT UNIQUE, \
hashed_password BLOB, \
expire INTEGER, \
salt BLOB \
)");
db.run("CREATE TABLE IF NOT EXISTS media ( \
id INTEGER PRIMARY KEY, \
path TEXT NOT NULL, \
expire INTEGER, \
username TEXT \
)");
db.run(`PRAGMA user_version = ${version}`);
}
/**Updates old Database schema to new */
function updateDatabase(oldVersion: number, newVersion: number){
if (oldVersion == 1) {
console.log(`Updating database from ${oldVersion} to ${newVersion}`);
db.run("PRAGMA user_version = 2", (err) => {
if(err) return;
});
db.run("ALTER TABLE media ADD COLUMN username TEXT", (err) => {
if(err) return;
});
db.run("ALTER TABLE users ADD COLUMN expire TEXT", (err) => {
if(err) return;
});
}
}
function onListening() {