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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#[macro_use]
extern crate diesel;

#[macro_use]
mod db_object;

#[macro_use]
extern crate diesel_migrations;

mod df_site_map_images;
mod df_world;
mod df_world_map_images;
pub mod schema;

pub use db_object::{DBObject, OrderTypes};
pub use df_site_map_images::*;
pub use df_world::*;
pub use df_world_map_images::*;
pub use schema::*;
use std::convert::TryFrom;
// use failure::Error;

use ::r2d2::Error;
use df_st_core::config::{get_database_url, get_db_system_url, RootConfig};
use diesel::r2d2::{self, ConnectionManager};
use diesel::{Connection, RunQueryDsl};
use diesel_migrations::embed_migrations;

#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};

// PostgreSQL
#[cfg(feature = "postgres")]
pub type DbConnection = diesel::pg::PgConnection;
// SQLite
#[cfg(not(feature = "postgres"))]
pub type DbConnection = diesel::sqlite::SqliteConnection;

// Common
pub type DbManager = ConnectionManager<DbConnection>;
pub type DbPool = r2d2::Pool<DbManager>;
pub type DbError = Error;

// Embed all migrations in binary
embed_migrations!("../df_st_db/migrations");

fn generate_random_password() -> String {
    use rand::{Rng, SeedableRng};
    // Password settings
    let password_length = 30;
    let characters: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                            abcdefghijklmnopqrstuvwxyz\
                            0123456789";
    // Set random generator.
    // ChaCha is a cryptographically secure random number generator.
    // We are using 20 rounds, from_entropy will provide secure entropy.
    // This will panic if this is unable to provide secure entropy.
    let mut rng = rand_chacha::ChaCha20Rng::from_entropy();

    let password: String = (0..password_length)
        .map(|_| {
            let idx = rng.gen_range(0, characters.len());
            characters[idx] as char
        })
        .collect();
    password
}

pub fn create_user(privileged_config: &RootConfig) {
    let database_url = get_db_system_url(&privileged_config);

    if !cfg!(feature = "postgres") {
        error!("You are using a SQLite build, this function is only available in Postgres");
        panic!("You are using a SQLite build, this function is only available in Postgres");
    }
    if let Some(database_url) = database_url {
        let user = "df_storyteller".to_string();
        // Create a random password
        let password = generate_random_password();
        println!("generated Password for {}: {}", user, password);

        // Do not allow password shorter then 6 characters.
        if password.len() < 6 {
            panic!(
                "The password set for the database needs \
                to be at least 6 characters long."
            );
        }

        let conn = match DbConnection::establish(&database_url) {
            Ok(value) => value,
            Err(err) => {
                error!("Could not connect to database: {}", database_url);
                error!("{}", err.to_string());
                panic!("Error connecting to database.");
            }
        };

        // Use `$1` for postgres and `?` in other cases.
        // TODO bind did not seem to work.
        match diesel::sql_query(format!(
            "CREATE ROLE {} WITH \
            LOGIN \
            NOSUPERUSER \
            CREATEDB \
            NOCREATEROLE \
            INHERIT \
            NOREPLICATION \
            CONNECTION LIMIT -1 \
            PASSWORD '{}';",
            user, password
        ))
        // TODO prepare statement
        // .bind::<Text, _>(password.clone())
        .execute(&conn)
        {
            Ok(_) => {}
            Err(err) => match err {
                diesel::result::Error::DatabaseError(_, info) => {
                    if info.message().ends_with("already exists") {
                        warn!("User already exists, changing password.");
                        change_user_password(privileged_config, user.clone(), password.clone());
                    } else {
                        println!("Error: {}", info.message());
                    }
                }
                _ => panic!("Database error: {:?}", err),
            },
        }
        // Save password in config
        info!("Saving new config to file.");

        let port = privileged_config.database.config.port.unwrap_or(5432);
        let mut new_config = privileged_config.clone();
        new_config.database.config = df_st_core::config::DBURLConfig {
            db_path: Some(std::path::PathBuf::from("df_st_database.db")),
            user: Some(user),
            password,
            host: Some("localhost".to_owned()),
            port: Some(port),
            database: Some("df_storyteller".to_owned()),
            ..Default::default()
        };
        df_st_core::config::store_config_to_file(new_config, None);
    }
}

fn change_user_password(privileged_config: &RootConfig, user: String, password: String) {
    let database_url = get_db_system_url(&privileged_config);

    if !cfg!(feature = "postgres") {
        error!("You are using a SQLite build, this function is only available in Postgres");
        panic!("You are using a SQLite build, this function is only available in Postgres");
    }
    if let Some(database_url) = database_url {
        // Do not allow password shorter then 6 characters.
        if password.len() < 6 {
            panic!(
                "The password set for the database needs \
                to be at least 6 characters long."
            );
        }

        let conn = match DbConnection::establish(&database_url) {
            Ok(value) => value,
            Err(err) => {
                error!("Could not connect to database: {}", database_url);
                error!("{}", err.to_string());
                panic!("Error connecting to database.");
            }
        };

        // Use `$1` for postgres and `?` in other cases.
        diesel::sql_query(format!(
            "ALTER ROLE {} WITH \
            LOGIN \
            NOSUPERUSER \
            CREATEDB \
            NOCREATEROLE \
            INHERIT \
            NOREPLICATION \
            CONNECTION LIMIT -1 \
            PASSWORD '{}';",
            user, password
        ))
        // TODO prepare statement
        // .bind::<Text, _>(password)
        .execute(&conn)
        .unwrap();
        info!("Password for {} updated.", user);
    }
}

pub fn recreate_database(config: &RootConfig, drop_db: bool) {
    let database_url = get_db_system_url(&config);
    let database_name = match &config.database.config.database {
        Some(db_name) => db_name.clone(),
        None => "df_storyteller".to_owned(),
    };

    if !cfg!(feature = "postgres") {
        error!("You are using a SQLite build, this function is only available in Postgres");
        panic!("You are using a SQLite build, this function is only available in Postgres");
    }
    if let Some(database_url) = database_url {
        let conn = match DbConnection::establish(&database_url) {
            Ok(value) => value,
            Err(err) => {
                error!("Could not connect to database: {}", database_url);
                error!("{}", err.to_string());
                panic!("Error connecting to database.");
            }
        };
        if drop_db {
            // Drop database if already exists
            // TODO backup old db to file for if someone did not read the warnings.
            match diesel::sql_query(format!("DROP DATABASE IF EXISTS {};", database_name))
                .execute(&conn)
            {
                Ok(_) => {}
                Err(err) => match err {
                    diesel::result::Error::DatabaseError(_, info) => {
                        if info.message().starts_with("must be owner of database") {
                            panic!("Must be owner of database to drop database.");
                        } else {
                            panic!("Database error: {}", info.message());
                        }
                    }
                    _ => panic!("Database error: {:?}", err),
                },
            };
            info!("Database `{}` deleted.", database_name);
        }
        // Create a new database. This will fail is already exists.
        match diesel::sql_query(format!("CREATE DATABASE {};", database_name)).execute(&conn) {
            Ok(_) => {}
            Err(err) => match err {
                diesel::result::Error::DatabaseError(_, info) => {
                    info!(
                        "Database not deleted. If the database already exists \
                        add the flag `--drop-db` to drop the existing database first. \
                        WARNING this will delete all stored in the `{}` database!",
                        database_name
                    );
                    if info.message().ends_with("already exists") {
                        panic!("Database already exists.");
                    } else {
                        panic!("Database error: {}", info.message());
                    }
                }
                _ => panic!("Database error: {:?}", err),
            },
        };
        info!("Database `{}` created.", database_name);
    }
}

pub fn run_migrations(config: &RootConfig) {
    info!("Updating database...");
    let pool = establish_connection(&config).expect("Failed to connect to database.");
    let conn = pool.get().expect("Couldn't get db connection from pool.");
    embedded_migrations::run_with_output(&conn, &mut std::io::stdout()).unwrap();
    // embedded_migrations::run(&conn).unwrap();
    info!("Done updating database.");
}

pub fn establish_connection(config: &RootConfig) -> Result<DbPool, Error> {
    check_db_and_config_match(&config);
    let database_url = get_database_url(&config);
    if database_url.is_none() {
        error!(
            "No database url found, update in config file required.\n\
            Set database.config or database.url"
        );
        panic!("No database url found in config.");
    }
    let manager = DbManager::new(database_url.unwrap());
    let mut builder = r2d2::Pool::builder();
    if let Some(pool_size) = &config.database.pool_size {
        builder = builder.max_size(u32::try_from(*pool_size).unwrap());
    }
    builder.build(manager)
}

pub fn check_db_has_tables(config: &RootConfig) -> bool {
    let pool = match establish_connection(&config) {
        Ok(pool) => pool,
        Err(err) => {
            error!("Could not connect to database.");
            error!("{}", err.to_string());
            panic!("Error connecting to database.");
        }
    };
    let conn = pool.get().expect("Couldn't get db connection from pool.");
    DFWorldInfo::get_list_from_db(
        &*conn,
        std::collections::HashMap::new(),
        std::collections::HashMap::new(),
        0,
        1,
        None,
        None,
        None,
        true,
    )
    .is_ok()
}

/// Checks if the DB type matches the config type
/// So if version is compiled for `postgres`, config should be for `postgres`
/// If they down match, panic.
pub fn check_db_and_config_match(config: &RootConfig) {
    let service = config
        .database
        .service
        .clone()
        .unwrap_or_else(|| "sqlite".to_string());
    if cfg!(feature = "postgres") && service != "postgres" {
        error!("You are using a Postgres build but the config is set to an other service");
        panic!("You are using a Postgres build but the config is set to an other service");
    }
    if !cfg!(feature = "postgres") && service != "sqlite" {
        error!("You are using a SQLite build but the config is set to an other service");
        panic!("You are using a SQLite build but the config is set to an other service");
    }
}

/// Returns the name of the database service (`"postgres"` or `"sqlite"`)
pub fn get_db_service_name() -> String {
    if cfg!(feature = "postgres") {
        "postgres".to_owned()
    } else {
        "sqlite".to_owned()
    }
}