1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use axum::{
    extract::{Path, State},
    response::{Html, IntoResponse, Response},
    Form,
};
use hyper::StatusCode;
use mas_axum_utils::{
    cookies::CookieJar,
    csrf::{CsrfExt, ProtectedForm},
    FancyError, SessionInfoExt,
};
use mas_data_model::SiteConfig;
use mas_router::UrlBuilder;
use mas_storage::{
    job::{JobRepositoryExt, SendAccountRecoveryEmailsJob},
    BoxClock, BoxRepository, BoxRng,
};
use mas_templates::{EmptyContext, RecoveryProgressContext, TemplateContext, Templates};
use ulid::Ulid;

use crate::{Limiter, PreferredLanguage, RequesterFingerprint};

pub(crate) async fn get(
    mut rng: BoxRng,
    clock: BoxClock,
    mut repo: BoxRepository,
    State(site_config): State<SiteConfig>,
    State(templates): State<Templates>,
    State(url_builder): State<UrlBuilder>,
    PreferredLanguage(locale): PreferredLanguage,
    cookie_jar: CookieJar,
    Path(id): Path<Ulid>,
) -> Result<Response, FancyError> {
    if !site_config.account_recovery_allowed {
        let context = EmptyContext.with_language(locale);
        let rendered = templates.render_recovery_disabled(&context)?;
        return Ok((cookie_jar, Html(rendered)).into_response());
    }

    let (session_info, cookie_jar) = cookie_jar.session_info();
    let (csrf_token, cookie_jar) = cookie_jar.csrf_token(&clock, &mut rng);

    let maybe_session = session_info.load_session(&mut repo).await?;
    if maybe_session.is_some() {
        // TODO: redirect to continue whatever action was going on
        return Ok((cookie_jar, url_builder.redirect(&mas_router::Index)).into_response());
    }

    let Some(recovery_session) = repo.user_recovery().lookup_session(id).await? else {
        // XXX: is that the right thing to do?
        return Ok((
            cookie_jar,
            url_builder.redirect(&mas_router::AccountRecoveryStart),
        )
            .into_response());
    };

    if recovery_session.consumed_at.is_some() {
        let context = EmptyContext.with_language(locale);
        let rendered = templates.render_recovery_consumed(&context)?;
        return Ok((cookie_jar, Html(rendered)).into_response());
    }

    let context = RecoveryProgressContext::new(recovery_session, false)
        .with_csrf(csrf_token.form_value())
        .with_language(locale);

    repo.save().await?;

    let rendered = templates.render_recovery_progress(&context)?;

    Ok((cookie_jar, Html(rendered)).into_response())
}

pub(crate) async fn post(
    mut rng: BoxRng,
    clock: BoxClock,
    mut repo: BoxRepository,
    State(site_config): State<SiteConfig>,
    State(templates): State<Templates>,
    State(url_builder): State<UrlBuilder>,
    (State(limiter), requester): (State<Limiter>, RequesterFingerprint),
    PreferredLanguage(locale): PreferredLanguage,
    cookie_jar: CookieJar,
    Path(id): Path<Ulid>,
    Form(form): Form<ProtectedForm<()>>,
) -> Result<Response, FancyError> {
    if !site_config.account_recovery_allowed {
        let context = EmptyContext.with_language(locale);
        let rendered = templates.render_recovery_disabled(&context)?;
        return Ok((cookie_jar, Html(rendered)).into_response());
    }

    let (session_info, cookie_jar) = cookie_jar.session_info();
    let (csrf_token, cookie_jar) = cookie_jar.csrf_token(&clock, &mut rng);

    let maybe_session = session_info.load_session(&mut repo).await?;
    if maybe_session.is_some() {
        // TODO: redirect to continue whatever action was going on
        return Ok((cookie_jar, url_builder.redirect(&mas_router::Index)).into_response());
    }

    let Some(recovery_session) = repo.user_recovery().lookup_session(id).await? else {
        // XXX: is that the right thing to do?
        return Ok((
            cookie_jar,
            url_builder.redirect(&mas_router::AccountRecoveryStart),
        )
            .into_response());
    };

    if recovery_session.consumed_at.is_some() {
        let context = EmptyContext.with_language(locale);
        let rendered = templates.render_recovery_consumed(&context)?;
        return Ok((cookie_jar, Html(rendered)).into_response());
    }

    // Verify the CSRF token
    let () = cookie_jar.verify_form(&clock, form)?;

    // Check the rate limit if we are about to process the form
    if let Err(e) = limiter.check_account_recovery(requester, &recovery_session.email) {
        tracing::warn!(error = &e as &dyn std::error::Error);
        let context = RecoveryProgressContext::new(recovery_session, true)
            .with_csrf(csrf_token.form_value())
            .with_language(locale);
        let rendered = templates.render_recovery_progress(&context)?;

        return Ok((StatusCode::TOO_MANY_REQUESTS, (cookie_jar, Html(rendered))).into_response());
    }

    // Schedule a new batch of emails
    repo.job()
        .schedule_job(SendAccountRecoveryEmailsJob::new(&recovery_session))
        .await?;

    repo.save().await?;

    let context = RecoveryProgressContext::new(recovery_session, false)
        .with_csrf(csrf_token.form_value())
        .with_language(locale);

    let rendered = templates.render_recovery_progress(&context)?;

    Ok((cookie_jar, Html(rendered)).into_response())
}