89 lines
2.6 KiB
Rust
89 lines
2.6 KiB
Rust
use argon2::{
|
|
Argon2,
|
|
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
|
|
};
|
|
use axum::{
|
|
extract::{Request, State},
|
|
http::{StatusCode, header::AUTHORIZATION},
|
|
middleware::Next,
|
|
response::Response,
|
|
};
|
|
use base64::{Engine, engine::general_purpose::STANDARD};
|
|
use sqlx::SqlitePool;
|
|
|
|
#[derive(Clone)]
|
|
pub struct User {
|
|
pub username: String,
|
|
}
|
|
|
|
/**
|
|
* Check Basic auth.
|
|
* If present, check password.
|
|
* If user doesn't exist, create it.
|
|
*/
|
|
pub async fn authorize(
|
|
State(db): State<SqlitePool>,
|
|
mut request: Request,
|
|
next: Next,
|
|
) -> Result<Response, StatusCode> {
|
|
let Some(header) = request.headers().get(AUTHORIZATION) else {
|
|
return Ok(next.run(request).await);
|
|
};
|
|
|
|
let (_, encoded) = header
|
|
.to_str()
|
|
.ok()
|
|
.and_then(|value| value.split_once(' '))
|
|
.filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Basic"))
|
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
|
|
|
let decoded = STANDARD
|
|
.decode(encoded)
|
|
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
|
|
|
let credentials = String::from_utf8(decoded).map_err(|_| StatusCode::UNAUTHORIZED)?;
|
|
let (username, password) = credentials
|
|
.split_once(':')
|
|
.filter(|(username, _)| !username.is_empty())
|
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
|
|
|
let argon2 = Argon2::default();
|
|
let mut hash = get_password_hash(&db, username).await?;
|
|
|
|
if hash.is_none() {
|
|
let new_hash: PasswordHash = argon2
|
|
.hash_password(password.as_bytes())
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
sqlx::query(
|
|
"INSERT INTO users (username, pass_hash) VALUES (?, ?) ON CONFLICT(username) DO NOTHING",
|
|
)
|
|
.bind(username)
|
|
.bind(new_hash.to_string())
|
|
.execute(&db)
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
|
|
hash = get_password_hash(&db, username).await?;
|
|
}
|
|
|
|
let hash = hash.ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
let hash = PasswordHash::new(&hash).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
argon2
|
|
.verify_password(password.as_bytes(), &hash)
|
|
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
|
|
|
request.extensions_mut().insert(User {
|
|
username: username.to_owned(),
|
|
});
|
|
|
|
Ok(next.run(request).await)
|
|
}
|
|
|
|
async fn get_password_hash(db: &SqlitePool, username: &str) -> Result<Option<String>, StatusCode> {
|
|
sqlx::query_scalar("SELECT pass_hash FROM users WHERE username = ?")
|
|
.bind(username)
|
|
.fetch_optional(db)
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
|
}
|