aurelin_framework/auth/
compromised_password.rs1use std::time::Duration;
2
3use reqwest::Client;
4use sha1::{Digest, Sha1};
5
6const HIBP_RANGE_ENDPOINT: &str = "https://api.pwnedpasswords.com/range";
7
8#[derive(Clone, Debug)]
9pub struct CompromisedPasswordChecker {
10 client: Client,
11 endpoint: String,
12}
13
14impl Default for CompromisedPasswordChecker {
15 fn default() -> Self {
16 Self { client: Client::new(), endpoint: HIBP_RANGE_ENDPOINT.into() }
17 }
18}
19
20impl CompromisedPasswordChecker {
21 pub fn for_endpoint(endpoint: impl Into<String>) -> Self {
22 Self { client: Client::new(), endpoint: endpoint.into() }
23 }
24
25 pub async fn is_compromised(&self, password: &str) -> Result<bool, reqwest::Error> {
26 let digest = Sha1::digest(password.as_bytes());
27 let mut hash = String::with_capacity(digest.len() * 2);
28 for byte in digest {
29 const HEX: &[u8; 16] = b"0123456789ABCDEF";
30 hash.push(char::from(HEX[usize::from(byte >> 4)]));
31 hash.push(char::from(HEX[usize::from(byte & 0x0f)]));
32 }
33 let (prefix, suffix) = hash.split_at(5);
34 let response = self
35 .client
36 .get(format!("{}/{prefix}", self.endpoint.trim_end_matches('/')))
37 .header("Add-Padding", "true")
38 .timeout(Duration::from_secs(30))
39 .send()
40 .await?
41 .error_for_status()?
42 .text()
43 .await?;
44
45 Ok(response.lines().any(|line| {
46 let Some((candidate, count)) = line.trim().split_once(':') else {
47 return false;
48 };
49 candidate.eq_ignore_ascii_case(suffix) && count.trim().parse::<u64>().is_ok_and(|count| count > 0)
50 }))
51 }
52}