use std::collections::HashSet;
use sha2::{Digest, Sha256};
pub struct AuthConfig {
digests: HashSet<[u8; 32]>,
}
impl AuthConfig {
pub fn new(tokens: impl IntoIterator<Item = String>) -> AuthConfig {
AuthConfig {
digests: tokens.into_iter().map(|token| digest(&token)).collect(),
}
}
pub fn accepts(&self, token: &str) -> bool {
self.digests.contains(&digest(token))
}
}
fn digest(token: &str) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(token.as_bytes());
hasher.finalize().into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_a_configured_token_and_rejects_others() {
let auth = AuthConfig::new(["alpha".to_string(), "beta".to_string()]);
assert!(auth.accepts("alpha"));
assert!(auth.accepts("beta"));
assert!(!auth.accepts("gamma"));
assert!(!auth.accepts(""));
assert!(!auth.accepts("alph"));
}
#[test]
fn an_empty_set_accepts_nothing() {
let auth = AuthConfig::new(std::iter::empty());
assert!(!auth.accepts("alpha"));
}
}