authbeam/
model.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use hcaptcha_no_wasm::Hcaptcha;
use std::collections::HashMap;

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};

use serde::{Deserialize, Serialize};
use databeam::DefaultReturn;

/// Basic user structure
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Profile {
    /// User ID
    pub id: String,
    /// User name
    pub username: String,
    /// Hashed user password
    pub password: String,
    /// User password salt
    pub salt: String,
    /// User login tokens
    pub tokens: Vec<String>,
    /// User IPs (these line up with the tokens in `tokens`)
    pub ips: Vec<String>,
    /// Extra information about tokens (these line up with the tokens in `tokens`)
    pub token_context: Vec<TokenContext>,
    /// Extra user information
    pub metadata: ProfileMetadata,
    /// User badges
    ///
    /// `Vec<(Text, Background, Text Color)>`
    pub badges: Vec<(String, String, String)>,
    /// User group
    pub group: i32,
    /// User join timestamp
    pub joined: u128,
    /// User tier for paid benefits
    pub tier: i32,
    /// The labels applied to the user (comma separated when as string with 1 comma at the end which creates an empty label)
    pub labels: Vec<String>,
}

impl Profile {
    /// Global user profile
    pub fn global() -> Self {
        Self {
            username: "@".to_string(),
            id: "@".to_string(),
            password: String::new(),
            salt: String::new(),
            tokens: Vec::new(),
            ips: Vec::new(),
            token_context: Vec::new(),
            group: 0,
            joined: 0,
            metadata: ProfileMetadata::default(),
            badges: Vec::new(),
            tier: 0,
            labels: Vec::new(),
        }
    }

    /// System profile
    pub fn system() -> Self {
        Self {
            username: "system".to_string(),
            id: "0".to_string(),
            password: String::new(),
            salt: String::new(),
            tokens: Vec::new(),
            ips: Vec::new(),
            token_context: Vec::new(),
            group: 0,
            joined: 0,
            metadata: ProfileMetadata::default(),
            badges: Vec::new(),
            tier: 0,
            labels: Vec::new(),
        }
    }

    /// Anonymous user profile
    pub fn anonymous(tag: String) -> Self {
        Self {
            username: "anonymous".to_string(),
            id: tag,
            password: String::new(),
            salt: String::new(),
            tokens: Vec::new(),
            ips: Vec::new(),
            token_context: Vec::new(),
            group: 0,
            joined: 0,
            metadata: ProfileMetadata::default(),
            badges: Vec::new(),
            tier: 0,
            labels: Vec::new(),
        }
    }

    /// Get the tag of an anonymous ID
    ///
    /// # Returns
    /// `(is anonymous, tag, username, input)`
    pub fn anonymous_tag(input: &str) -> (bool, String, String, String) {
        if (input != "anonymous") && !input.starts_with("anonymous#") {
            // not anonymous
            return (false, String::new(), String::new(), input.to_string());
        }

        // anonymous questions from BEFORE the anonymous tag update will just have the "anonymous" tag
        let split: Vec<&str> = input.split("#").collect();
        (
            true,
            split.get(1).unwrap_or(&"unknown").to_string(),
            split.get(0).unwrap().to_string(),
            input.to_string(),
        )
    }

    /// Clean profile information
    pub fn clean(&mut self) -> () {
        self.ips = Vec::new();
        self.tokens = Vec::new();
        self.token_context = Vec::new();
        self.salt = String::new();
        self.password = String::new();
        self.metadata = ProfileMetadata::default();
    }

    /// Get context from a token
    pub fn token_context_from_token(&self, token: &str) -> TokenContext {
        let token = databeam::utility::hash(token.to_string());

        if let Some(pos) = self.tokens.iter().position(|t| *t == token) {
            if let Some(ctx) = self.token_context.get(pos) {
                return ctx.to_owned();
            }

            return TokenContext::default();
        }

        return TokenContext::default();
    }
}

impl Default for Profile {
    fn default() -> Self {
        Self {
            id: String::new(),
            username: String::new(),
            password: String::new(),
            salt: String::new(),
            tokens: Vec::new(),
            ips: Vec::new(),
            token_context: Vec::new(),
            metadata: ProfileMetadata::default(),
            badges: Vec::new(),
            group: 0,
            joined: databeam::utility::unix_epoch_timestamp(),
            tier: 0,
            labels: Vec::new(),
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TokenContext {
    #[serde(default)]
    pub app: Option<String>,
    #[serde(default)]
    pub permissions: Option<Vec<TokenPermission>>,
    #[serde(default)]
    pub timestamp: u128,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum TokenPermission {
    /// Manage UGC (user-generated-content) uploaded by the user
    ManageAssets,
    /// Manage user metadata
    ManageProfile,
    /// Manage all user fields
    ManageAccount,
    /// Execute moderator actions
    Moderator,
    /// Generate tokens on behalf of the account
    ///
    /// Generated tokens cannot have any permissions the token used to generate it doesn't have
    GenerateTokens,
    /// Send mail to other users on behalf of the user
    SendMail,
}

impl TokenContext {
    /// Get the value of the token's `app` field
    ///
    /// Returns an empty string if the field value is `None`
    pub fn app_name(&self) -> String {
        if let Some(ref name) = self.app {
            return name.to_string();
        }

        String::new()
    }

    /// Check if the token has the given [`TokenPermission`]
    ///
    /// ### Returns `true` if the field value is `None`
    pub fn can_do(&self, permission: TokenPermission) -> bool {
        if let Some(ref permissions) = self.permissions {
            return permissions.contains(&permission);
        }

        return true;
    }
}

impl Default for TokenContext {
    fn default() -> Self {
        Self {
            app: None,
            permissions: None,
            timestamp: databeam::utility::unix_epoch_timestamp(),
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ProfileMetadata {
    #[serde(default)]
    pub email: String,
    /// Extra key-value pairs
    #[serde(default)]
    pub kv: HashMap<String, String>,
}

impl ProfileMetadata {
    /// Check if a value exists in `kv` (and isn't empty)
    pub fn exists(&self, key: &str) -> bool {
        if let Some(ref value) = self.kv.get(key) {
            if value.is_empty() {
                return false;
            }

            return true;
        }

        false
    }

    /// Check if a value in `kv` is "true"
    pub fn is_true(&self, key: &str) -> bool {
        if !self.exists(key) {
            return false;
        }

        self.kv.get(key).unwrap() == "true"
    }

    /// Get a value from `kv`, returns an empty string if it doesn't exist
    pub fn soft_get(&self, key: &str) -> String {
        if !self.exists(key) {
            return String::new();
        }

        self.kv.get(key).unwrap().to_owned()
    }

    /// Check `kv` lengths
    ///
    /// # Returns
    /// * `true`: ok
    /// * `false`: invalid
    pub fn check(&self) -> bool {
        for field in &self.kv {
            if field.0 == "sparkler:custom_css" {
                // custom_css gets an extra long value
                if field.1.len() > 64 * 128 {
                    return false;
                }

                continue;
            }

            if field.1.len() > 64 * 64 {
                return false;
            }
        }

        true
    }
}

impl ProfileMetadata {
    pub fn from_email(email: String) -> Self {
        Self {
            email,
            kv: HashMap::new(),
        }
    }
}

impl Default for ProfileMetadata {
    fn default() -> Self {
        Self {
            email: String::new(),
            kv: HashMap::new(),
        }
    }
}

/// Basic follow structure
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct UserFollow {
    /// The ID of the user following
    pub user: String,
    /// The ID of the user they are following
    pub following: String,
}

/// Basic notification structure
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Notification {
    /// The title of the notification
    pub title: String,
    /// The content of the notification
    pub content: String,
    /// The address of the notification (where it goes)
    pub address: String,
    /// The timestamp of when the notification was created
    pub timestamp: u128,
    /// The ID of the notification
    pub id: String,
    /// The recipient of the notification
    pub recipient: String,
}

/// Basic warning structure
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Warning {
    /// The ID of the warning
    pub id: String,
    /// The content of the warning
    pub content: String,
    /// The timestamp of when the warning was created
    pub timestamp: u128,
    /// The recipient of the warning
    pub recipient: String,
    /// The moderator who warned the recipient
    pub moderator: Box<Profile>,
}

/// Basic IP ban
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct IpBan {
    /// The ID of the ban
    pub id: String,
    /// The IP that was banned
    pub ip: String,
    /// The reason for the ban
    pub reason: String,
    /// The user that banned this IP
    pub moderator: Box<Profile>,
    /// The timestamp of when the ban was created
    pub timestamp: u128,
}

/// The state of a user's relationship with another user
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RelationshipStatus {
    /// No relationship
    Unknown,
    /// User two is blocked from interacting with user one
    Blocked,
    /// User two is pending a friend request from user one
    Pending,
    /// User two is friends with user one
    Friends,
}

impl Default for RelationshipStatus {
    fn default() -> Self {
        Self::Unknown
    }
}

/// A user's relationship with another user
///
/// If a relationship already exists, user two cannot attempt to create a relationship with user one.
/// The existing relation should be used.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Relationship {
    /// The first user in the relationship
    pub one: Profile,
    /// The second user in the relationship
    pub two: Profile,
    /// The status of the relationship
    pub status: RelationshipStatus,
    /// The timestamp of the relationship's creation
    pub timestamp: u128,
}

/// An IP-based block
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct IpBlock {
    /// The ID of the block
    pub id: String,
    /// The IP that was blocked
    pub ip: String,
    /// The user that blocked this IP
    pub user: String,
    /// The context of this block (question content, etc.)
    pub context: String,
    /// The timestamp of when the block was created
    pub timestamp: u128,
}

/// Rainbeam system permission
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum Permission {
    /// Permission to manage the server and managers
    Admin,
    /// Permission to manage the server and assets
    Manager,
    /// Permission to create warnings and do small moderator tasks
    Helper,
}

/// Basic permission group
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Group {
    pub name: String,
    pub id: i32,
    pub permissions: Vec<Permission>,
}

impl Default for Group {
    fn default() -> Self {
        Self {
            name: "default".to_string(),
            id: 0,
            permissions: Vec::new(),
        }
    }
}

/// Mail state
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum MailState {
    /// The mail has been sent, but has never been opened by the recipient
    Unread,
    /// The mail has been opened by the recipient at least once
    Read,
}

/// Basic mail structure
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Mail {
    /// The title of the mail
    pub title: String,
    /// The content of the mail
    pub content: String,
    /// The timestamp of when the mail was created
    pub timestamp: u128,
    /// The ID of the mail
    pub id: String,
    /// The state of the mail
    pub state: MailState,
    /// The author of the mail
    pub author: String,
    /// The recipient(s) of the mail
    pub recipient: Vec<String>,
}

/// A label which describes a user
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct UserLabel {
    /// The ID of the label (unique)
    pub id: String,
    /// The name of the label
    pub name: String,
    /// The timestamp of when the label was created
    pub timestamp: u128,
    /// The ID creator of the label
    pub creator: String,
}

// props
#[derive(Serialize, Deserialize, Debug, Hcaptcha)]
pub struct ProfileCreate {
    pub username: String,
    pub password: String,
    #[captcha]
    pub token: String,
}

#[derive(Serialize, Deserialize, Debug, Hcaptcha)]
pub struct ProfileLogin {
    pub username: String,
    pub password: String,
    #[captcha]
    pub token: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SetProfileMetadata {
    pub metadata: ProfileMetadata,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SetProfileBadges {
    pub badges: Vec<(String, String, String)>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SetProfileLabels {
    pub labels: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SetProfileGroup {
    pub group: i32,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SetProfileTier {
    pub tier: i32,
}

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

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

#[derive(Serialize, Deserialize, Debug)]
pub struct NotificationCreate {
    pub title: String,
    pub content: String,
    pub address: String,
    pub recipient: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct WarningCreate {
    pub content: String,
    pub recipient: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct IpBanCreate {
    pub ip: String,
    pub reason: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct IpBlockCreate {
    pub ip: String,
    pub context: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct MailCreate {
    pub title: String,
    pub content: String,
    pub recipient: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SetMailState {
    pub state: MailState,
}

/// General API errors
#[derive(Debug)]
pub enum DatabaseError {
    MustBeUnique,
    OutOfScope,
    NotAllowed,
    ValueError,
    NotFound,
    TooLong,
    Other,
}

impl DatabaseError {
    pub fn to_string(&self) -> String {
        use DatabaseError::*;
        match self {
            MustBeUnique => String::from("One of the given values must be unique. (MustBeUnique)"),
            OutOfScope => String::from(
                "Cannot generate tokens with permissions the provided token doesn't have. (OutOfScope)",
            ),
            NotAllowed => String::from("You are not allowed to access this resource. (NotAllowed)"),
            ValueError => String::from("One of the field values given is invalid. (ValueError)"),
            NotFound => String::from("No asset with this ID could be found. (NotFound)"),
            TooLong => String::from("Given data is too long. (TooLong)"),
            _ => String::from("An unspecified error has occured"),
        }
    }
}

impl IntoResponse for DatabaseError {
    fn into_response(self) -> Response {
        use crate::model::DatabaseError::*;
        match self {
            NotAllowed => (
                StatusCode::UNAUTHORIZED,
                Json(DefaultReturn::<u16> {
                    success: false,
                    message: self.to_string(),
                    payload: 401,
                }),
            )
                .into_response(),
            NotFound => (
                StatusCode::NOT_FOUND,
                Json(DefaultReturn::<u16> {
                    success: false,
                    message: self.to_string(),
                    payload: 404,
                }),
            )
                .into_response(),
            _ => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(DefaultReturn::<u16> {
                    success: false,
                    message: self.to_string(),
                    payload: 500,
                }),
            )
                .into_response(),
        }
    }
}