Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix clippy lint & refactor if let Some to OptionFuture #18

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions src/http/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use argon2::{Argon2, PasswordHash};
use axum::extract::Extension;
use axum::routing::{get, post};
use axum::{Json, Router};
use futures::future::OptionFuture;

use crate::http::error::{Error, ResultExt};
use crate::http::extractor::AuthUser;
Expand Down Expand Up @@ -169,11 +170,9 @@ async fn update_user(
}

// WTB `Option::map_async()`
let password_hash = if let Some(password) = req.user.password {
Some(hash_password(password).await?)
} else {
None
};
let password_hash = OptionFuture::from(req.user.password.map(hash_password))
.await
.transpose()?;

let user = sqlx::query!(
// This is how we do optional updates of fields without needing a separate query for each.
Expand Down Expand Up @@ -218,7 +217,7 @@ async fn update_user(
async fn hash_password(password: String) -> Result<String> {
// Argon2 hashing is designed to be computationally intensive,
// so we need to do this on a blocking thread.
Ok(tokio::task::spawn_blocking(move || -> Result<String> {
tokio::task::spawn_blocking(move || -> Result<String> {
let salt = SaltString::generate(rand::thread_rng());
Ok(
PasswordHash::generate(Argon2::default(), password, salt.as_str())
Expand All @@ -227,11 +226,11 @@ async fn hash_password(password: String) -> Result<String> {
)
})
.await
.context("panic in generating password hash")??)
.context("panic in generating password hash")?
}

async fn verify_password(password: String, password_hash: String) -> Result<()> {
Ok(tokio::task::spawn_blocking(move || -> Result<()> {
tokio::task::spawn_blocking(move || -> Result<()> {
let hash = PasswordHash::new(&password_hash)
.map_err(|e| anyhow::anyhow!("invalid password hash: {}", e))?;

Expand All @@ -242,5 +241,5 @@ async fn verify_password(password: String, password_hash: String) -> Result<()>
})
})
.await
.context("panic in verifying password hash")??)
.context("panic in verifying password hash")?
}