forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiB3d53dfdTahinli1 month ago208 commits

model.rs299 lines, 9.4 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 /// The address the session signed in from.
124 pub ip: Option<String>,
125 /// The address of the most recent request.
126 pub last_ip: Option<String>,
127}
128
129const REDACTED: &str = "<redacted>";
130
131impl std::fmt::Debug for User {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 f.debug_struct("User")
134 .field("id", &self.id)
135 .field("username", &self.username)
136 .field("email", &self.email)
137 .field("password_hash", &REDACTED)
138 .field("is_admin", &self.is_admin)
139 .field("created_at", &self.created_at)
140 .field("about", &self.about)
141 .field("timezone", &self.timezone)
142 .field("avatar_hash", &self.avatar_hash)
143 .field("theme", &self.theme)
144 .field("language", &self.language)
145 .field("accent", &self.accent)
146 .field("accent_dark", &self.accent_dark)
147 .field("base_light", &self.base_light)
148 .field("base_dark", &self.base_dark)
149 .field("sidebar_side", &self.sidebar_side)
150 .field("kind", &self.kind)
151 .finish()
152 }
153}
154
155impl std::fmt::Debug for Session {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 f.debug_struct("Session")
158 .field("id", &self.id)
159 .field("user_id", &self.user_id)
160 .field("csrf_token", &REDACTED)
161 .field("created_at", &self.created_at)
162 .field("expires_at", &self.expires_at)
163 .field("last_seen", &self.last_seen)
164 .field("user_agent", &self.user_agent)
165 .field("ip", &self.ip)
166 .field("last_ip", &self.last_ip)
167 .finish()
168 }
169}
170
171impl Visibility {
172 pub fn as_str(&self) -> &'static str {
173 match self {
174 Visibility::Public => "public",
175 Visibility::Private => "private",
176 }
177 }
178}
179
180impl std::str::FromStr for Visibility {
181 type Err = crate::error::Error;
182
183 fn from_str(s: &str) -> Result<Self, Self::Err> {
184 match s {
185 "public" => Ok(Visibility::Public),
186 "private" => Ok(Visibility::Private),
187 other => Err(crate::error::Error::Invalid(format!(
188 "visibility {other:?}"
189 ))),
190 }
191 }
192}
193
194impl Role {
195 pub fn as_str(&self) -> &'static str {
196 match self {
197 Role::Read => "read",
198 Role::Triage => "triage",
199 Role::Write => "write",
200 Role::Maintain => "maintain",
201 Role::Admin => "admin",
202 }
203 }
204}
205
206impl std::str::FromStr for Role {
207 type Err = crate::error::Error;
208
209 fn from_str(s: &str) -> Result<Self, Self::Err> {
210 match s {
211 "read" => Ok(Role::Read),
212 "triage" => Ok(Role::Triage),
213 "write" => Ok(Role::Write),
214 "maintain" => Ok(Role::Maintain),
215 "admin" => Ok(Role::Admin),
216 other => Err(crate::error::Error::Invalid(format!("role {other:?}"))),
217 }
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn debug_output_redacts_secrets() {
227 let user = User {
228 id: "u1".into(),
229 username: "tahinli".into(),
230 email: None,
231 password_hash: "$argon2id$SECRETHASH".into(),
232 is_admin: true,
233 created_at: "now".into(),
234 about: String::new(),
235 display_name: None,
236 timezone: "UTC".into(),
237 avatar_hash: None,
238 theme: "auto".into(),
239 language: "auto".into(),
240 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
241 accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
242 base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
243 base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
244 sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(),
245 kind: AccountKind::User,
246 email_notifications: true,
247 };
248 let session = Session {
249 id: "s1".into(),
250 user_id: "u1".into(),
251 csrf_token: "CSRFSECRET".into(),
252 created_at: "now".into(),
253 expires_at: "later".into(),
254 last_seen: "now".into(),
255 user_agent: None,
256 ip: None,
257 last_ip: None,
258 };
259 let dbg = format!("{user:?} {session:?}");
260 assert!(dbg.contains("\"<redacted>\""));
261 assert!(!dbg.contains("SECRETHASH"));
262 assert!(!dbg.contains("CSRFSECRET"));
263 assert!(dbg.contains("tahinli"));
264 }
265
266 #[test]
267 fn visibility_and_role_round_trip_and_keep_stored_literals() {
268 // Both are stored in the database, so the literals are pinned here.
269 let visibility = [
270 (Visibility::Public, "public"),
271 (Visibility::Private, "private"),
272 ];
273 for (v, literal) in visibility {
274 assert_eq!(v.as_str(), literal, "case visibility {literal}");
275 assert_eq!(
276 literal.parse::<Visibility>().ok(),
277 Some(v),
278 "case visibility {literal}"
279 );
280 }
281 assert!(
282 "Public".parse::<Visibility>().is_err(),
283 "case visibility casing"
284 );
285
286 let roles = [
287 (Role::Read, "read"),
288 (Role::Triage, "triage"),
289 (Role::Write, "write"),
290 (Role::Maintain, "maintain"),
291 (Role::Admin, "admin"),
292 ];
293 for (r, literal) in roles {
294 assert_eq!(r.as_str(), literal, "case role {literal}");
295 assert_eq!(literal.parse::<Role>().ok(), Some(r), "case role {literal}");
296 }
297 assert!("owner".parse::<Role>().is_err(), "case role owner");
298 }
299}