Setup tables in a single init function

This commit is contained in:
Ethan O'Brien 2024-05-04 14:37:32 -05:00
parent 72f05a5d52
commit 32b5f5b68c
4 changed files with 26 additions and 39 deletions

View file

@ -9,7 +9,7 @@ use crate::encryption;
use crate::sql::SQLite; use crate::sql::SQLite;
lazy_static! { lazy_static! {
static ref DATABASE: SQLite = SQLite::new("live_statistics.db"); static ref DATABASE: SQLite = SQLite::new("live_statistics.db", setup_tables);
} }
pub struct Live { pub struct Live {
@ -24,8 +24,8 @@ pub struct Live {
pub master_pass: i64, pub master_pass: i64,
} }
fn create_store() { fn setup_tables(conn: &SQLite) {
DATABASE.lock_and_exec("CREATE TABLE IF NOT EXISTS lives ( conn.lock_and_exec("CREATE TABLE IF NOT EXISTS lives (
live_id INT NOT NULL PRIMARY KEY, live_id INT NOT NULL PRIMARY KEY,
normal_failed BIGINT NOT NULL, normal_failed BIGINT NOT NULL,
normal_pass BIGINT NOT NULL, normal_pass BIGINT NOT NULL,
@ -36,13 +36,13 @@ fn create_store() {
master_failed BIGINT NOT NULL, master_failed BIGINT NOT NULL,
master_pass BIGINT NOT NULL master_pass BIGINT NOT NULL
)", params!()); )", params!());
} conn.lock_and_exec("CREATE TABLE IF NOT EXISTS scores (
fn update_live_score(id: i64, uid: i64, score: i64) {
DATABASE.lock_and_exec("CREATE TABLE IF NOT EXISTS scores (
live_id INT NOT NULL PRIMARY KEY, live_id INT NOT NULL PRIMARY KEY,
score_data TEXT NOT NULL score_data TEXT NOT NULL
)", params!()); )", params!());
}
fn update_live_score(id: i64, uid: i64, score: i64) {
if uid == 0 || score == 0 { if uid == 0 || score == 0 {
return; return;
} }
@ -181,7 +181,6 @@ fn get_json() -> JsonValue {
} }
fn get_clearrate_json() -> JsonValue { fn get_clearrate_json() -> JsonValue {
create_store();
loop { loop {
match CACHED_DATA.lock() { match CACHED_DATA.lock() {
Ok(mut result) => { Ok(mut result) => {

View file

@ -20,7 +20,15 @@ use openssl::hash::MessageDigest;
use openssl::sign::Verifier; use openssl::sign::Verifier;
lazy_static! { lazy_static! {
static ref DATABASE: SQLite = SQLite::new("gree.db"); static ref DATABASE: SQLite = SQLite::new("gree.db", setup_tables);
}
fn setup_tables(conn: &SQLite) {
conn.create_store_v2("CREATE TABLE IF NOT EXISTS users (
cert TEXT NOT NULL,
uuid TEXT NOT NULL,
user_id BIGINT NOT NULL PRIMARY KEY
)");
} }
fn update_cert(uid: i64, cert: &str) { fn update_cert(uid: i64, cert: &str) {
@ -37,11 +45,6 @@ fn update_cert(uid: i64, cert: &str) {
DATABASE.lock_and_exec("UPDATE users SET cert=?1 WHERE user_id=?2", params!(cert, uid)); DATABASE.lock_and_exec("UPDATE users SET cert=?1 WHERE user_id=?2", params!(cert, uid));
} }
fn create_acc(cert: &str) -> String { fn create_acc(cert: &str) -> String {
DATABASE.create_store_v2("CREATE TABLE IF NOT EXISTS users (
cert TEXT NOT NULL,
uuid TEXT NOT NULL,
user_id BIGINT NOT NULL PRIMARY KEY
)");
let uuid = global::create_token(); let uuid = global::create_token();
let user = userdata::get_acc(&uuid); let user = userdata::get_acc(&uuid);
let user_id = user["user"]["id"].as_i64().unwrap(); let user_id = user["user"]["id"].as_i64().unwrap();

View file

@ -8,26 +8,22 @@ use base64::{Engine as _, engine::general_purpose};
use crate::sql::SQLite; use crate::sql::SQLite;
lazy_static! { lazy_static! {
static ref DATABASE: SQLite = SQLite::new("userdata.db"); static ref DATABASE: SQLite = SQLite::new("userdata.db", setup_tables);
static ref NEW_USER: JsonValue = { static ref NEW_USER: JsonValue = {
json::parse(include_str!("new_user.json")).unwrap() json::parse(include_str!("new_user.json")).unwrap()
}; };
} }
fn create_token_store() { fn setup_tables(conn: &SQLite) {
DATABASE.create_store_v2("CREATE TABLE IF NOT EXISTS tokens ( conn.create_store_v2("CREATE TABLE IF NOT EXISTS tokens (
user_id BIGINT NOT NULL PRIMARY KEY, user_id BIGINT NOT NULL PRIMARY KEY,
token TEXT NOT NULL token TEXT NOT NULL
)"); )");
} conn.create_store_v2("CREATE TABLE IF NOT EXISTS migration (
fn create_migration_store() {
DATABASE.create_store_v2("CREATE TABLE IF NOT EXISTS migration (
token TEXT NOT NULL PRIMARY KEY, token TEXT NOT NULL PRIMARY KEY,
password TEXT NOT NULL password TEXT NOT NULL
)"); )");
} conn.create_store_v2("CREATE TABLE IF NOT EXISTS users (
fn create_users_store() {
DATABASE.create_store_v2("CREATE TABLE IF NOT EXISTS users (
user_id BIGINT NOT NULL PRIMARY KEY, user_id BIGINT NOT NULL PRIMARY KEY,
userdata TEXT NOT NULL, userdata TEXT NOT NULL,
userhome TEXT NOT NULL, userhome TEXT NOT NULL,
@ -40,7 +36,6 @@ fn create_users_store() {
} }
fn acc_exists(uid: i64) -> bool { fn acc_exists(uid: i64) -> bool {
create_users_store();
DATABASE.lock_and_select("SELECT user_id FROM users WHERE user_id=?1", params!(uid)).is_ok() DATABASE.lock_and_select("SELECT user_id FROM users WHERE user_id=?1", params!(uid)).is_ok()
} }
fn get_key(auth_key: &str) -> i64 { fn get_key(auth_key: &str) -> i64 {
@ -74,8 +69,6 @@ fn generate_uid() -> i64 {
} }
fn create_acc(uid: i64, login: &str) { fn create_acc(uid: i64, login: &str) {
create_users_store();
let mut new_user = NEW_USER.clone(); let mut new_user = NEW_USER.clone();
new_user["user"]["id"] = uid.into(); new_user["user"]["id"] = uid.into();
new_user["stamina"]["last_updated_time"] = global::timestamp().into(); new_user["stamina"]["last_updated_time"] = global::timestamp().into();
@ -91,13 +84,11 @@ fn create_acc(uid: i64, login: &str) {
0 0
)); ));
create_token_store();
DATABASE.lock_and_exec("DELETE FROM tokens WHERE token=?1", params!(login)); DATABASE.lock_and_exec("DELETE FROM tokens WHERE token=?1", params!(login));
DATABASE.lock_and_exec("INSERT INTO tokens (user_id, token) VALUES (?1, ?2)", params!(uid, login)); DATABASE.lock_and_exec("INSERT INTO tokens (user_id, token) VALUES (?1, ?2)", params!(uid, login));
} }
fn get_uid(token: &str) -> i64 { fn get_uid(token: &str) -> i64 {
create_token_store();
let data = DATABASE.lock_and_select("SELECT user_id FROM tokens WHERE token = ?1;", params!(token)); let data = DATABASE.lock_and_select("SELECT user_id FROM tokens WHERE token = ?1;", params!(token));
if !data.is_ok() { if !data.is_ok() {
return 0; return 0;
@ -108,7 +99,6 @@ fn get_uid(token: &str) -> i64 {
// Needed by gree // Needed by gree
pub fn get_login_token(uid: i64) -> String { pub fn get_login_token(uid: i64) -> String {
create_token_store();
let data = DATABASE.lock_and_select("SELECT token FROM tokens WHERE user_id=?1", params!(uid)); let data = DATABASE.lock_and_select("SELECT token FROM tokens WHERE user_id=?1", params!(uid));
if !data.is_ok() { if !data.is_ok() {
return String::new(); return String::new();
@ -249,7 +239,6 @@ fn verify_password(password: &str, salted_hash: &str) -> bool {
} }
pub fn get_acc_transfer(uid: i64, token: &str, password: &str) -> JsonValue { pub fn get_acc_transfer(uid: i64, token: &str, password: &str) -> JsonValue {
create_migration_store();
let data = DATABASE.lock_and_select("SELECT password FROM migration WHERE token=?1", params!(token)); let data = DATABASE.lock_and_select("SELECT password FROM migration WHERE token=?1", params!(token));
if !data.is_ok() { if !data.is_ok() {
return object!{success: false}; return object!{success: false};
@ -265,7 +254,6 @@ pub fn get_acc_transfer(uid: i64, token: &str, password: &str) -> JsonValue {
} }
pub fn save_acc_transfer(token: &str, password: &str) { pub fn save_acc_transfer(token: &str, password: &str) {
create_migration_store();
DATABASE.lock_and_exec("DELETE FROM migration WHERE token=?1", params!(token)); DATABASE.lock_and_exec("DELETE FROM migration WHERE token=?1", params!(token));
DATABASE.lock_and_exec("INSERT INTO migration (token, password) VALUES (?1, ?2)", params!(token, hash_password(password))); DATABASE.lock_and_exec("INSERT INTO migration (token, password) VALUES (?1, ?2)", params!(token, hash_password(password)));
} }
@ -396,7 +384,6 @@ fn create_webui_token() -> String {
pub fn webui_login(uid: i64, password: &str) -> Result<String, String> { pub fn webui_login(uid: i64, password: &str) -> Result<String, String> {
create_webui_store(); create_webui_store();
create_migration_store();
let pass = DATABASE.lock_and_select("SELECT password FROM migration WHERE token=?1", params!(crate::router::user::uid_to_code(uid.to_string()))).unwrap_or(String::new()); let pass = DATABASE.lock_and_select("SELECT password FROM migration WHERE token=?1", params!(crate::router::user::uid_to_code(uid.to_string()))).unwrap_or(String::new());
if !verify_password(password, &pass) { if !verify_password(password, &pass) {
if acc_exists(uid) && pass == "" { if acc_exists(uid) && pass == "" {
@ -414,9 +401,6 @@ pub fn webui_login(uid: i64, password: &str) -> Result<String, String> {
pub fn webui_import_user(user: JsonValue) -> Result<JsonValue, String> { pub fn webui_import_user(user: JsonValue) -> Result<JsonValue, String> {
let mut user = user; let mut user = user;
create_webui_store();
create_migration_store();
create_token_store();
let uid = user["userdata"]["user"]["id"].as_i64().unwrap(); let uid = user["userdata"]["user"]["id"].as_i64().unwrap();
if acc_exists(uid) { if acc_exists(uid) {
return Err(String::from("User already exists")); return Err(String::from("User already exists"));

View file

@ -9,14 +9,15 @@ pub struct SQLite {
} }
impl SQLite { impl SQLite {
pub fn new(path: &str) -> SQLite { pub fn new(path: &str, setup: fn(&SQLite)) -> SQLite {
let conn = Connection::open(path).unwrap(); let conn = Connection::open(path).unwrap();
conn.execute("PRAGMA foreign_keys = ON;", ()).unwrap(); conn.execute("PRAGMA foreign_keys = ON;", ()).unwrap();
let instance = SQLite {
SQLite {
engine: Mutex::new(conn), engine: Mutex::new(conn),
sleep_duration: 10 sleep_duration: 10
} };
setup(&instance);
instance
} }
pub fn lock_and_exec(&self, command: &str, args: &[&dyn ToSql]) { pub fn lock_and_exec(&self, command: &str, args: &[&dyn ToSql]) {
loop { loop {