mod flows;
mod notifier;
mod pg;
mod routes;
mod store;
mod token;
use std::fmt;
use std::time::Duration;
pub use flows::Accounts;
pub use notifier::{AccountMail, AccountNotifier, MemoryAccountNotifier};
pub use pg::PgAccountTokenStore;
pub use routes::{AccountRoutes, DEFAULT_BASE_PATH};
pub use store::{Account, AccountStore, MemoryAccountStore};
pub use token::{AccountToken, AccountTokenStore, MemoryAccountTokenStore, TokenKind, TokenRecord};
use crate::password::PasswordError;
use crate::session::SessionError;
#[cfg(doc)]
use crate::{PasswordHasher, Sessions};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountsConfig {
pub verify_ttl: Duration,
pub reset_ttl: Duration,
pub min_password_len: usize,
pub max_password_len: usize,
}
impl Default for AccountsConfig {
fn default() -> Self {
Self {
verify_ttl: Duration::from_secs(24 * 60 * 60),
reset_ttl: Duration::from_secs(30 * 60),
min_password_len: 12,
max_password_len: 256,
}
}
}
impl AccountsConfig {
pub fn ttl(&self, kind: TokenKind) -> Duration {
match kind {
TokenKind::VerifyEmail => self.verify_ttl,
TokenKind::ResetPassword => self.reset_ttl,
}
}
pub fn check_password(&self, password: &str) -> Result<(), AccountError> {
let len = password.chars().count();
if len < self.min_password_len {
return Err(AccountError::WeakPassword(format!(
"a password needs at least {} characters",
self.min_password_len
)));
}
if len > self.max_password_len {
return Err(AccountError::WeakPassword(format!(
"a password may have at most {} characters",
self.max_password_len
)));
}
Ok(())
}
}
pub fn normalize_email(raw: &str) -> Option<String> {
let email = raw.trim();
let (local, domain) = email.split_once('@')?;
let ok = !local.is_empty()
&& local.len() <= 64
&& email.len() <= 254
&& !domain.contains('@')
&& !domain.split('.').any(str::is_empty)
&& !email.chars().any(|c| c.is_whitespace() || c.is_control());
ok.then(|| email.to_lowercase())
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AccountError {
InvalidEmail,
WeakPassword(String),
EmailTaken,
InvalidToken,
ExpiredToken,
Storage(String),
Password(PasswordError),
Session(SessionError),
Notify(String),
Random(String),
}
impl AccountError {
pub fn http_status(&self) -> u16 {
match self {
Self::InvalidEmail | Self::WeakPassword(_) => 422,
Self::EmailTaken => 409,
Self::InvalidToken | Self::ExpiredToken => 400,
Self::Storage(_) | Self::Session(_) | Self::Notify(_) => 503,
Self::Password(_) | Self::Random(_) => 500,
}
}
}
impl fmt::Display for AccountError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidEmail => f.write_str("not a valid email address"),
Self::WeakPassword(m) => f.write_str(m),
Self::EmailTaken => f.write_str("an account with this email address exists"),
Self::InvalidToken => f.write_str("the link is invalid or was already used"),
Self::ExpiredToken => f.write_str("the link has expired; ask for a new one"),
Self::Storage(m) => write!(f, "account storage: {m}"),
Self::Password(e) => write!(f, "{e}"),
Self::Session(e) => write!(f, "{e}"),
Self::Notify(m) => write!(f, "account mail: {m}"),
Self::Random(m) => write!(f, "random source: {m}"),
}
}
}
impl std::error::Error for AccountError {}
impl From<PasswordError> for AccountError {
fn from(e: PasswordError) -> Self {
Self::Password(e)
}
}
impl From<SessionError> for AccountError {
fn from(e: SessionError) -> Self {
Self::Session(e)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_are_short_lived_tokens_and_a_12_character_minimum() {
let c = AccountsConfig::default();
assert_eq!(c.ttl(TokenKind::ResetPassword), Duration::from_secs(1800));
assert_eq!(c.ttl(TokenKind::VerifyEmail), Duration::from_secs(86_400));
assert!(c.check_password("eleven char").is_err());
assert!(c.check_password("twelve chars").is_ok());
assert!(c.check_password(&"x".repeat(257)).is_err());
}
#[test]
fn addresses_are_trimmed_lowercased_and_checked() {
assert_eq!(
normalize_email(" Carol@Ledger.Example "),
Some("carol@ledger.example".into())
);
for bad in [
"",
"carol",
"@ledger.example",
"carol@",
"carol@ledger..example",
"carol@a@b",
"ca rol@ledger.example",
&format!("{}@x.y", "a".repeat(65)),
] {
assert_eq!(normalize_email(bad), None, "{bad}");
}
}
#[test]
fn statuses_and_messages() {
let cases = [
(AccountError::InvalidEmail, 422),
(AccountError::WeakPassword("short".into()), 422),
(AccountError::EmailTaken, 409),
(AccountError::InvalidToken, 400),
(AccountError::ExpiredToken, 400),
(AccountError::Storage("db".into()), 503),
(
AccountError::Session(SessionError::Storage("db".into())),
503,
),
(AccountError::Notify("smtp".into()), 503),
(AccountError::Password(PasswordError::Blocking), 500),
(AccountError::Random("rng".into()), 500),
];
for (error, status) in cases {
assert_eq!(error.http_status(), status, "{error:?}");
assert!(!error.to_string().is_empty());
}
assert_eq!(
AccountError::from(PasswordError::Blocking),
AccountError::Password(PasswordError::Blocking)
);
}
}