55 lines
1.8 KiB
Rust
55 lines
1.8 KiB
Rust
use anyhow::{anyhow, Context};
|
|
use argon2::{password_hash::SaltString, Argon2};
|
|
use rand::rngs::OsRng;
|
|
|
|
use argon2::{PasswordHash, PasswordHasher, PasswordVerifier};
|
|
use sqlx::SqlitePool;
|
|
use tokio::task;
|
|
|
|
pub(super) async fn verify_hashed_value(value: String, hash: String) -> anyhow::Result<()> {
|
|
task::spawn_blocking(move || {
|
|
let hash = PasswordHash::new(&hash)?;
|
|
Argon2::default()
|
|
.verify_password(value.as_bytes(), &hash)
|
|
.map_err(|_| anyhow!("Couldn't verify hashed value"))
|
|
})
|
|
.await?
|
|
}
|
|
|
|
pub(super) async fn hash_value(value: String) -> anyhow::Result<String> {
|
|
task::spawn_blocking(move || {
|
|
let salt = SaltString::generate(&mut OsRng);
|
|
let argon2 = Argon2::default();
|
|
Ok(argon2.hash_password(value.as_bytes(), &salt)?.to_string())
|
|
})
|
|
.await?
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(super) mod tests {
|
|
use crate::*;
|
|
use posts::Post;
|
|
use sqlx::{ConnectOptions, SqlitePool};
|
|
|
|
pub(crate) async fn get_init_db(pool: SqlitePool) -> anyhow::Result<(BlogDb, i64)> {
|
|
let user = "evie";
|
|
let password = "hunter2".to_string();
|
|
let db_url = pool.connect_options().to_url_lossy().to_string();
|
|
let db = BlogDb::new(user, password.clone(), db_url).await?;
|
|
let session_id = db.new_session(user, password, "+1 year").await?;
|
|
Ok((db, session_id))
|
|
}
|
|
|
|
pub(crate) async fn init_and_add_post(pool: SqlitePool) -> anyhow::Result<(BlogDb, i64, Post)> {
|
|
let (db, session_id) = get_init_db(pool).await?;
|
|
let post = db.add_post("hello", "", "").await?;
|
|
let resulting_post = db.get_post(post.id).await?;
|
|
|
|
assert_eq!(resulting_post.title, "hello");
|
|
assert_eq!(resulting_post.tags, "");
|
|
assert_eq!(resulting_post.content, "");
|
|
|
|
Ok((db, session_id, post))
|
|
}
|
|
}
|