what2watch/src/auth.rs
2023-12-17 17:38:22 -08:00

92 lines
2.3 KiB
Rust

use argon2::Argon2;
use async_trait::async_trait;
use axum_login::{AuthnBackend, UserId};
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<AuthStore>;
impl AuthStore {
pub fn new(pool: SqlitePool) -> Self {
AuthStore(pool)
}
}
impl std::ops::DerefMut for AuthStore {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl std::ops::Deref for AuthStore {
type Target = SqlitePool;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[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<Option<Self::User>, Self::Error> {
let username = creds.username.trim();
let password = creds.password.trim();
let user = User::try_get(username, &self)
.await
.map_err(|_| AuthError)?;
let verifier = Argon2::default();
let hash = PasswordHash::new(&user.pwhash).map_err(|_| AuthError)?;
match verifier.verify_password(password.as_bytes(), &hash) {
Ok(_) => Ok(Some(user)),
_ => Ok(None),
}
}
async fn get_user(&self, user_id: &UserId<Self>) -> Result<Option<Self::User>, Self::Error> {
let user = sqlx::query_as("select * from users where id = ?")
.bind(user_id)
.fetch_optional(&self.0)
.await
.map_err(|_| AuthError)?;
Ok(user)
}
}
pub async fn session_layer(pool: SqlitePool) -> SessionManagerLayer<SqliteStore> {
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))
}