JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Base protocol refactor complete

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨079d544

⁨giterated-models/src/model/user.rs⁩ - ⁨2281⁩ bytes
Raw
1 use std::fmt::{Display, Formatter};
2 use std::str::FromStr;
3
4 use secrecy::{CloneableSecret, DebugSecret, SerializableSecret, Zeroize};
5 use serde::{Deserialize, Serialize};
6
7 use crate::operation::GiteratedObject;
8
9 use super::instance::Instance;
10
11 /// A user, defined by its username and instance.
12 ///
13 /// # Textual Format
14 /// A user's textual reference is defined as:
15 ///
16 /// `{username: String}:{instance: Instance}`
17 ///
18 /// # Examples
19 /// For the user with the username `barson` and the instance `giterated.dev`,
20 /// the following [`User`] initialization would be valid:
21 ///
22 /// ```
23 /// let user = User {
24 /// username: String::from("barson"),
25 /// instance: Instance::from_str("giterated.dev").unwrap()
26 /// };
27 ///
28 /// // This is correct
29 /// assert_eq!(User::from_str("barson:giterated.dev").unwrap(), user);
30 /// ```
31 #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
32 pub struct User {
33 pub username: String,
34 pub instance: Instance,
35 }
36
37 impl GiteratedObject for User {
38 fn object_name() -> &'static str {
39 "user"
40 }
41
42 fn from_object_str(object_str: &str) -> Result<Self, anyhow::Error> {
43 Ok(User::from_str(object_str).unwrap())
44 }
45 }
46
47 impl Display for User {
48 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49 write!(f, "{}:{}", self.username, self.instance.url)
50 }
51 }
52
53 impl From<String> for User {
54 fn from(user_string: String) -> Self {
55 User::from_str(&user_string).unwrap()
56 }
57 }
58
59 impl FromStr for User {
60 type Err = UserParseError;
61
62 fn from_str(s: &str) -> Result<Self, Self::Err> {
63 if s.contains('/') {
64 return Err(UserParseError);
65 }
66
67 let mut colon_split = s.split(':');
68 let username = colon_split.next().unwrap().to_string();
69 let instance = Instance::from_str(colon_split.next().unwrap()).unwrap();
70
71 Ok(Self { username, instance })
72 }
73 }
74
75 #[derive(thiserror::Error, Debug)]
76 #[error("failed to parse user")]
77 pub struct UserParseError;
78
79 #[derive(Clone, Debug, Serialize, Deserialize)]
80 pub struct Password(pub String);
81
82 impl Zeroize for Password {
83 fn zeroize(&mut self) {
84 self.0.zeroize()
85 }
86 }
87
88 impl SerializableSecret for Password {}
89 impl CloneableSecret for Password {}
90 impl DebugSecret for Password {}
91