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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use std::sync::Arc;

use axum::extract::{FromRef, Path, Query, State};
use axum::response::IntoResponse;
use http::StatusCode;
use serde::{Deserialize, Serialize};
use spacetimedb::auth::identity::encode_token_with_expiry;
use spacetimedb_lib::de::serde::DeserializeWrapper;
use spacetimedb_lib::Identity;

use crate::auth::{SpacetimeAuth, SpacetimeAuthHeader};
use crate::{log_and_500, ControlCtx, ControlNodeDelegate};

#[derive(Deserialize)]
pub struct CreateIdentityQueryParams {
    email: Option<email_address::EmailAddress>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateIdentityResponse {
    identity: String,
    token: String,
}

pub async fn create_identity(
    State(ctx): State<Arc<dyn ControlCtx>>,
    Query(CreateIdentityQueryParams { email }): Query<CreateIdentityQueryParams>,
) -> axum::response::Result<impl IntoResponse> {
    let auth = SpacetimeAuth::alloc(&*ctx).await?;
    if let Some(email) = email {
        ctx.control_db()
            .associate_email_spacetime_identity(auth.identity, email.as_str())
            .await
            .unwrap();
    }

    let identity_response = CreateIdentityResponse {
        identity: auth.identity.to_hex(),
        token: auth.creds.token().to_owned(),
    };
    Ok(axum::Json(identity_response))
}

#[derive(Debug, Clone, Serialize)]
pub struct GetIdentityResponse {
    identities: Vec<GetIdentityResponseEntry>,
}

#[derive(Debug, Clone, Serialize)]
pub struct GetIdentityResponseEntry {
    identity: String,
    email: String,
}

#[derive(Deserialize)]
pub struct GetIdentityQueryParams {
    email: Option<String>,
}
pub async fn get_identity(
    State(ctx): State<Arc<dyn ControlCtx>>,
    Query(GetIdentityQueryParams { email }): Query<GetIdentityQueryParams>,
) -> axum::response::Result<impl IntoResponse> {
    let lookup = match email {
        None => None,
        Some(email) => {
            let identities = ctx
                .control_db()
                .get_identities_for_email(email.as_str())
                .map_err(log_and_500)?;
            if identities.is_empty() {
                None
            } else {
                let mut response = GetIdentityResponse {
                    identities: Vec::<GetIdentityResponseEntry>::new(),
                };

                for identity_email in identities {
                    response.identities.push(GetIdentityResponseEntry {
                        identity: identity_email.identity.to_hex(),
                        email: identity_email.email,
                    })
                }
                Some(response)
            }
        }
    };
    let identity_response = lookup.ok_or(StatusCode::NOT_FOUND)?;
    Ok(axum::Json(identity_response))
}

/// A version of `Identity` appropriate for URL de/encoding.
///
/// Because `Identity` is represented in SATS as a `ProductValue`,
/// its serialized format is somewhat gnarly.
/// When URL-encoding identities, we want to use only the hex string,
/// without wrapping it in a `ProductValue`.
/// This keeps our routes pretty, like `/identity/<64 hex chars>/set-email`.
///
/// This newtype around `Identity` implements `Deserialize`
/// directly from the inner identity bytes,
/// without the enclosing `ProductValue` wrapper.
pub struct IdentityForUrl(Identity);

impl From<IdentityForUrl> for Identity {
    /// Consumes `self` returning the backing `Identity`.
    fn from(IdentityForUrl(id): IdentityForUrl) -> Identity {
        id
    }
}

impl<'de> serde::Deserialize<'de> for IdentityForUrl {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        <_>::deserialize(de).map(|DeserializeWrapper(b)| IdentityForUrl(Identity::from_byte_array(b)))
    }
}

#[derive(Deserialize)]
pub struct SetEmailParams {
    identity: IdentityForUrl,
}

#[derive(Deserialize)]
pub struct SetEmailQueryParams {
    email: email_address::EmailAddress,
}

pub async fn set_email(
    State(ctx): State<Arc<dyn ControlCtx>>,
    Path(SetEmailParams { identity }): Path<SetEmailParams>,
    Query(SetEmailQueryParams { email }): Query<SetEmailQueryParams>,
    auth: SpacetimeAuthHeader,
) -> axum::response::Result<impl IntoResponse> {
    let identity = identity.into();
    let auth = auth.get().ok_or(StatusCode::BAD_REQUEST)?;

    if auth.identity != identity {
        return Err(StatusCode::UNAUTHORIZED.into());
    }

    ctx.control_db()
        .associate_email_spacetime_identity(identity, email.as_str())
        .await
        .unwrap();

    Ok(())
}

#[derive(Deserialize)]
pub struct GetDatabasesParams {
    identity: IdentityForUrl,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetDatabasesResponse {
    addresses: Vec<String>,
}

pub async fn get_databases(
    State(ctx): State<Arc<dyn ControlCtx>>,
    Path(GetDatabasesParams { identity }): Path<GetDatabasesParams>,
) -> axum::response::Result<impl IntoResponse> {
    let identity = identity.into();
    // Linear scan for all databases that have this identity, and return their addresses
    let all_dbs = ctx.control_db().get_databases().await.map_err(|e| {
        log::error!("Failure when retrieving databases for search: {}", e);
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    let matching_dbs = all_dbs.into_iter().filter(|db| db.identity == identity);
    let addresses = matching_dbs.map(|db| db.address.to_hex());
    let response = GetDatabasesResponse {
        addresses: addresses.collect(),
    };
    Ok(axum::Json(response))
}

#[derive(Debug, Serialize)]
pub struct WebsocketTokenResponse {
    token: String,
}

pub async fn create_websocket_token(
    State(ctx): State<Arc<dyn ControlCtx>>,
    auth: SpacetimeAuthHeader,
) -> axum::response::Result<impl IntoResponse> {
    match auth.auth {
        Some(auth) => {
            let token = encode_token_with_expiry(ctx.private_key(), auth.identity, Some(60)).map_err(log_and_500)?;
            Ok(axum::Json(WebsocketTokenResponse { token }))
        }
        None => Err(StatusCode::UNAUTHORIZED)?,
    }
}

pub fn router<S>() -> axum::Router<S>
where
    S: ControlNodeDelegate + Clone + 'static,
    Arc<dyn ControlCtx>: FromRef<S>,
{
    use axum::routing::{get, post};
    axum::Router::new()
        .route("/", get(get_identity).post(create_identity))
        .route("/websocket_token", post(create_websocket_token))
        .route("/:identity/set-email", post(set_email))
        .route("/:identity/databases", get(get_databases))
}