forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiBbcaef90Tahinli1 month ago164 commits

model.rs291 lines, 9.1 KiBHistoryRawDownload
1//! Domain types. Stored shapes are described in docs/architecture.md, section 4.
2
3pub type Id = String;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
6#[serde(rename_all = "lowercase")]
7pub enum Visibility {
8 Public,
9 Private,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum Role {
15 Read,
16 Triage,
17 Write,
18 Maintain,
19 Admin,
20}
21
22/// What a `users` row stands for. An org is a row with `Org`; it can never authenticate.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum AccountKind {
26 User,
27 Org,
28}
29
30#[derive(Clone, PartialEq)]
31pub struct User {
32 pub id: Id,
33 pub username: String,
34 pub email: Option<String>,
35 pub password_hash: String,
36 pub is_admin: bool,
37 pub created_at: String,
38 /// Raw markdown, at most 2000 chars.
39 pub about: String,
40 /// Optional heading shown on the profile instead of the username. `None` when unset.
41 pub display_name: Option<String>,
42 /// IANA name, e.g. "Europe/Istanbul"; "UTC" by default.
43 pub timezone: String,
44 /// Hash of the current avatar, or `None` when the user has none. Filled by the user queries.
45 pub avatar_hash: Option<String>,
46 /// Colour theme: "auto", "light" or "dark". Follows the browser when "auto".
47 pub theme: String,
48 /// Language code, e.g. "en"; "auto" uses the instance default.
49 pub language: String,
50 /// Accent colour for the light theme: the id of a palette in forge-web's `accent_palette.rs`.
51 /// "sage" is the default.
52 pub accent: String,
53 /// Accent colour for the dark theme, chosen separately from `accent`. "sage" is the default.
54 pub accent_dark: String,
55 /// Base (neutral background, surface and text) set for the light theme. "fern" is the default.
56 pub base_light: String,
57 /// Base set for the dark theme. "fern" is the default.
58 pub base_dark: String,
59 /// Which side the main shell sidebar sits on: "left" (the default) or "right".
60 pub sidebar_side: String,
61 /// `User` for a person, `Org` for an organization.
62 pub kind: AccountKind,
63 /// Whether notifications are also sent by email (needs a verified email and instance mail).
64 pub email_notifications: bool,
65}
66
67impl User {
68 /// True for an organization row. Orgs never authenticate and never act as a person.
69 pub fn is_org(&self) -> bool {
70 self.kind == AccountKind::Org
71 }
72}
73
74#[derive(Debug, Clone, PartialEq)]
75pub struct Repo {
76 pub id: Id,
77 pub owner_id: Id,
78 pub owner_name: String,
79 pub name: String,
80 pub description: String,
81 pub visibility: Visibility,
82 pub default_branch: String,
83 pub archived: bool,
84 pub created_at: String,
85 /// The repo this one was forked from. `None` for originals and for forks whose parent was
86 /// deleted.
87 pub fork_of: Option<Id>,
88}
89
90#[derive(Debug, Clone, PartialEq)]
91pub struct SshKey {
92 pub id: Id,
93 pub user_id: Id,
94 pub title: String,
95 pub algorithm: String,
96 /// Raw SSH wire-format public key blob (the bytes base64-encoded in authorized_keys).
97 pub key_blob: Vec<u8>,
98 pub fingerprint: String,
99 pub created_at: String,
100 pub last_used_at: Option<String>,
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub struct AccessToken {
105 pub id: Id,
106 pub user_id: Id,
107 pub name: String,
108 pub scopes: Vec<String>,
109 pub expires_at: Option<String>,
110 pub created_at: String,
111 pub last_used_at: Option<String>,
112}
113
114#[derive(Clone, PartialEq)]
115pub struct Session {
116 pub id: Id,
117 pub user_id: Id,
118 pub csrf_token: String,
119 pub created_at: String,
120 pub expires_at: String,
121 pub last_seen: String,
122 pub user_agent: Option<String>,
123}
124
125const REDACTED: &str = "<redacted>";
126
127impl std::fmt::Debug for User {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 f.debug_struct("User")
130 .field("id", &self.id)
131 .field("username", &self.username)
132 .field("email", &self.email)
133 .field("password_hash", &REDACTED)
134 .field("is_admin", &self.is_admin)
135 .field("created_at", &self.created_at)
136 .field("about", &self.about)
137 .field("timezone", &self.timezone)
138 .field("avatar_hash", &self.avatar_hash)
139 .field("theme", &self.theme)
140 .field("language", &self.language)
141 .field("accent", &self.accent)
142 .field("accent_dark", &self.accent_dark)
143 .field("base_light", &self.base_light)
144 .field("base_dark", &self.base_dark)
145 .field("sidebar_side", &self.sidebar_side)
146 .field("kind", &self.kind)
147 .finish()
148 }
149}
150
151impl std::fmt::Debug for Session {
152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 f.debug_struct("Session")
154 .field("id", &self.id)
155 .field("user_id", &self.user_id)
156 .field("csrf_token", &REDACTED)
157 .field("created_at", &self.created_at)
158 .field("expires_at", &self.expires_at)
159 .field("last_seen", &self.last_seen)
160 .field("user_agent", &self.user_agent)
161 .finish()
162 }
163}
164
165impl Visibility {
166 pub fn as_str(&self) -> &'static str {
167 match self {
168 Visibility::Public => "public",
169 Visibility::Private => "private",
170 }
171 }
172}
173
174impl std::str::FromStr for Visibility {
175 type Err = crate::error::Error;
176
177 fn from_str(s: &str) -> Result<Self, Self::Err> {
178 match s {
179 "public" => Ok(Visibility::Public),
180 "private" => Ok(Visibility::Private),
181 other => Err(crate::error::Error::Invalid(format!(
182 "visibility {other:?}"
183 ))),
184 }
185 }
186}
187
188impl Role {
189 pub fn as_str(&self) -> &'static str {
190 match self {
191 Role::Read => "read",
192 Role::Triage => "triage",
193 Role::Write => "write",
194 Role::Maintain => "maintain",
195 Role::Admin => "admin",
196 }
197 }
198}
199
200impl std::str::FromStr for Role {
201 type Err = crate::error::Error;
202
203 fn from_str(s: &str) -> Result<Self, Self::Err> {
204 match s {
205 "read" => Ok(Role::Read),
206 "triage" => Ok(Role::Triage),
207 "write" => Ok(Role::Write),
208 "maintain" => Ok(Role::Maintain),
209 "admin" => Ok(Role::Admin),
210 other => Err(crate::error::Error::Invalid(format!("role {other:?}"))),
211 }
212 }
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 #[test]
220 fn debug_output_redacts_secrets() {
221 let user = User {
222 id: "u1".into(),
223 username: "tahinli".into(),
224 email: None,
225 password_hash: "$argon2id$SECRETHASH".into(),
226 is_admin: true,
227 created_at: "now".into(),
228 about: String::new(),
229 display_name: None,
230 timezone: "UTC".into(),
231 avatar_hash: None,
232 theme: "auto".into(),
233 language: "auto".into(),
234 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
235 accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
236 base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
237 base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
238 sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(),
239 kind: AccountKind::User,
240 email_notifications: true,
241 };
242 let session = Session {
243 id: "s1".into(),
244 user_id: "u1".into(),
245 csrf_token: "CSRFSECRET".into(),
246 created_at: "now".into(),
247 expires_at: "later".into(),
248 last_seen: "now".into(),
249 user_agent: None,
250 };
251 let dbg = format!("{user:?} {session:?}");
252 assert!(dbg.contains("\"<redacted>\""));
253 assert!(!dbg.contains("SECRETHASH"));
254 assert!(!dbg.contains("CSRFSECRET"));
255 assert!(dbg.contains("tahinli"));
256 }
257
258 #[test]
259 fn visibility_and_role_round_trip_and_keep_stored_literals() {
260 // Both are stored in the database, so the literals are pinned here.
261 let visibility = [
262 (Visibility::Public, "public"),
263 (Visibility::Private, "private"),
264 ];
265 for (v, literal) in visibility {
266 assert_eq!(v.as_str(), literal, "case visibility {literal}");
267 assert_eq!(
268 literal.parse::<Visibility>().ok(),
269 Some(v),
270 "case visibility {literal}"
271 );
272 }
273 assert!(
274 "Public".parse::<Visibility>().is_err(),
275 "case visibility casing"
276 );
277
278 let roles = [
279 (Role::Read, "read"),
280 (Role::Triage, "triage"),
281 (Role::Write, "write"),
282 (Role::Maintain, "maintain"),
283 (Role::Admin, "admin"),
284 ];
285 for (r, literal) in roles {
286 assert_eq!(r.as_str(), literal, "case role {literal}");
287 assert_eq!(literal.parse::<Role>().ok(), Some(r), "case role {literal}");
288 }
289 assert!("owner".parse::<Role>().is_err(), "case role owner");
290 }
291}