7.8 KiB · text History 01e509e
//! "Forgot password?": the app's half of neiam-auth's password reset.
//!
//! The crate owns the token (only its SHA-256 stored, one hour, single use,
//! voided by a password or email change), the routes (`/password/forgot`,
//! `/password/reset`), the neutral answer, the limits and the mail's text.
//! This adapter:
//!
//! * finds accounts by email (case-insensitive);
//! * gives a link to active accounts, including ones created through NEIAM
//!   that have no password yet, when the login mode lets them use one
//!   (`neiam_auth::sea_orm::password_reset::account_state`); a mail saying
//!   "sign in with NEIAM" when `OIDC_LOGIN_MODE=sso` requires it; nothing
//!   for deactivated or currently suspended accounts;
//! * hashes with the app's argon2 settings and its 8-character rule;
//! * revokes every web session and every paired device's API token;
//! * marks the address verified (the link reached it, and the token is only
//!   valid while the account still has that address);
//! * sends the mail through the app's own mailer (`AppState::mailer`:
//!   mail-prism, or the log), keyed per token for mail-prism's idempotency;
//! * limits per client IP with the address `client_ip::layer` resolved
//!   (`TRUSTED_PROXIES`), not the crate's header guess;
//! * sends the user to `/login?reset=1` afterwards.
use std::net::IpAddr;
use std::sync::Arc;

use axum::http::request::Parts;
use axum::response::{IntoResponse, Redirect, Response};
use chrono::Utc;
use minijinja::context;
use neiam_auth::password_reset::{
    self as reset, Account, AccountState, BoxError, Mailer, OutgoingMail, Page, PasswordReset,
    ResetApp, ResetConfig, SendMail,
};
use neiam_auth::sea_orm::password_reset::{SeaOrmTokenStore, account_state};
use sea_orm::sea_query::{Expr, Func};
use sea_orm::*;
use uuid::Uuid;

use crate::AppState;
use crate::auth::{password, verification};
use crate::entities::{api_tokens, user_sessions, users};
use crate::mailer::RawMessage;

#[derive(Clone)]
pub struct RecourseReset {
    pub state: AppState,
}

pub type Reset = PasswordReset<RecourseReset, SeaOrmTokenStore>;

/// The service: the app's mailer, `PUBLIC_URL` for the link,
/// `PASSWORD_RESET_TTL_MINUTES` (default 60), off (404) without local login.
pub fn service(state: AppState) -> Reset {
    let mut cfg = ResetConfig::from_env(state.config.app_name.clone(), &state.config.public_url);
    // The app's own PUBLIC_URL (and its default) wins.
    cfg.public_url = state.config.public_url.trim_end_matches('/').to_string();
    cfg.enabled = crate::handlers::auth::local_login(&state);
    cfg.client_ip = resolved_client_ip;
    service_with(state, cfg)
}

pub fn service_with(state: AppState, cfg: ResetConfig) -> Reset {
    let mailer = Mailer::custom(AppMailer(state.mailer.clone()));
    service_with_mailer(state, cfg, mailer)
}

pub fn service_with_mailer(state: AppState, cfg: ResetConfig, mailer: Mailer) -> Reset {
    let store = SeaOrmTokenStore::new(state.db.clone());
    PasswordReset::new(RecourseReset { state }, store, mailer, cfg)
}

pub fn router<S: Clone + Send + Sync + 'static>(reset: Reset) -> axum::Router<S> {
    reset::router(reset)
}

/// The address `client_ip::layer` resolved and stamped on the request (it
/// strips any copy the client sent).
pub(crate) fn resolved_client_ip(parts: &Parts) -> Option<IpAddr> {
    if let Some(crate::client_ip::ClientIp(ip)) =
        parts.extensions.get::<crate::client_ip::ClientIp>()
    {
        return *ip;
    }
    parts
        .headers
        .get(crate::client_ip::RESOLVED_HEADER)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse().ok())
}

/// The reset mail through the app's own mailer.
struct AppMailer(Arc<dyn crate::mailer::Mailer>);

impl SendMail for AppMailer {
    fn send<'a>(
        &'a self,
        mail: &'a OutgoingMail,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), BoxError>> + Send + 'a>>
    {
        Box::pin(async move {
            let raw = RawMessage {
                to: mail.to.clone(),
                subject: mail.subject.clone(),
                text: mail.text.clone(),
                html: mail.html.clone(),
                idempotency_key: mail.idempotency_key.clone(),
                label: "password-reset",
            };
            self.0
                .send_raw(&raw)
                .await
                .map_err(|e| Box::new(e) as BoxError)
        })
    }
}

impl RecourseReset {
    fn db(&self) -> &DatabaseConnection {
        self.state.db.as_ref()
    }

    async fn account(&self, u: users::Model) -> Result<Account, BoxError> {
        let suspended = crate::policy::suspension(&u).is_some();
        let state = if suspended {
            AccountState::Disabled
        } else {
            account_state(
                self.db(),
                &self.state.config.oidc,
                u.id,
                u.is_active,
                crate::handlers::auth::local_login(&self.state),
            )
            .await?
        };
        Ok(Account {
            id: u.id,
            email: u.email,
            name: u.username,
            password_hash: Some(u.password_hash),
            state,
        })
    }
}

impl ResetApp for RecourseReset {
    async fn find_by_email(&self, email: &str) -> Result<Option<Account>, BoxError> {
        let found = users::Entity::find()
            .filter(
                Expr::expr(Func::lower(Expr::col(users::Column::Email))).eq(email.to_lowercase()),
            )
            .one(self.db())
            .await?;
        match found {
            Some(u) => Ok(Some(self.account(u).await?)),
            None => Ok(None),
        }
    }

    async fn find_by_id(&self, id: Uuid) -> Result<Option<Account>, BoxError> {
        match users::Entity::find_by_id(id).one(self.db()).await? {
            Some(u) => Ok(Some(self.account(u).await?)),
            None => Ok(None),
        }
    }

    async fn set_password(&self, id: Uuid, new_password: &str) -> Result<(), BoxError> {
        let hash = password::hash_password(new_password)?;
        let user = users::Entity::find_by_id(id)
            .one(self.db())
            .await?
            .ok_or("user vanished")?;
        let mut am: users::ActiveModel = user.clone().into();
        am.password_hash = Set(hash);
        am.updated_at = Set(Utc::now().into());
        let user = am.update(self.db()).await?;
        // The link reached this address, and the token is only valid while
        // the account still has it.
        verification::mark_verified(self.db(), &user).await?;
        Ok(())
    }

    /// Web sessions and every paired device's API token: a reset is how an
    /// account is taken back, so nothing signed in before survives.
    async fn revoke_sessions(&self, id: Uuid) -> Result<(), BoxError> {
        user_sessions::Entity::delete_many()
            .filter(user_sessions::Column::UserId.eq(id))
            .exec(self.db())
            .await?;
        api_tokens::Entity::delete_many()
            .filter(api_tokens::Column::UserId.eq(id))
            .exec(self.db())
            .await?;
        Ok(())
    }

    async fn after_reset(&self, _account: &Account, _parts: &Parts) -> Response {
        Redirect::to("/login?reset=1").into_response()
    }

    async fn render(&self, page: Page<'_>, _parts: &Parts) -> Response {
        let app_name = &self.state.config.app_name;
        let ctx = match &page {
            Page::Forgot { error } => context! { title => "Forgot password", app_name, error },
            Page::Sent => context! { title => "Check your email", app_name },
            Page::Reset {
                token,
                error,
                min_length,
            } => context! { title => "Choose a new password", app_name, token, error, min_length },
            Page::Invalid => context! { title => "Reset link invalid", app_name },
        };
        crate::handlers::render(&self.state, page.template(), ctx).into_response()
    }
}