use argon2::Argon2; use async_trait::async_trait; use axum_login::{AuthUser, AuthnBackend, UserId}; use julid::Julid; use password_hash::{PasswordHash, PasswordVerifier}; use sqlx::SqlitePool; use tower_sessions::{cookie::time::Duration, Expiry, SessionManagerLayer, SqliteStore}; use crate::User; const SESSION_TTL: Duration = Duration::new((365.2422 * 24. * 3600.0) as i64, 0); #[derive(Debug, Clone)] pub struct AuthStore(SqlitePool); pub type AuthSession = axum_login::AuthSession; impl AuthStore { pub fn new(pool: SqlitePool) -> Self { AuthStore(pool) } } #[derive(Default, Debug, Clone, PartialEq, Eq)] pub struct Credentials { pub username: String, pub password: String, } #[Error] pub struct AuthError; #[async_trait] impl AuthnBackend for AuthStore { type User = User; type Credentials = Credentials; type Error = AuthError; async fn authenticate( &self, creds: Self::Credentials, ) -> Result, Self::Error> { let username = creds.username.trim(); let password = creds.password.trim(); let user = User::try_get(username, &self.0) .await .map_err(|_| AuthError)?; let verifier = Argon2::default(); let hash = PasswordHash::new(&user.pwhash).map_err(|_| AuthError)?; Ok( if verifier.verify_password(password.as_bytes(), &hash).is_ok() { Some(user) } else { None }, ) } async fn get_user(&self, user_id: &UserId) -> Result, Self::Error> { sqlx::query_as("select * from users where id = ?") .bind(user_id) .fetch_optional(&self.0) .await .map_err(|_| AuthError) } } impl AuthUser for User { type Id = Julid; fn id(&self) -> Self::Id { self.id } fn session_auth_hash(&self) -> &[u8] { self.digest.as_bytes() } } pub async fn session_layer(pool: SqlitePool) -> SessionManagerLayer { let store = SqliteStore::new(pool); store .migrate() .await .expect("Calling `migrate()` should be reliable, is the DB gone?"); SessionManagerLayer::new(store) .with_secure(true) .with_expiry(Expiry::OnInactivity(SESSION_TTL)) }