~vpzom/lotide

ref: 32fee9a2e36802f2ed56b8c905aef19c4cae4b2a lotide/src/routes/api/forgot_password.rs -rw-r--r-- 4.6 KiB
32fee9a2 — Colin Reeder Add endpoint for checking forgot password key validity 2 months ago
                                                                                
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
use crate::UserLocalID;
use lettre::Tokio02Transport;
use rand::Rng;
use serde_derive::Deserialize;
use std::borrow::Cow;
use std::sync::Arc;

struct ForgotPasswordKey {
    value: i32,
}

impl ForgotPasswordKey {
    pub fn generate() -> Self {
        Self {
            value: rand::thread_rng().gen(),
        }
    }

    pub fn as_int(&self) -> i32 {
        self.value
    }
}

// implementing this trait is discouraged in favor of Display, but bs58 doesn't do streaming output
impl std::string::ToString for ForgotPasswordKey {
    fn to_string(&self) -> String {
        bs58::encode(&self.value.to_be_bytes()).into_string()
    }
}

impl std::str::FromStr for ForgotPasswordKey {
    type Err = bs58::decode::Error;

    fn from_str(src: &str) -> Result<Self, Self::Err> {
        let mut buf = [0; 4];
        bs58::decode(src).into(&mut buf)?;
        Ok(Self {
            value: i32::from_be_bytes(buf),
        })
    }
}

async fn route_unstable_forgot_password_keys_create(
    _: (),
    ctx: Arc<crate::RouteContext>,
    req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, crate::Error> {
    let lang = crate::get_lang_for_req(&req);

    if ctx.mailer.is_none() {
        return Err(crate::Error::UserError(crate::simple_response(
            hyper::StatusCode::INTERNAL_SERVER_ERROR,
            lang.tr("email_not_configured", None).into_owned(),
        )));
    }

    #[derive(Deserialize)]
    struct ForgotPasswordBody<'a> {
        email_address: Cow<'a, str>,
    }

    let body = hyper::body::to_bytes(req.into_body()).await?;
    let body: ForgotPasswordBody = serde_json::from_slice(&body)?;

    let db = ctx.db_pool.get().await?;

    let user_row = db.query_opt("SELECT id, username, email_address FROM person WHERE local AND LOWER(email_address) = LOWER($1)", &[&body.email_address]).await?
        .ok_or_else(|| {
            crate::Error::UserError(crate::simple_response(
                hyper::StatusCode::BAD_REQUEST,
                lang.tr("no_such_local_user_by_email", None).into_owned(),
            ))
        })?;

    let user_id = UserLocalID(user_row.get(0));
    let username: &str = user_row.get(1);
    let user_email: &str = user_row.get(2);

    let user_email = lettre::Mailbox::new(None, user_email.parse()?);

    let key = ForgotPasswordKey::generate();
    db.execute(
        "INSERT INTO forgot_password_key (key, person, created) VALUES ($1, $2, current_timestamp)",
        &[&key.as_int(), &user_id],
    )
    .await?;

    let msg_body = lang
        .tr(
            "email_content_forgot_password",
            Some(&fluent::fluent_args!["key" => key.to_string(), "username" => username]),
        )
        .into_owned();

    let msg = lettre::Message::builder()
        .date_now()
        .subject("Forgot Password Request")
        .from(ctx.mail_from.as_ref().unwrap().clone())
        .to(user_email)
        .singlepart(
            lettre::message::SinglePart::binary()
                .header(lettre::message::header::ContentType::text_utf8())
                .body(msg_body),
        )?;

    crate::spawn_task(async move {
        ctx.mailer.as_ref().unwrap().send(msg).await?;

        Ok(())
    });

    Ok(hyper::Response::builder()
        .header(hyper::header::CONTENT_TYPE, "application/json")
        .body("{}".into())?)
}

async fn route_unstable_forgot_password_keys_get(
    params: (ForgotPasswordKey,),
    ctx: Arc<crate::RouteContext>,
    req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, crate::Error> {
    let (key,) = params;

    let lang = crate::get_lang_for_req(&req);
    let db = ctx.db_pool.get().await?;

    let row = db.query_opt("SELECT created < (current_timestamp - INTERVAL '1 HOUR') FROM forgot_password_key WHERE key=$1", &[&key.as_int()]).await?;

    let found = match row {
        None => false,
        Some(row) => !row.get::<_, bool>(0),
    };

    if found {
        Ok(hyper::Response::builder()
            .header(hyper::header::CONTENT_TYPE, "application/json")
            .body("{}".into())?)
    } else {
        Err(crate::Error::UserError(crate::simple_response(
            hyper::StatusCode::NOT_FOUND,
            lang.tr("no_such_forgot_password_key", None).into_owned(),
        )))
    }
}

pub fn route_forgot_password() -> crate::RouteNode<()> {
    crate::RouteNode::new().with_child(
        "keys",
        crate::RouteNode::new()
            .with_handler_async("POST", route_unstable_forgot_password_keys_create)
            .with_child_parse::<ForgotPasswordKey, _>(
                crate::RouteNode::new()
                    .with_handler_async("GET", route_unstable_forgot_password_keys_get),
            ),
    )
}