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

ambee/giterated

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

Fixes

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨b87f0a3

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