torrust_index/config/v2/
auth.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5/// Authentication options.
6#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
7pub struct Auth {
8    /// The secret key used to sign JWT tokens.
9    #[serde(default = "Auth::default_user_claim_token_pepper")]
10    pub user_claim_token_pepper: ClaimTokenPepper,
11
12    /// The password constraints
13    #[serde(default = "Auth::default_password_constraints")]
14    pub password_constraints: PasswordConstraints,
15}
16
17impl Default for Auth {
18    fn default() -> Self {
19        Self {
20            password_constraints: Self::default_password_constraints(),
21            user_claim_token_pepper: Self::default_user_claim_token_pepper(),
22        }
23    }
24}
25
26impl Auth {
27    pub fn override_user_claim_token_pepper(&mut self, user_claim_token_pepper: &str) {
28        self.user_claim_token_pepper = ClaimTokenPepper::new(user_claim_token_pepper);
29    }
30
31    fn default_user_claim_token_pepper() -> ClaimTokenPepper {
32        ClaimTokenPepper::new("MaxVerstappenWC2021")
33    }
34
35    fn default_password_constraints() -> PasswordConstraints {
36        PasswordConstraints::default()
37    }
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
41pub struct ClaimTokenPepper(String);
42
43impl ClaimTokenPepper {
44    /// # Panics
45    ///
46    /// Will panic if the key if empty.
47    #[must_use]
48    pub fn new(key: &str) -> Self {
49        assert!(!key.is_empty(), "secret key cannot be empty");
50
51        Self(key.to_owned())
52    }
53
54    #[must_use]
55    pub fn as_bytes(&self) -> &[u8] {
56        self.0.as_bytes()
57    }
58}
59
60impl fmt::Display for ClaimTokenPepper {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        write!(f, "{}", self.0)
63    }
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
67pub struct PasswordConstraints {
68    /// The maximum password length.
69    #[serde(default = "PasswordConstraints::default_max_password_length")]
70    pub max_password_length: usize,
71    /// The minimum password length.
72    #[serde(default = "PasswordConstraints::default_min_password_length")]
73    pub min_password_length: usize,
74}
75
76impl Default for PasswordConstraints {
77    fn default() -> Self {
78        Self {
79            max_password_length: Self::default_max_password_length(),
80            min_password_length: Self::default_min_password_length(),
81        }
82    }
83}
84
85impl PasswordConstraints {
86    fn default_min_password_length() -> usize {
87        6
88    }
89
90    fn default_max_password_length() -> usize {
91        64
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::ClaimTokenPepper;
98
99    #[test]
100    #[should_panic(expected = "secret key cannot be empty")]
101    fn secret_key_can_not_be_empty() {
102        drop(ClaimTokenPepper::new(""));
103    }
104}