2022-09-11 16:14:07 +01:00
|
|
|
use once_cell::sync::Lazy;
|
2018-12-09 15:55:36 +00:00
|
|
|
|
2022-07-09 21:08:11 +01:00
|
|
|
use crate::errors::ServiceError;
|
|
|
|
|
2022-09-11 16:14:07 +01:00
|
|
|
pub static SECRET_KEY: Lazy<String> =
|
2023-02-19 07:12:36 +01:00
|
|
|
Lazy::new(|| std::env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(16)));
|
2018-12-09 15:55:36 +00:00
|
|
|
|
2021-10-07 03:04:59 +01:00
|
|
|
const SALT: &[u8] = b"supersecuresalt";
|
2020-12-02 12:29:03 +09:00
|
|
|
|
2023-07-09 02:19:15 +01:00
|
|
|
// PLEASE NOTE THIS IS ONLY FOR DEMO PLEASE DO MORE RESEARCH FOR PRODUCTION USE
|
2019-07-18 12:55:14 +01:00
|
|
|
pub fn hash_password(password: &str) -> Result<String, ServiceError> {
|
2023-10-29 01:08:45 +01:00
|
|
|
let config = argon2::Config {
|
2020-12-02 12:29:03 +09:00
|
|
|
secret: SECRET_KEY.as_bytes(),
|
2023-10-29 01:08:45 +01:00
|
|
|
..argon2::Config::rfc9106_low_mem()
|
2020-12-02 12:29:03 +09:00
|
|
|
};
|
2021-10-07 03:04:59 +01:00
|
|
|
argon2::hash_encoded(password.as_bytes(), SALT, &config).map_err(|err| {
|
2020-12-02 12:29:03 +09:00
|
|
|
dbg!(err);
|
|
|
|
ServiceError::InternalServerError
|
|
|
|
})
|
2018-12-09 15:55:36 +00:00
|
|
|
}
|
|
|
|
|
2019-07-18 12:55:14 +01:00
|
|
|
pub fn verify(hash: &str, password: &str) -> Result<bool, ServiceError> {
|
2022-02-18 02:44:02 +00:00
|
|
|
argon2::verify_encoded_ext(hash, password.as_bytes(), SECRET_KEY.as_bytes(), &[]).map_err(
|
|
|
|
|err| {
|
2019-07-18 12:55:14 +01:00
|
|
|
dbg!(err);
|
|
|
|
ServiceError::Unauthorized
|
2022-02-18 02:44:02 +00:00
|
|
|
},
|
|
|
|
)
|
2018-12-09 15:55:36 +00:00
|
|
|
}
|
2023-02-19 07:12:36 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use std::env;
|
|
|
|
|
|
|
|
use actix_web::cookie::Key;
|
|
|
|
|
|
|
|
use super::SECRET_KEY;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn secret_key_default() {
|
|
|
|
env::remove_var("SECRET_KEY");
|
|
|
|
|
|
|
|
assert!(Key::try_from(SECRET_KEY.as_bytes()).is_ok());
|
|
|
|
}
|
|
|
|
}
|