rok-core 0.6.0

Core primitives for the rok ecosystem — errors, crypto, i18n, config, DI, and more
Documentation
mod auth_finder;
mod config;
mod driver;
mod drivers;
mod error;

pub use auth_finder::AuthFinder;
pub use config::{Argon2Config, BcryptConfig, Driver, HashConfig, ScryptConfig};
pub use error::HashError;

use std::sync::Arc;

use driver::HashDriver;
use drivers::{argon2::Argon2Driver, bcrypt::BcryptDriver, scrypt::ScryptDriver};

pub struct Hasher {
    inner: Arc<dyn HashDriver>,
}

impl Hasher {
    pub fn from_config(config: HashConfig) -> Self {
        let inner: Arc<dyn HashDriver> = match config.driver {
            Driver::Argon2 => Arc::new(Argon2Driver::new(config.argon2)),
            Driver::Bcrypt => Arc::new(BcryptDriver::new(config.bcrypt)),
            Driver::Scrypt => Arc::new(ScryptDriver::new(config.scrypt)),
        };
        Self { inner }
    }

    pub fn make(&self, password: &str) -> Result<String, HashError> {
        self.inner.hash(password)
    }

    pub fn verify(&self, password: &str, hash: &str) -> Result<bool, HashError> {
        self.inner.verify(password, hash)
    }

    pub fn needs_rehash(&self, hash: &str) -> bool {
        self.inner.needs_rehash(hash)
    }

    pub fn verify_for<U: AuthFinder>(&self, password: &str, user: &U) -> Result<bool, HashError> {
        self.verify(password, user.get_auth_password())
    }

    pub fn needs_rehash_for<U: AuthFinder>(&self, user: &U) -> bool {
        self.needs_rehash(user.get_auth_password())
    }
}

impl Clone for Hasher {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}