diff --git a/README.md b/README.md index 14cea4c..315587a 100644 --- a/README.md +++ b/README.md @@ -321,6 +321,27 @@ csrf = '' session = '' ``` +#### Environment variables + +The cookies can also be overridden by environment variables, which might be useful to exclude the sensitive information from the configuration file `leetcode.toml`. To do this, you can leave the `csrf` and `session` fields empty in the configuration file and override cookies settings via the environment variables `LEETCODE_CSRF`, `LEETCODE_SESSION`, and `LEETCODE_SITE`: + +```toml +[cookies] +csrf = '' +session = '' +site = 'leetcode.com' +``` + +Then set the environment variables: + +```bash +export LEETCODE_CSRF='' +export LEETCODE_SESSION='' +export LEETCODE_SITE='leetcode.cn' # or 'leetcode.com' +``` + +Note that `cookies.site` in still required in the `leetcode.toml` to avoid exception during configuration file parsing, but can be overridden using environment variables. + ## Programmable If you want to filter LeetCode questions using custom Python scripts, add the following to your the configuration file: diff --git a/src/config/cookies.rs b/src/config/cookies.rs index 6c5f5c6..8492780 100644 --- a/src/config/cookies.rs +++ b/src/config/cookies.rs @@ -62,3 +62,27 @@ impl Display for Cookies { ) } } + +/// Override cookies from environment variables +pub const LEETCODE_CSRF_ENV: &str = "LEETCODE_CSRF"; +pub const LEETCODE_SESSION_ENV: &str = "LEETCODE_SESSION"; +pub const LEETCODE_SITE_ENV: &str = "LEETCODE_SITE"; + +impl Cookies { + /// Load cookies from environment variables, overriding any existing values + /// if the environment variables are set. + pub fn with_env_override(mut self) -> Self { + if let Ok(csrf) = std::env::var(LEETCODE_CSRF_ENV) { + self.csrf = csrf; + } + if let Ok(session) = std::env::var(LEETCODE_SESSION_ENV) { + self.session = session; + } + if let Ok(site) = std::env::var(LEETCODE_SITE_ENV) { + if let Ok(leetcode_site) = LeetcodeSite::from_str(&site) { + self.site = leetcode_site; + } + } + self + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index c1d9a4e..f3f5e40 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -46,14 +46,19 @@ impl Config { let s = fs::read_to_string(&conf)?; match toml::from_str::(&s) { - Ok(config) => match config.cookies.site { - cookies::LeetcodeSite::LeetcodeCom => Ok(config), - cookies::LeetcodeSite::LeetcodeCn => { - let mut config = config; - config.sys.urls = sys::Urls::new_with_leetcode_cn(); - Ok(config) + Ok(mut config) => { + // Override config.cookies with environment variables + config.cookies = config.cookies.with_env_override(); + + match config.cookies.site { + cookies::LeetcodeSite::LeetcodeCom => Ok(config), + cookies::LeetcodeSite::LeetcodeCn => { + let mut config = config; + config.sys.urls = sys::Urls::new_with_leetcode_cn(); + Ok(config) + } } - }, + } Err(e) => { let tmp = Self::root()?.join("leetcode.tmp.toml"); Self::write_default(tmp)?;