medal/
config.rs

1/*  medal                                                                                                            *\
2 *  Copyright (C) 2022  Bundesweite Informatikwettbewerbe, Robert Czechowski                                         *
3 *                                                                                                                   *
4 *  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero        *
5 *  General Public License as published  by the Free Software Foundation, either version 3 of the License, or (at    *
6 *  your option) any later version.                                                                                  *
7 *                                                                                                                   *
8 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the       *
9 *  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public      *
10 *  License for more details.                                                                                        *
11 *                                                                                                                   *
12 *  You should have received a copy of the GNU Affero General Public License along with this program.  If not, see   *
13\*  <http://www.gnu.org/licenses/>.                                                                                  */
14
15use std::path::{Path, PathBuf};
16
17use structopt::StructOpt;
18
19#[derive(Serialize, Deserialize, Clone, Default, Debug)]
20pub struct OauthProvider {
21    pub provider_id: String,
22    pub medal_oauth_type: String,
23    pub url: String,
24    pub client_id: String,
25    pub client_secret: String,
26    pub access_token_url: String,
27    pub user_data_url: String,
28    pub school_data_url: Option<String>,
29    pub school_data_secret: Option<String>,
30    pub allow_teacher_login_without_school: Option<bool>,
31    pub login_link_text: String,
32}
33
34#[derive(Serialize, Deserialize, Clone, Default, Debug)]
35pub struct Config {
36    pub host: Option<String>,
37    pub port: Option<u16>,
38    pub self_url: Option<String>,
39    pub oauth_providers: Option<Vec<OauthProvider>>,
40    pub database_file: Option<PathBuf>,
41    pub database_url: Option<String>,
42    pub template: Option<String>,
43    pub no_contest_scan: Option<bool>,
44    pub open_browser: Option<bool>,
45    pub cookie_signing_secret: Option<String>,
46    pub disable_results_page: Option<bool>,
47    pub enable_password_login: Option<bool>,
48    pub require_sex: Option<bool>,
49    pub allow_sex_na: Option<bool>,
50    pub allow_sex_diverse: Option<bool>,
51    pub allow_sex_other: Option<bool>,
52    pub dbstatus_secret: Option<String>,
53    pub template_params: Option<::std::collections::BTreeMap<String, serde_json::Value>>,
54    pub only_contest_scan: Option<bool>,
55    pub reset_admin_pw: Option<bool>,
56    pub log_timing: Option<bool>,
57    pub auto_save_interval: Option<u64>,
58    pub version: Option<bool>,
59    pub restricted_task_directories: Option<Vec<String>>,
60}
61
62#[derive(StructOpt, Debug)]
63#[structopt()]
64struct Opt {
65    /// Config file to use (default: 'config.json')
66    #[structopt(short = "c", long = "config", default_value = "config.yaml", parse(from_os_str))]
67    pub configfile: PathBuf,
68
69    /// Database file to use (default: from config file or 'medal.db')
70    #[structopt(short = "d", long = "database", parse(from_os_str))]
71    pub databasefile: Option<PathBuf>,
72
73    /// Database file to use (default: from config file or 'medal.db')
74    #[structopt(short = "D", long = "databaseurl")]
75    pub databaseurl: Option<String>,
76
77    /// Port to listen on (default: from config file or 8080)
78    #[structopt(short = "p", long = "port")]
79    pub port: Option<u16>,
80
81    /// Teacher page in task directory
82    #[structopt(short = "t", long = "template")]
83    pub template: Option<String>,
84
85    /// Reset password of admin user (user_id=1)
86    #[structopt(short = "a", long = "reset-admin-pw")]
87    pub resetadminpw: bool,
88
89    /// Run medal without scanning for contests
90    #[structopt(short = "S", long = "no-contest-scan")]
91    pub nocontestscan: bool,
92
93    /// Scan for contests without starting medal
94    #[structopt(short = "s", long = "only-contest-scan")]
95    pub onlycontestscan: bool,
96
97    /// Automatically open medal in the default browser
98    #[structopt(short = "b", long = "browser")]
99    pub openbrowser: bool,
100
101    /// Disable results page to reduce load on the server
102    #[structopt(long = "disable-results-page")]
103    pub disableresultspage: bool,
104
105    /// Enable the login with username and password
106    #[structopt(short = "P", long = "passwordlogin")]
107    pub enablepasswordlogin: bool,
108
109    /// Teacher page in task directory
110    #[structopt(short = "T", long = "teacherpage")]
111    pub teacherpage: Option<String>,
112
113    /// Log response time of every request
114    #[structopt(long = "log-timing")]
115    pub logtiming: bool,
116
117    /// Auto save interval in seconds (defaults to 10)
118    #[structopt(long = "auto-save-interval")]
119    pub autosaveinterval: Option<u64>,
120
121    /// Show version
122    #[structopt(long = "version")]
123    pub version: bool,
124}
125
126enum FileType {
127    Json,
128    Yaml,
129}
130
131pub fn read_config_from_file(file: &Path) -> Config {
132    use std::io::Read;
133
134    let file_type = match file.extension().map(|e| e.to_str().unwrap_or("<Encoding error>")) {
135        Some("yaml") | Some("YAML") => FileType::Yaml,
136        Some("json") | Some("JSON") => FileType::Json,
137        Some(ext) => panic!("Config file has unknown file extension `{}` (supported types are YAML and JSON).", ext),
138        None => panic!("Config file has no file extension (supported types are YAML and JSON)."),
139    };
140
141    println!("Reading configuration file '{}'", file.to_str().unwrap_or("<Encoding error>"));
142
143    let mut config: Config = if let Ok(mut file) = std::fs::File::open(file) {
144        let mut contents = String::new();
145        file.read_to_string(&mut contents).unwrap();
146        match file_type {
147            FileType::Json => serde_json::from_str(&contents).unwrap(),
148            FileType::Yaml => serde_yaml::from_str(&contents).unwrap(),
149        }
150    } else {
151        println!("Configuration file '{}' not found. Using default configuration.",
152                 file.to_str().unwrap_or("<Encoding error>"));
153        Default::default()
154    };
155
156    if let Some(ref rtds) = config.restricted_task_directories {
157        // Some sanity checks
158        for rtd in rtds {
159            if !Path::new(rtd).exists() {
160                println!("WARNING: restricted task directory '{}' does NOT exist!", rtd);
161            }
162            if rtd.chars().last().unwrap_or(' ') != '/' {
163                println!("WARNING: restricted task directory '{}' does NOT end with a '/'", rtd);
164            }
165            if !rtd.starts_with("tasks/") {
166                println!("WARNING: restricted task directory '{}' does NOT start with 'tasks/'", rtd);
167            }
168            if rtd == "tasks/" {
169                println!("WARNING: restricted task directory '{}' restricts ALL tasks", rtd);
170            }
171        }
172    }
173
174    if let Some(ref oap) = config.oauth_providers {
175        println!("OAuth providers:");
176        for oap in oap {
177            println!("  * {}", oap.provider_id);
178        }
179    }
180
181    if config.host.is_none() {
182        config.host = Some("[::]".to_string())
183    }
184    if config.port.is_none() {
185        config.port = Some(8080)
186    }
187    if config.self_url.is_none() {
188        config.self_url = Some("http://localhost:8080".to_string())
189    }
190    if config.template.is_none() {
191        config.template = Some("default".to_string())
192    }
193    if config.no_contest_scan.is_none() {
194        config.no_contest_scan = Some(false)
195    }
196    if config.open_browser.is_none() {
197        config.open_browser = Some(false)
198    }
199    if config.enable_password_login.is_none() {
200        config.enable_password_login = Some(false)
201    }
202    if config.auto_save_interval.is_none() {
203        config.auto_save_interval = Some(10)
204    }
205
206    println!("OAuth providers will be told to redirect to {}", config.self_url.as_ref().unwrap());
207
208    config
209}
210
211fn merge_value<T>(into: &mut Option<T>, from: Option<T>) { from.map(|x| *into = Some(x)); }
212
213fn merge_flag(into: &mut Option<bool>, from: bool) {
214    if from {
215        *into = Some(true);
216    }
217}
218
219pub fn get_config() -> Config {
220    let opt = Opt::from_args();
221    if opt.version {
222        return Config { version: Some(true), ..Config::default() };
223    }
224
225    #[cfg(feature = "debug")]
226    println!("Options: {:#?}", opt);
227
228    let mut config = read_config_from_file(&opt.configfile);
229
230    #[cfg(feature = "debug")]
231    println!("Config: {:#?}", config);
232
233    // Let options override config values
234    merge_value(&mut config.database_file, opt.databasefile);
235    merge_value(&mut config.database_url, opt.databaseurl);
236    merge_value(&mut config.port, opt.port);
237    merge_value(&mut config.template, opt.template);
238    merge_value(&mut config.auto_save_interval, opt.autosaveinterval);
239
240    merge_flag(&mut config.no_contest_scan, opt.nocontestscan);
241    merge_flag(&mut config.open_browser, opt.openbrowser);
242    merge_flag(&mut config.disable_results_page, opt.disableresultspage);
243    merge_flag(&mut config.enable_password_login, opt.enablepasswordlogin);
244    merge_flag(&mut config.only_contest_scan, opt.onlycontestscan);
245    merge_flag(&mut config.reset_admin_pw, opt.resetadminpw);
246    merge_flag(&mut config.log_timing, opt.logtiming);
247
248    if let Some(template_params) = &mut config.template_params {
249        if let Some(teacherpage) = opt.teacherpage {
250            template_params.insert("teacher_page".to_string(), teacherpage.into());
251        }
252
253        let all_categories = if let Some(serde_json::Value::Object(categories)) = template_params.get("categories") {
254            Some(categories.clone())
255        } else {
256            None
257        };
258
259        if let Some(serde_json::Value::Array(tiles)) = template_params.get_mut("index_tiles") {
260            for (i, elem) in tiles.iter_mut().enumerate() {
261                if let serde_json::Value::Object(tile) = elem {
262                    if i == 0 {
263                        tile.insert("medal_index_tile_is_first".to_string(), serde_json::Value::Bool(true));
264                    }
265                    if i % 2 == 0 {
266                        tile.insert("medal_index_tile_is_even".to_string(), serde_json::Value::Bool(true));
267                    }
268                    if let Some(serde_json::Value::String(category_name)) = tile.get("category") {
269                        if let Some(Some(serde_json::Value::Object(category))) =
270                            all_categories.as_ref().map(|c| c.get(category_name))
271                        {
272                            for (key, value) in category {
273                                tile.insert(key.clone(), value.clone());
274                            }
275                        }
276                    }
277                }
278            }
279        }
280    } else if let Some(teacherpage) = opt.teacherpage {
281        let mut template_params = ::std::collections::BTreeMap::<String, serde_json::Value>::new();
282        template_params.insert("teacher_page".to_string(), teacherpage.into());
283        config.template_params = Some(template_params);
284    }
285
286    // Use default database file if none set
287    config.database_file.get_or_insert(Path::new("medal.db").to_owned());
288
289    config
290}