Skip to main content

sunday_slate/auth/
backend.rs

1use axum_login::{AuthUser, AuthnBackend};
2
3use super::password;
4use crate::User;
5use crate::users::store as users;
6use crate::{AppError, Db};
7
8#[derive(Clone)]
9pub struct Credentials {
10    pub email: String,
11    pub password: String,
12}
13
14impl AuthnBackend for Db {
15    type User = User;
16    type Credentials = Credentials;
17    type Error = AppError;
18
19    async fn authenticate(&self, creds: Credentials) -> Result<Option<User>, AppError> {
20        let Some(mut user) = users::find_by_email(self.reader(), &creds.email).await? else {
21            return Ok(None);
22        };
23
24        if !password::verify(&creds.password, &user.password_hash) {
25            return Ok(None);
26        }
27
28        // Transparently upgrade the stored hash when its params are outdated.
29        if password::is_obsolete(&user.password_hash) {
30            let new_hash = password::hash(&creds.password);
31            self.write_tx(async |conn| -> Result<(), sqlx::Error> {
32                users::update_password_hash(&mut *conn, user.id, &new_hash).await
33            })
34            .await?;
35            user.password_hash = new_hash;
36        }
37
38        Ok(Some(user))
39    }
40
41    async fn get_user(&self, user_id: &<User as AuthUser>::Id) -> Result<Option<User>, AppError> {
42        Ok(users::find_by_id(self.reader(), *user_id).await?)
43    }
44}