1use std::fmt;
2use std::sync::Arc;
3
4use time::{Duration, OffsetDateTime};
5use url::Url;
6
7use crate::crypto::{Argon2id, PasswordHasher};
8use crate::models::Session;
9use crate::rate_limit::RateLimit;
10
11type PasswordPolicy = Arc<dyn Fn(&str) -> bool + Send + Sync>;
12
13#[derive(Clone)]
15pub struct EmailPassword {
16 pub(crate) min_password_length: usize,
17 pub(crate) max_password_length: usize,
18 pub(crate) require_email_verification: bool,
19 pub(crate) auto_sign_in: bool,
20 pub(crate) revoke_sessions_on_password_reset: bool,
21 pub(crate) reset_password_ttl: Duration,
22 pub(crate) password_policy: Option<PasswordPolicy>,
23 pub(crate) hasher: Arc<dyn PasswordHasher>,
24}
25
26impl fmt::Debug for EmailPassword {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 f.debug_struct("EmailPassword")
29 .field("min_password_length", &self.min_password_length)
30 .field("max_password_length", &self.max_password_length)
31 .field(
32 "require_email_verification",
33 &self.require_email_verification,
34 )
35 .field("auto_sign_in", &self.auto_sign_in)
36 .finish_non_exhaustive()
37 }
38}
39
40impl Default for EmailPassword {
41 fn default() -> Self {
42 Self {
43 min_password_length: 8,
44 max_password_length: 128,
45 require_email_verification: false,
46 auto_sign_in: true,
47 revoke_sessions_on_password_reset: false,
48 reset_password_ttl: Duration::hours(1),
49 password_policy: None,
50 hasher: Arc::new(Argon2id::owasp()),
51 }
52 }
53}
54
55impl EmailPassword {
56 pub fn min_password_length(mut self, n: usize) -> Self {
57 self.min_password_length = n;
58 self
59 }
60
61 pub fn max_password_length(mut self, n: usize) -> Self {
62 self.max_password_length = n;
63 self
64 }
65
66 pub fn require_email_verification(mut self, on: bool) -> Self {
68 self.require_email_verification = on;
69 self
70 }
71
72 pub fn auto_sign_in(mut self, on: bool) -> Self {
74 self.auto_sign_in = on;
75 self
76 }
77
78 pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
79 self.revoke_sessions_on_password_reset = on;
80 self
81 }
82
83 pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
84 self.reset_password_ttl = ttl;
85 self
86 }
87
88 pub fn password_policy(
90 mut self,
91 policy: impl Fn(&str) -> bool + Send + Sync + 'static,
92 ) -> Self {
93 self.password_policy = Some(Arc::new(policy));
94 self
95 }
96
97 pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
98 self.hasher = Arc::new(hasher);
99 self
100 }
101}
102
103#[derive(Clone, Debug)]
104pub struct EmailVerification {
105 pub(crate) send_on_sign_up: bool,
106 pub(crate) auto_sign_in_after_verification: bool,
107 pub(crate) ttl: Duration,
108}
109
110impl Default for EmailVerification {
111 fn default() -> Self {
112 Self {
113 send_on_sign_up: true,
114 auto_sign_in_after_verification: false,
115 ttl: Duration::hours(1),
116 }
117 }
118}
119
120impl EmailVerification {
121 pub fn send_on_sign_up(mut self, on: bool) -> Self {
122 self.send_on_sign_up = on;
123 self
124 }
125
126 pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
127 self.auto_sign_in_after_verification = on;
128 self
129 }
130
131 pub fn ttl(mut self, ttl: Duration) -> Self {
132 self.ttl = ttl;
133 self
134 }
135}
136
137#[derive(Clone, Debug)]
138pub struct SessionConfig {
139 pub(crate) expires_in: Duration,
140 pub(crate) update_age: Duration,
141 pub(crate) fresh_age: Duration,
142 pub(crate) cookie_cache: Option<Duration>,
143}
144
145impl Default for SessionConfig {
146 fn default() -> Self {
147 Self {
148 expires_in: Duration::days(7),
149 update_age: Duration::days(1),
150 fresh_age: Duration::days(1),
151 cookie_cache: None,
152 }
153 }
154}
155
156impl SessionConfig {
157 pub fn expires_in(mut self, d: Duration) -> Self {
158 self.expires_in = d;
159 self
160 }
161
162 pub fn update_age(mut self, d: Duration) -> Self {
164 self.update_age = d;
165 self
166 }
167
168 pub fn fresh_age(mut self, d: Duration) -> Self {
170 self.fresh_age = d;
171 self
172 }
173
174 pub fn cookie_cache(mut self, max_age: Duration) -> Self {
177 self.cookie_cache = Some(max_age);
178 self
179 }
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub enum SameSite {
184 Strict,
185 Lax,
186 None,
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum Secure {
191 Auto,
193 Always,
194 Never,
195}
196
197#[derive(Clone, Debug)]
198pub struct CookieConfig {
199 pub(crate) prefix: String,
200 pub(crate) same_site: SameSite,
201 pub(crate) domain: Option<String>,
202 pub(crate) secure: Secure,
203}
204
205impl Default for CookieConfig {
206 fn default() -> Self {
207 Self {
208 prefix: "fastauth".into(),
209 same_site: SameSite::Lax,
210 domain: None,
211 secure: Secure::Auto,
212 }
213 }
214}
215
216impl CookieConfig {
217 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
219 self.prefix = prefix.into();
220 self
221 }
222
223 pub fn same_site(mut self, same_site: SameSite) -> Self {
224 self.same_site = same_site;
225 self
226 }
227
228 pub fn domain(mut self, domain: impl Into<String>) -> Self {
229 self.domain = Some(domain.into());
230 self
231 }
232
233 pub fn secure(mut self, secure: Secure) -> Self {
234 self.secure = secure;
235 self
236 }
237}
238
239#[derive(Clone, Debug, PartialEq, Eq)]
241pub enum ClientIp {
242 Socket,
244 Header(String),
246}
247
248#[derive(Clone, Debug)]
250pub struct CoreConfig {
251 pub app_name: String,
252 pub base_url: Url,
253 pub base_path: String,
254 pub trusted_origins: Vec<String>,
255 pub session: SessionConfig,
256 pub cookies: CookieConfig,
257 pub email_password: Option<EmailPassword>,
258 pub email_verification: EmailVerification,
259 pub rate_limit: RateLimit,
260 pub client_ip: ClientIp,
261 pub(crate) secure_cookies: bool,
262}
263
264impl CoreConfig {
265 pub fn auth_url(&self) -> String {
267 format!(
268 "{}{}",
269 self.base_url.as_str().trim_end_matches('/'),
270 self.base_path
271 )
272 }
273
274 pub fn is_trusted_origin(&self, origin: &str) -> bool {
275 let origin = origin.trim_end_matches('/');
276 origin == self.base_url.origin().ascii_serialization()
277 || self.trusted_origins.iter().any(|o| o == origin)
278 }
279
280 pub fn is_safe_redirect(&self, target: &str) -> bool {
282 if target.starts_with('/') {
283 return !target.starts_with("//") && !target.starts_with("/\\");
284 }
285 Url::parse(target).is_ok_and(|u| self.is_trusted_origin(&u.origin().ascii_serialization()))
286 }
287
288 pub fn is_fresh(&self, session: &Session) -> bool {
291 let fresh_age = self.session.fresh_age;
292 fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
293 }
294
295 pub fn cookie_name(&self, name: &str) -> String {
296 let secure = if self.secure_cookies { "__Secure-" } else { "" };
297 format!("{secure}{}.{name}", self.cookies.prefix)
298 }
299}