1use crate::*;
2use axum::extract::{FromRequest, Multipart};
3use rusqlite::{OptionalExtension, params as sql};
4
5fn uuid(id: &str) -> Result<()> {
6 if regex::Regex::new(
7 r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
8 )
9 .unwrap()
10 .is_match(id)
11 {
12 Ok(())
13 } else {
14 Err(Error::new(400, "No user with that id"))
15 }
16}
17fn profile(body: &Value, full: bool) -> Result<Value> {
18 let mut profile = serde_json::Map::new();
19 let username_pattern = regex::Regex::new(r"^[a-z0-9][a-z0-9._@-]*$").unwrap();
20 for key in [
21 "username",
22 "email",
23 "firstName",
24 "lastName",
25 "enabled",
26 "emailVerified",
27 "requiredActions",
28 ] {
29 let Some(value) = body.get(key) else {
30 if full && ["username", "email", "firstName", "lastName"].contains(&key) {
31 return Err(Error::new(400, "Enter a user profile."));
32 }
33 continue;
34 };
35 let value = match key {
36 "username" => {
37 let v = string(value).trim().to_lowercase();
38 if v.starts_with("ai-") || v.starts_with("api-") {
39 return Err(Error::new(400, "Choose a username without the ai- or api- prefix. Those are reserved for service accounts."));
40 }
41 if v.len() > 254 || !username_pattern.is_match(&v) {
42 return Err(Error::new(
43 400,
44 "Usernames use lowercase letters, digits, dots, dashes, and @",
45 ));
46 }
47 json!(v)
48 }
49 "email" | "firstName" | "lastName" => {
50 let v = value
51 .as_str()
52 .ok_or_else(|| Error::new(400, "Enter a name or email address."))?
53 .trim();
54 if v.len() > 254 {
55 return Err(Error::new(400, "Use a shorter name or email address."));
56 }
57 if key == "email" && !v.is_empty() && (!v.contains('@') || v.contains(' ')) {
58 return Err(Error::new(400, "Enter a full email address"));
59 }
60 if v.is_empty() { Value::Null } else { json!(v) }
61 }
62 "enabled" | "emailVerified" => {
63 if !value.is_boolean() {
64 return Err(Error::new(400, "Invalid profile."));
65 }
66 value.clone()
67 }
68 _ => {
69 if !value.is_array() || array(value).iter().any(|v| v != "UPDATE_PASSWORD") {
70 return Err(Error::new(400, "Invalid required actions."));
71 }
72 value.clone()
73 }
74 };
75 profile.insert(key.into(), value);
76 }
77 Ok(Value::Object(profile))
78}
79fn password(value: &Value) -> Result<&str> {
80 value
81 .as_str()
82 .filter(|s| s.chars().count() >= 8 && s.len() <= 1024)
83 .ok_or_else(|| Error::new(400, "Use at least 8 characters"))
84}
85
86pub(crate) fn revoke_connections(app: &App, id: &str) -> Result<()> {
87 let mut db = app.mcp.db.lock().unwrap();
88 let transaction = db.transaction()?;
89 for grant in mcp::list(&transaction, "grant:")? {
90 if grant["user"] == id {
91 mcp::revoke(&transaction, string(&grant["id"]))?;
92 }
93 }
94 transaction.execute(
95 "DELETE FROM records WHERE json_extract(value,'$.owner')=?",
96 [id],
97 )?;
98 transaction.commit()?;
99 Ok(())
100}
101
102pub async fn self_user(app: &App, me: &Value) -> Result<Value> {
103 let db = app.auth.db.lock().unwrap();
104 let id: Option<String> = db
105 .query_row(
106 "SELECT id FROM users WHERE username=?",
107 [string(&me["name"])],
108 |r| r.get(0),
109 )
110 .optional()?;
111 auth::user(
112 &db,
113 &id.ok_or_else(|| Error::new(401, "Sign in again to open your account."))?,
114 )
115}
116
117pub async fn route(
118 app: Arc<App>,
119 method: &Method,
120 parts: &[&str],
121 me: &Value,
122 body: Value,
123) -> Result<Response> {
124 if parts == ["groups"] && method == Method::PUT {
125 let users: Vec<String> = serde_json::from_value(body["users"].clone())
126 .map_err(|_| Error::new(400, "Select users to edit."))?;
127 let add: Vec<String> = serde_json::from_value(body["add"].clone())
128 .map_err(|_| Error::new(400, "Choose groups to add."))?;
129 let remove: Vec<String> = serde_json::from_value(body["remove"].clone())
130 .map_err(|_| Error::new(400, "Choose groups to remove."))?;
131 if users.is_empty() || (add.is_empty() && remove.is_empty()) {
132 return Err(Error::new(
133 400,
134 "Select users and change at least one group.",
135 ));
136 }
137 let mut db = app.auth.db.lock().unwrap();
138 let transaction = db.transaction()?;
139 for group in add.iter().chain(&remove) {
140 if add.contains(group) && remove.contains(group) {
141 return Err(Error::new(
142 400,
143 "Choose whether to add or remove each group.",
144 ));
145 }
146 let exists: bool = transaction.query_row(
147 "SELECT EXISTS(SELECT 1 FROM roles WHERE id=?)",
148 [group],
149 |r| r.get(0),
150 )?;
151 if !exists {
152 return Err(Error::new(
153 400,
154 "This group no longer exists. Reload the page.",
155 ));
156 }
157 }
158 for id in &users {
159 uuid(id)?;
160 let user = auth::user(&transaction, id)?;
161 if guest::is_guest(&user) || user["kind"] == "ai" {
162 return Err(Error::new(
163 400,
164 "Guests can use Shale only. Select regular accounts to edit groups.",
165 ));
166 }
167 for group in &add {
168 transaction.execute(
169 "INSERT OR IGNORE INTO memberships VALUES (?,?)",
170 sql![id, group],
171 )?;
172 }
173 for group in &remove {
174 if user["username"] == me["name"]
175 && array(&user["groups"])
176 .iter()
177 .any(|g| g["id"] == *group && g["name"] == "infra-admin")
178 {
179 return Err(Error::new(
180 400,
181 "Sign in as another admin to remove your admin access.",
182 ));
183 }
184 transaction.execute(
185 "DELETE FROM memberships WHERE user_id=? AND role_id=?",
186 sql![id, group],
187 )?;
188 }
189 transaction.execute("DELETE FROM pending WHERE kind IN ('authentication','registration','handoff') AND json_extract(data,'$.user')=?", [id])?;
190 }
191 transaction.commit()?;
192 drop(db);
193 if !remove.is_empty() {
194 for id in users {
195 revoke_connections(&app, &id)?;
196 }
197 }
198 return Ok(StatusCode::NO_CONTENT.into_response());
199 }
200 if parts == ["guests"] && method == Method::POST {
201 return Ok(axum::Json(
202 guest::add(&app.auth, string(&body["provider"]), string(&body["handle"])).await?,
203 )
204 .into_response());
205 }
206 if parts.is_empty() && method == Method::GET {
207 let db = app.auth.db.lock().unwrap();
208 let mut statement = db.prepare("SELECT id FROM users WHERE coalesce(json_extract(profile,'$.kind'),'')!='ai' ORDER BY username")?;
209 let ids = statement
210 .query_map([], |r| r.get::<_, String>(0))?
211 .collect::<std::result::Result<Vec<_>, _>>()?;
212 let users = ids
213 .iter()
214 .map(|id| {
215 let mut user = auth::user(&db, id)?;
216 user["sessions"] = auth::Store::sessions(&db, id)?;
217 Ok(user)
218 })
219 .collect::<Result<Vec<_>>>()?;
220 let mut statement = db.prepare("SELECT id,name FROM roles ORDER BY name")?;
221 let groups = statement
222 .query_map([], |r| {
223 Ok(json!({"id":r.get::<_,String>(0)?,"name":r.get::<_,String>(1)?}))
224 })?
225 .collect::<std::result::Result<Vec<_>, _>>()?;
226 return Ok(Document::new(json!({"users":users,"groups":groups})).response());
227 }
228 if parts.is_empty() && method == Method::POST {
229 let mut profile = profile(&body["profile"], true)?;
230 let setup = string(&body["setup"]["kind"]);
231 if !["invite", "password", "astheno"].contains(&setup) {
232 return Err(Error::new(400, "Choose an invitation, a password, or Astheno."));
233 }
234 let hash = if setup == "password" {
235 Some(
236 app.auth
237 .hash_password(password(&body["setup"]["password"])?)
238 .await?,
239 )
240 } else {
241 None
242 };
243 if !body["groups"].is_array() {
244 return Err(Error::new(400, "Choose groups."));
245 }
246 let id = uuid::Uuid::new_v4().to_string();
247 profile["enabled"] = json!(true);
248 profile["emailVerified"] = json!(false);
249 profile["requiredActions"] = match setup {
250 "password" => json!(["UPDATE_PASSWORD"]),
251 "invite" => json!(["SETUP"]),
252 _ => json!([]),
253 };
254 profile["createdTimestamp"] = json!((now() * 1000.0) as i64);
255 profile["attributes"] = json!({});
256 {
257 let mut db = app.auth.db.lock().unwrap();
258 let transaction = db.transaction()?;
259 transaction
260 .execute(
261 "INSERT INTO users(id,profile) VALUES (?,?)",
262 sql![id, profile.to_string()],
263 )
264 .map_err(|_| Error::new(409, "That username is already taken. Choose another."))?;
265 for group in array(&body["groups"]) {
266 let group = string(group);
267 if transaction.execute(
268 "INSERT OR IGNORE INTO memberships SELECT ?,id FROM roles WHERE id=?",
269 sql![id, group],
270 )? == 0
271 {
272 return Err(Error::new(400, "Choose an available group."));
273 }
274 }
275 if let Some(hash) = &hash {
276 auth::set_password(&transaction, &id, hash)?;
277 }
278 if setup == "astheno" || !string(&body["astheno"]).is_empty() {
279 guest::link(&transaction, &id, string(&body["astheno"]))?;
280 }
281 transaction.commit()?;
282 }
283 return Ok((StatusCode::CREATED,axum::Json(json!({"id":id,"url":if setup=="invite" {Some(app.auth.setup_link(&id)?)}else{None}}))).into_response());
284 }
285 let id = parts
286 .first()
287 .ok_or_else(|| Error::new(404, "No user here."))?;
288 uuid(id)?;
289 if auth::user(&app.auth.db.lock().unwrap(), id)?["kind"] == "ai" {
290 return Err(Error::new(404, "No user here."));
291 }
292 if *parts == [*id, "setup-link"] && method == Method::POST {
293 return Ok(axum::Json(json!({"url":app.auth.setup_link(id)?})).into_response());
294 }
295 let hash = if *parts == [*id, "password"] && method == Method::PUT {
296 Some(app.auth.hash_password(password(&body["password"])?).await?)
297 } else {
298 None
299 };
300 let mut db = app.auth.db.lock().unwrap();
301 let transaction = db.transaction()?;
302 let mut user = auth::user(&transaction, id)?;
303 if guest::is_guest(&user)
304 && matches!(parts, [_, "password"] | [_, "groups", _])
305 && method != Method::GET
306 {
307 return Err(Error::new(
308 400,
309 "Guests can use Shale only. Invite a separate account for other services.",
310 ));
311 }
312 let own = user["username"] == me["name"];
313 let value = match parts {
314 [_] if method == Method::PATCH => {
315 let patch = profile(&body, false)?;
316 if own && patch["enabled"] == false {
317 return Err(Error::new(
318 400,
319 "Sign in as another admin to disable your account.",
320 ));
321 }
322 if patch.get("username").is_some() && patch["username"] != user["username"] {
323 return Err(Error::new(
324 400,
325 "Usernames are fixed to preserve service identities.",
326 ));
327 }
328 user.as_object_mut()
329 .unwrap()
330 .extend(patch.as_object().unwrap().clone());
331 auth::save_user(&transaction, id, user)?;
332 Value::Null
333 }
334 [_] if method == Method::DELETE => {
335 if own {
336 return Err(Error::new(
337 400,
338 "Sign in as another admin to delete your account.",
339 ));
340 }
341 transaction.execute(
342 "DELETE FROM pending WHERE json_extract(data,'$.user')=?",
343 [id],
344 )?;
345 transaction.execute("DELETE FROM users WHERE id=?", [id])?;
346 Value::Null
347 }
348 [_, "groups", group] if method == Method::PUT || method == Method::DELETE => {
349 let name: Option<String> = transaction
350 .query_row("SELECT name FROM roles WHERE id=?", [group], |r| r.get(0))
351 .optional()?;
352 let name = name
353 .ok_or_else(|| Error::new(404, "This group no longer exists. Reload the page."))?;
354 if own && method == Method::DELETE && name == "infra-admin" {
355 return Err(Error::new(
356 400,
357 "Sign in as another admin to remove your admin access.",
358 ));
359 }
360 if method == Method::PUT {
361 transaction.execute(
362 "INSERT OR IGNORE INTO memberships VALUES (?,?)",
363 sql![id, group],
364 )?;
365 } else {
366 transaction.execute(
367 "DELETE FROM memberships WHERE user_id=? AND role_id=?",
368 sql![id, group],
369 )?;
370 }
371 Value::Null
372 }
373 [_, "commit-identity"] if method == Method::GET => identity::account(&transaction, id)?,
374 [_, "commit-emails", email] if method == Method::PUT => {
375 let email = identity::email(&json!(percent_encoding::percent_decode_str(email).decode_utf8().map_err(|_| Error::new(400,"Enter a full email address."))?))?;
376 let exists: bool = transaction.query_row("SELECT EXISTS(SELECT 1 FROM commit_emails WHERE user_id=? AND email=?)",sql![id,email],|r|r.get(0))?;
377 if !exists { return Err(Error::new(404, "This account has not added that email.")); }
378 identity::add_email(&transaction,id,&json!(email),true)?;
379 Value::Null
380 }
381 [_, "signing-keys", fingerprint] if method == Method::PUT => {
382 let fingerprint = percent_encoding::percent_decode_str(fingerprint).decode_utf8().map_err(|_| Error::new(400,"Choose a signing key."))?;
383 identity::confirm_key(&transaction,id,&fingerprint)?;
384 Value::Null
385 }
386 [_, "astheno"] if method == Method::PUT => {
387 guest::link(&transaction, id, string(&body["handle"]))?;
388 Value::Null
389 }
390 [_, "astheno"] if method == Method::DELETE => {
391 guest::unlink(&transaction, id)?;
392 Value::Null
393 }
394 [_, "credentials"] if method == Method::GET => auth::credentials(&transaction, id)?,
395 [_, "logout"] if method == Method::POST => {
396 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
397 Value::Null
398 }
399 [_, "setup-link"] if method == Method::DELETE => {
400 transaction.execute(
401 "DELETE FROM pending WHERE kind='setup' AND json_extract(data,'$.user')=?",
402 [id],
403 )?;
404 Value::Null
405 }
406 [_, "password"] if method == Method::PUT => {
407 if !body["temporary"].is_boolean() {
408 return Err(Error::new(
409 400,
410 "Choose whether this password is temporary.",
411 ));
412 }
413 auth::set_password(&transaction, id, hash.as_deref().unwrap())?;
414 user["requiredActions"] = if body["temporary"] == true {
415 json!(["UPDATE_PASSWORD"])
416 } else {
417 json!([])
418 };
419 auth::save_user(&transaction, id, user)?;
420 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
421 Value::Null
422 }
423 _ => return Err(Error::new(404, "No account action here.")),
424 };
425 if method != Method::GET {
426 transaction.execute("DELETE FROM pending WHERE kind IN ('authentication','registration','handoff') AND json_extract(data,'$.user')=?",[id])?;
427 if body["enabled"] == false {
428 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
429 transaction.execute(
430 "DELETE FROM pending WHERE kind='setup' AND json_extract(data,'$.user')=?",
431 [id],
432 )?;
433 }
434 }
435 transaction.commit()?;
436 drop(db);
437 if body["enabled"] == false
438 || hash.is_some()
439 || (method == Method::DELETE && !matches!(parts, [_, "setup-link"]))
440 || matches!(parts, [_, "logout"])
441 {
442 revoke_connections(&app, id)?;
443 }
444 Ok(if value.is_null() {
445 StatusCode::NO_CONTENT.into_response()
446 } else {
447 Document::new(value).response()
448 })
449}
450fn image_type(bytes: &[u8]) -> Option<&'static str> {
451 if bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
452 Some("image/webp")
453 } else if bytes.get(1..4) == Some(b"PNG") {
454 Some("image/png")
455 } else {
456 None
457 }
458}
459pub async fn picture(app: &App, parts: &[&str]) -> Result<Response> {
460 let ["account", "pictures", id] = parts else {
461 return Err(Error::new(404, "No picture here"));
462 };
463 if id.is_empty()
464 || !id
465 .bytes()
466 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
467 {
468 return Err(Error::new(404, "No picture here"));
469 }
470 let bytes = tokio::fs::read(app.data.join("pictures").join(id))
471 .await
472 .map_err(|_| Error::new(404, "No picture here"))?;
473 Ok((
474 [
475 (
476 "content-type",
477 image_type(&bytes).unwrap_or("application/octet-stream"),
478 ),
479 ("cache-control", "max-age=86400"),
480 ],
481 bytes,
482 )
483 .into_response())
484}
485pub async fn account(
486 app: Arc<App>,
487 request: Request,
488 parts: &[&str],
489 me: &Value,
490) -> Result<Response> {
491 let method = request.method().clone();
492 let mut user = self_user(&app, me).await?;
493 let id = string(&user["id"]).to_owned();
494 let value = match parts {
495 [] if method == Method::GET => {
496 user["commitIdentity"] = identity::account(&app.auth.db.lock().unwrap(), &id)?;
497 user["picture"] = user["attributes"]["picture"][0].clone();
498 user["credentials"] = auth::credentials(&app.auth.db.lock().unwrap(), &id)?;
499 user.as_object_mut().unwrap().remove("attributes");
500 user
501 }
502 [] if method == Method::PATCH => {
503 let body: Value =
504 serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 8192).await?)?;
505 for key in ["firstName", "lastName", "email"] {
506 if body.get(key).is_some() {
507 let mut field = serde_json::Map::new();
508 field.insert(key.to_owned(), body[key].clone());
509 let patch = profile(&Value::Object(field), false)?;
510 user[key] = patch[key].clone();
511 if key == "email" {
512 user["emailVerified"] = json!(false);
513 }
514 }
515 }
516 user["requiredActions"] = json!(
517 array(&user["requiredActions"])
518 .iter()
519 .filter(|v| **v != "UPDATE_PROFILE")
520 .collect::<Vec<_>>()
521 );
522 auth::save_user(&app.auth.db.lock().unwrap(), &id, user)?;
523 Value::Null
524 }
525 ["commit-emails"] if method == Method::POST => {
526 app.auth.recent(request.headers())?;
527 let body: Value = serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 8192).await?)?;
528 let mut db = app.auth.db.lock().unwrap();
529 let tx = db.transaction()?;
530 identity::add_email(&tx, &id, &body["email"], false)?;
531 tx.commit()?;
532 Value::Null
533 }
534 ["commit-emails", email] if method == Method::PUT || method == Method::DELETE => {
535 app.auth.recent(request.headers())?;
536 let email = identity::email(&json!(percent_encoding::percent_decode_str(email).decode_utf8().map_err(|_| Error::new(400,"Enter a full email address."))?))?;
537 let mut db = app.auth.db.lock().unwrap();
538 let tx = db.transaction()?;
539 if method == Method::PUT {
540 if !array(&user["groups"]).iter().any(|group| group["name"] == "infra-admin") {
541 return Err(Error::new(403, "Ask an admin to confirm ownership of this email."));
542 }
543 let exists: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM commit_emails WHERE user_id=? AND email=?)",sql![id,email],|r|r.get(0))?;
544 if !exists { return Err(Error::new(404, "Add this email before confirming ownership.")); }
545 identity::add_email(&tx, &id, &json!(email), true)?;
546 } else {
547 tx.execute("DELETE FROM commit_emails WHERE user_id=? AND email=?",sql![id,email])?;
548 }
549 tx.commit()?;
550 Value::Null
551 }
552 ["signing-keys"] if method == Method::POST => {
553 app.auth.recent(request.headers())?;
554 let body: Value = serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 32768).await?)?;
555 let mut db = app.auth.db.lock().unwrap();
556 let tx = db.transaction()?;
557 identity::add_key(&tx, &id, &body, false)?;
558 tx.commit()?;
559 Value::Null
560 }
561 ["signing-keys", fingerprint] if method == Method::PUT || method == Method::DELETE => {
562 let fingerprint = percent_encoding::percent_decode_str(fingerprint).decode_utf8().map_err(|_| Error::new(400,"Choose a signing key."))?;
563 app.auth.recent(request.headers())?;
564 let mut db = app.auth.db.lock().unwrap();
565 let tx = db.transaction()?;
566 if method == Method::PUT {
567 if !array(&user["groups"]).iter().any(|group| group["name"] == "infra-admin") {
568 return Err(Error::new(403, "Ask an admin to confirm ownership of this signing key."));
569 }
570 identity::confirm_key(&tx,&id,&fingerprint)?;
571 } else { tx.execute("DELETE FROM signing_keys WHERE user_id=? AND fingerprint=?",sql![id,fingerprint.as_ref()])?; }
572 tx.commit()?;
573 Value::Null
574 }
575 ["credentials", credential] if method == Method::DELETE => {
576 app.auth.recent(request.headers())?;
577 let mut db = app.auth.db.lock().unwrap();
578 let transaction = db.transaction()?;
579 let count: i64 = transaction.query_row(
580 "SELECT count(*) FROM credentials WHERE user_id=?",
581 [&id],
582 |r| r.get(0),
583 )?;
584 if count <= 1 {
585 return Err(Error::new(
586 400,
587 "Add another sign-in method before removing this one.",
588 ));
589 }
590 if transaction.execute(
591 "DELETE FROM credentials WHERE user_id=? AND id=?",
592 sql![id, credential],
593 )? == 0
594 {
595 return Err(Error::new(404, "This sign-in method was already removed."));
596 }
597 transaction.execute("DELETE FROM pending WHERE kind IN ('authentication','registration') AND json_extract(data,'$.user')=?",[&id])?;
598 transaction.commit()?;
599 Value::Null
600 }
601 ["picture"] if method == Method::PUT => {
602 let (parts, body) = request.into_parts();
603 let bytes = axum::body::to_bytes(body, 512 * 1024)
604 .await
605 .map_err(|_| Error::new(413, "That picture is over 512 KB. Pick a smaller one."))?;
606 let request = Request::from_parts(parts, axum::body::Body::from(bytes));
607 let mut multipart = Multipart::from_request(request, &())
608 .await
609 .map_err(|_| Error::new(400, "Pick a picture to upload"))?;
610 let mut picture = None;
611 while let Some(field) = multipart
612 .next_field()
613 .await
614 .map_err(|_| Error::new(400, "Pick a picture to upload"))?
615 {
616 if field.name() == Some("picture") && field.file_name().is_some() {
617 picture = Some(
618 field
619 .bytes()
620 .await
621 .map_err(|_| Error::new(400, "Pick a picture to upload"))?,
622 );
623 break;
624 }
625 }
626 let bytes = picture.ok_or_else(|| Error::new(400, "Pick a picture to upload"))?;
627 if image_type(&bytes).is_none() {
628 return Err(Error::new(415, "Upload a WebP or PNG picture"));
629 }
630 tokio::fs::create_dir_all(app.data.join("pictures")).await?;
631 tokio::fs::write(app.data.join("pictures").join(&id), bytes).await?;
632 let picture = format!(
633 "{}/api/account/pictures/{id}?v={}",
634 app.auth.origin.origin().ascii_serialization(),
635 (now() * 1000.0) as u64
636 );
637 user["attributes"]["picture"] = json!([picture]);
638 auth::save_user(&app.auth.db.lock().unwrap(), &id, user)?;
639 json!({"picture":picture})
640 }
641 ["picture"] if method == Method::DELETE => {
642 user["attributes"]["picture"] = Value::Null;
643 auth::save_user(&app.auth.db.lock().unwrap(), &id, user)?;
644 let _ = tokio::fs::remove_file(app.data.join("pictures").join(id)).await;
645 Value::Null
646 }
647 _ => return Err(Error::new(404, "No account action here.")),
648 };
649 Ok(if value.is_null() {
650 StatusCode::NO_CONTENT.into_response()
651 } else {
652 Document::new(value).response()
653 })
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659
660 #[test]
661 fn people_cannot_claim_service_account_usernames() {
662 for username in ["api-account", "API-account", "ai-account"] {
663 assert!(profile(&json!({"username":username}), false).is_err());
664 }
665 assert!(profile(&json!({"username":"person"}), false).is_ok());
666 }
667}