authbeam/api/
me.rs

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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use crate::database::Database;
use crate::model::{DatabaseError, TokenContext, TokenPermission};
use serde::{Deserialize, Serialize};
use databeam::DefaultReturn;

use axum::http::{HeaderMap, HeaderValue};
use axum::response::IntoResponse;
use axum::{extract::State, Json};
use axum_extra::extract::cookie::CookieJar;

/// Returns the current user's username
pub async fn get_request(jar: CookieJar, State(database): State<Database>) -> impl IntoResponse {
    // get user from token
    let auth_user = match jar.get("__Secure-Token") {
        Some(c) => match database
            .get_profile_by_unhashed(c.value_trimmed().to_string())
            .await
        {
            Ok(ua) => ua,
            Err(e) => {
                return Json(DefaultReturn {
                    success: false,
                    message: e.to_string(),
                    payload: (),
                });
            }
        },
        None => {
            return Json(DefaultReturn {
                success: false,
                message: DatabaseError::NotAllowed.to_string(),
                payload: (),
            });
        }
    };

    // return
    Json(DefaultReturn {
        success: true,
        message: auth_user.username,
        payload: (),
    })
}

#[derive(Serialize, Deserialize)]
pub struct DeleteProfile {
    password: String,
}

/// Delete the current user's profile
pub async fn delete_request(
    jar: CookieJar,
    State(database): State<Database>,
    Json(req): Json<DeleteProfile>,
) -> impl IntoResponse {
    // get user from token
    let auth_user = match jar.get("__Secure-Token") {
        Some(c) => match database
            .get_profile_by_unhashed(c.value_trimmed().to_string())
            .await
        {
            Ok(ua) => ua,
            Err(e) => {
                return Json(DefaultReturn {
                    success: false,
                    message: e.to_string(),
                    payload: (),
                });
            }
        },
        None => {
            return Json(DefaultReturn {
                success: false,
                message: DatabaseError::NotAllowed.to_string(),
                payload: (),
            });
        }
    };

    // get profile
    let hashed = rainbeam_shared::hash::hash_salted(req.password, auth_user.salt);

    if hashed != auth_user.password {
        return Json(DefaultReturn {
            success: false,
            message: DatabaseError::NotAllowed.to_string(),
            payload: (),
        });
    }

    // return
    if let Err(e) = database.delete_profile_by_id(auth_user.id).await {
        return Json(DefaultReturn {
            success: false,
            message: e.to_string(),
            payload: (),
        });
    }

    Json(DefaultReturn {
        success: true,
        message: "Profile deleted, goodbye!".to_string(),
        payload: (),
    })
}

/// Generate a new token and session (like logging in while already logged in)
pub async fn generate_token_request(
    jar: CookieJar,
    headers: HeaderMap,
    State(database): State<Database>,
    Json(props): Json<TokenContext>,
) -> impl IntoResponse {
    // get user from token
    let mut existing_permissions: Option<Vec<TokenPermission>> = None;
    let mut auth_user = match jar.get("__Secure-Token") {
        Some(c) => {
            let token = c.value_trimmed().to_string();

            match database.get_profile_by_unhashed(token.clone()).await {
                Ok(ua) => {
                    // check token permission
                    let token = ua.token_context_from_token(&token);

                    if let Some(ref permissions) = token.permissions {
                        existing_permissions = Some(permissions.to_owned())
                    }

                    if !token.can_do(TokenPermission::GenerateTokens) {
                        return Json(DefaultReturn {
                            success: false,
                            message: DatabaseError::NotAllowed.to_string(),
                            payload: None,
                        });
                    }

                    // return
                    ua
                }
                Err(e) => {
                    return Json(DefaultReturn {
                        success: false,
                        message: e.to_string(),
                        payload: None,
                    });
                }
            }
        }
        None => {
            return Json(DefaultReturn {
                success: false,
                message: DatabaseError::NotAllowed.to_string(),
                payload: None,
            });
        }
    };

    // for every token that doesn't have a context, insert the default context
    for (i, _) in auth_user.tokens.clone().iter().enumerate() {
        if let None = auth_user.token_context.get(i) {
            auth_user.token_context.insert(i, TokenContext::default())
        }
    }

    // get real ip
    let real_ip = if let Some(ref real_ip_header) = database.config.real_ip_header {
        headers
            .get(real_ip_header.to_owned())
            .unwrap_or(&HeaderValue::from_static(""))
            .to_str()
            .unwrap_or("")
            .to_string()
    } else {
        String::new()
    };

    // check ip
    if database.get_ipban_by_ip(real_ip.clone()).await.is_ok() {
        return Json(DefaultReturn {
            success: false,
            message: DatabaseError::NotAllowed.to_string(),
            payload: None,
        });
    }

    // check given context
    if let Some(ref permissions) = props.permissions {
        // make sure we don't want anything we don't have
        // if our permissions are "None", allow any permission to be granted
        for permission in permissions {
            if let Some(ref existing) = existing_permissions {
                if !existing.contains(permission) {
                    return Json(DefaultReturn {
                        success: false,
                        message: DatabaseError::OutOfScope.to_string(),
                        payload: None,
                    });
                }
            } else {
                break;
            }
        }
    }

    // ...
    let token = databeam::utility::uuid();
    let token_hashed = databeam::utility::hash(token.clone());

    auth_user.tokens.push(token_hashed);
    auth_user.ips.push(String::new()); // don't actually store ip, this endpoint is used by external apps
    auth_user.token_context.push(props);

    database
        .update_profile_tokens(
            auth_user.id,
            auth_user.tokens,
            auth_user.ips,
            auth_user.token_context,
        )
        .await
        .unwrap();

    // return
    return Json(DefaultReturn {
        success: true,
        message: "Generated token!".to_string(),
        payload: Some(token),
    });
}

#[derive(Serialize, Deserialize)]
pub struct UpdateTokens {
    pub tokens: Vec<String>,
}

/// Update the current user's session tokens
pub async fn update_tokens_request(
    jar: CookieJar,
    State(database): State<Database>,
    Json(req): Json<UpdateTokens>,
) -> impl IntoResponse {
    // get user from token
    let mut auth_user = match jar.get("__Secure-Token") {
        Some(c) => {
            let token = c.value_trimmed().to_string();

            match database.get_profile_by_unhashed(token.clone()).await {
                Ok(ua) => {
                    // check token permission
                    if !ua
                        .token_context_from_token(&token)
                        .can_do(TokenPermission::ManageAccount)
                    {
                        return Json(DefaultReturn {
                            success: false,
                            message: DatabaseError::NotAllowed.to_string(),
                            payload: (),
                        });
                    }

                    // return
                    ua
                }
                Err(e) => {
                    return Json(DefaultReturn {
                        success: false,
                        message: e.to_string(),
                        payload: (),
                    });
                }
            }
        }
        None => {
            return Json(DefaultReturn {
                success: false,
                message: DatabaseError::NotAllowed.to_string(),
                payload: (),
            });
        }
    };

    // for every token that doesn't have a context, insert the default context
    for (i, _) in auth_user.tokens.clone().iter().enumerate() {
        if let None = auth_user.token_context.get(i) {
            auth_user.token_context.insert(i, TokenContext::default())
        }
    }

    // get diff
    let mut removed_indexes = Vec::new();

    for (i, token) in auth_user.tokens.iter().enumerate() {
        if !req.tokens.contains(token) {
            removed_indexes.push(i);
        }
    }

    // edit dependent vecs
    for i in removed_indexes.clone() {
        if (auth_user.ips.len() < i) | (auth_user.ips.len() == 0) {
            break;
        }

        auth_user.ips.remove(i);
    }

    for i in removed_indexes.clone() {
        if (auth_user.token_context.len() < i) | (auth_user.token_context.len() == 0) {
            break;
        }

        auth_user.token_context.remove(i);
    }

    // return
    if let Err(e) = database
        .update_profile_tokens(
            auth_user.id,
            req.tokens,
            auth_user.ips,
            auth_user.token_context,
        )
        .await
    {
        return Json(DefaultReturn {
            success: false,
            message: e.to_string(),
            payload: (),
        });
    }

    Json(DefaultReturn {
        success: true,
        message: "Tokens updated!".to_string(),
        payload: (),
    })
}