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 let guest_groups = if guest::is_guest(&user) {
162 add.iter().chain(&remove).any(|group| transaction.query_row("SELECT name != 'knife-native' FROM roles WHERE id=?", [group], |r| r.get::<_,bool>(0)).unwrap_or(true))
163 } else { false };
164 if guest_groups || user["kind"] == "ai" {
165 return Err(Error::new(
166 400,
167 "Guests can only join knife-native.",
168 ));
169 }
170 for group in &add {
171 transaction.execute(
172 "INSERT OR IGNORE INTO memberships VALUES (?,?)",
173 sql![id, group],
174 )?;
175 }
176 for group in &remove {
177 if user["username"] == me["name"]
178 && array(&user["groups"])
179 .iter()
180 .any(|g| g["id"] == *group && g["name"] == "infra-admin")
181 {
182 return Err(Error::new(
183 400,
184 "Sign in as another admin to remove your admin access.",
185 ));
186 }
187 transaction.execute(
188 "DELETE FROM memberships WHERE user_id=? AND role_id=?",
189 sql![id, group],
190 )?;
191 }
192 transaction.execute("DELETE FROM pending WHERE kind IN ('authentication','registration','handoff') AND json_extract(data,'$.user')=?", [id])?;
193 }
194 transaction.commit()?;
195 drop(db);
196 if !remove.is_empty() {
197 for id in users {
198 revoke_connections(&app, &id)?;
199 }
200 }
201 return Ok(StatusCode::NO_CONTENT.into_response());
202 }
203 if parts == ["guests"] && method == Method::POST {
204 return Ok(axum::Json(
205 guest::add(&app.auth, string(&body["provider"]), string(&body["handle"])).await?,
206 )
207 .into_response());
208 }
209 if parts.is_empty() && method == Method::GET {
210 let db = app.auth.db.lock().unwrap();
211 let mut statement = db.prepare("SELECT id FROM users WHERE coalesce(json_extract(profile,'$.kind'),'')!='ai' ORDER BY username")?;
212 let ids = statement
213 .query_map([], |r| r.get::<_, String>(0))?
214 .collect::<std::result::Result<Vec<_>, _>>()?;
215 let users = ids
216 .iter()
217 .map(|id| {
218 let mut user = auth::user(&db, id)?;
219 user["sessions"] = auth::Store::sessions(&db, id)?;
220 Ok(user)
221 })
222 .collect::<Result<Vec<_>>>()?;
223 let mut statement = db.prepare("SELECT id,name FROM roles ORDER BY name")?;
224 let groups = statement
225 .query_map([], |r| {
226 Ok(json!({"id":r.get::<_,String>(0)?,"name":r.get::<_,String>(1)?}))
227 })?
228 .collect::<std::result::Result<Vec<_>, _>>()?;
229 return Ok(Document::new(json!({"users":users,"groups":groups})).response());
230 }
231 if parts.is_empty() && method == Method::POST {
232 let mut profile = profile(&body["profile"], true)?;
233 let setup = string(&body["setup"]["kind"]);
234 if !["invite", "password", "astheno"].contains(&setup) {
235 return Err(Error::new(400, "Choose an invitation, a password, or Astheno."));
236 }
237 let hash = if setup == "password" {
238 Some(
239 app.auth
240 .hash_password(password(&body["setup"]["password"])?)
241 .await?,
242 )
243 } else {
244 None
245 };
246 if !body["groups"].is_array() {
247 return Err(Error::new(400, "Choose groups."));
248 }
249 let id = uuid::Uuid::new_v4().to_string();
250 profile["enabled"] = json!(true);
251 profile["emailVerified"] = json!(false);
252 profile["requiredActions"] = match setup {
253 "password" => json!(["UPDATE_PASSWORD"]),
254 "invite" => json!(["SETUP"]),
255 _ => json!([]),
256 };
257 profile["createdTimestamp"] = json!((now() * 1000.0) as i64);
258 profile["attributes"] = json!({});
259 {
260 let mut db = app.auth.db.lock().unwrap();
261 let transaction = db.transaction()?;
262 transaction
263 .execute(
264 "INSERT INTO users(id,profile) VALUES (?,?)",
265 sql![id, profile.to_string()],
266 )
267 .map_err(|_| Error::new(409, "That username is already taken. Choose another."))?;
268 for group in array(&body["groups"]) {
269 let group = string(group);
270 if transaction.execute(
271 "INSERT OR IGNORE INTO memberships SELECT ?,id FROM roles WHERE id=?",
272 sql![id, group],
273 )? == 0
274 {
275 return Err(Error::new(400, "Choose an available group."));
276 }
277 }
278 if let Some(hash) = &hash {
279 auth::set_password(&transaction, &id, hash)?;
280 }
281 if setup == "astheno" || !string(&body["astheno"]).is_empty() {
282 guest::link(&transaction, &id, string(&body["astheno"]))?;
283 }
284 transaction.commit()?;
285 }
286 return Ok((StatusCode::CREATED,axum::Json(json!({"id":id,"url":if setup=="invite" {Some(app.auth.setup_link(&id)?)}else{None}}))).into_response());
287 }
288 let id = parts
289 .first()
290 .ok_or_else(|| Error::new(404, "No user here."))?;
291 uuid(id)?;
292 if auth::user(&app.auth.db.lock().unwrap(), id)?["kind"] == "ai" {
293 return Err(Error::new(404, "No user here."));
294 }
295 if *parts == [*id, "setup-link"] && method == Method::POST {
296 return Ok(axum::Json(json!({"url":app.auth.setup_link(id)?})).into_response());
297 }
298 let hash = if *parts == [*id, "password"] && method == Method::PUT {
299 Some(app.auth.hash_password(password(&body["password"])?).await?)
300 } else {
301 None
302 };
303 let mut db = app.auth.db.lock().unwrap();
304 let transaction = db.transaction()?;
305 let mut user = auth::user(&transaction, id)?;
306 if guest::is_guest(&user)
307 && matches!(parts, [_, "password"])
308 && method != Method::GET
309 {
310 return Err(Error::new(
311 400,
312 "Guests can use Shale only. Invite a separate account for other services.",
313 ));
314 }
315 let own = user["username"] == me["name"];
316 let value = match parts {
317 [_] if method == Method::PATCH => {
318 let patch = profile(&body, false)?;
319 if own && patch["enabled"] == false {
320 return Err(Error::new(
321 400,
322 "Sign in as another admin to disable your account.",
323 ));
324 }
325 if patch.get("username").is_some() && patch["username"] != user["username"] {
326 return Err(Error::new(
327 400,
328 "Usernames are fixed to preserve service identities.",
329 ));
330 }
331 user.as_object_mut()
332 .unwrap()
333 .extend(patch.as_object().unwrap().clone());
334 auth::save_user(&transaction, id, user)?;
335 Value::Null
336 }
337 [_] if method == Method::DELETE => {
338 if own {
339 return Err(Error::new(
340 400,
341 "Sign in as another admin to delete your account.",
342 ));
343 }
344 transaction.execute(
345 "DELETE FROM pending WHERE json_extract(data,'$.user')=?",
346 [id],
347 )?;
348 transaction.execute("DELETE FROM users WHERE id=?", [id])?;
349 Value::Null
350 }
351 [_, "groups", group] if method == Method::PUT || method == Method::DELETE => {
352 let name: Option<String> = transaction
353 .query_row("SELECT name FROM roles WHERE id=?", [group], |r| r.get(0))
354 .optional()?;
355 let name = name
356 .ok_or_else(|| Error::new(404, "This group no longer exists. Reload the page."))?;
357 if guest::is_guest(&user) && name != "knife-native" {
358 return Err(Error::new(400, "Guests can only join knife-native."));
359 }
360 if own && method == Method::DELETE && name == "infra-admin" {
361 return Err(Error::new(
362 400,
363 "Sign in as another admin to remove your admin access.",
364 ));
365 }
366 if method == Method::PUT {
367 transaction.execute(
368 "INSERT OR IGNORE INTO memberships VALUES (?,?)",
369 sql![id, group],
370 )?;
371 } else {
372 transaction.execute(
373 "DELETE FROM memberships WHERE user_id=? AND role_id=?",
374 sql![id, group],
375 )?;
376 }
377 Value::Null
378 }
379 [_, "commit-identity"] if method == Method::GET => identity::account(&transaction, id)?,
380 [_, "commit-emails", email] if method == Method::PUT => {
381 let email = identity::email(&json!(percent_encoding::percent_decode_str(email).decode_utf8().map_err(|_| Error::new(400,"Enter a full email address."))?))?;
382 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))?;
383 if !exists { return Err(Error::new(404, "This account has not added that email.")); }
384 identity::add_email(&transaction,id,&json!(email),true)?;
385 Value::Null
386 }
387 [_, "signing-keys", fingerprint] if method == Method::PUT => {
388 let fingerprint = percent_encoding::percent_decode_str(fingerprint).decode_utf8().map_err(|_| Error::new(400,"Choose a signing key."))?;
389 identity::confirm_key(&transaction,id,&fingerprint)?;
390 Value::Null
391 }
392 [_, "astheno"] if method == Method::PUT => {
393 guest::link(&transaction, id, string(&body["handle"]))?;
394 Value::Null
395 }
396 [_, "astheno"] if method == Method::DELETE => {
397 guest::unlink(&transaction, id)?;
398 Value::Null
399 }
400 [_, "credentials"] if method == Method::GET => auth::credentials(&transaction, id)?,
401 [_, "logout"] if method == Method::POST => {
402 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
403 Value::Null
404 }
405 [_, "setup-link"] if method == Method::DELETE => {
406 transaction.execute(
407 "DELETE FROM pending WHERE kind='setup' AND json_extract(data,'$.user')=?",
408 [id],
409 )?;
410 Value::Null
411 }
412 [_, "password"] if method == Method::PUT => {
413 if !body["temporary"].is_boolean() {
414 return Err(Error::new(
415 400,
416 "Choose whether this password is temporary.",
417 ));
418 }
419 auth::set_password(&transaction, id, hash.as_deref().unwrap())?;
420 user["requiredActions"] = if body["temporary"] == true {
421 json!(["UPDATE_PASSWORD"])
422 } else {
423 json!([])
424 };
425 auth::save_user(&transaction, id, user)?;
426 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
427 Value::Null
428 }
429 _ => return Err(Error::new(404, "No account action here.")),
430 };
431 if method != Method::GET {
432 transaction.execute("DELETE FROM pending WHERE kind IN ('authentication','registration','handoff') AND json_extract(data,'$.user')=?",[id])?;
433 if body["enabled"] == false {
434 transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?;
435 transaction.execute(
436 "DELETE FROM pending WHERE kind='setup' AND json_extract(data,'$.user')=?",
437 [id],
438 )?;
439 }
440 }
441 transaction.commit()?;
442 drop(db);
443 if body["enabled"] == false
444 || hash.is_some()
445 || (method == Method::DELETE && !matches!(parts, [_, "setup-link"]))
446 || matches!(parts, [_, "logout"])
447 {
448 revoke_connections(&app, id)?;
449 }
450 Ok(if value.is_null() {
451 StatusCode::NO_CONTENT.into_response()
452 } else {
453 Document::new(value).response()
454 })
455}
456fn image_type(bytes: &[u8]) -> Option<&'static str> {
457 if bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
458 Some("image/webp")
459 } else if bytes.get(1..4) == Some(b"PNG") {
460 Some("image/png")
461 } else {
462 None
463 }
464}
465pub async fn picture(app: &App, parts: &[&str]) -> Result<Response> {
466 let ["account", "pictures", id] = parts else {
467 return Err(Error::new(404, "No picture here"));
468 };
469 if id.is_empty()
470 || !id
471 .bytes()
472 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
473 {
474 return Err(Error::new(404, "No picture here"));
475 }
476 let bytes = tokio::fs::read(app.data.join("pictures").join(id))
477 .await
478 .map_err(|_| Error::new(404, "No picture here"))?;
479 Ok((
480 [
481 (
482 "content-type",
483 image_type(&bytes).unwrap_or("application/octet-stream"),
484 ),
485 ("cache-control", "max-age=86400"),
486 ],
487 bytes,
488 )
489 .into_response())
490}
491pub async fn account(
492 app: Arc<App>,
493 request: Request,
494 parts: &[&str],
495 me: &Value,
496) -> Result<Response> {
497 let method = request.method().clone();
498 let mut user = self_user(&app, me).await?;
499 let id = string(&user["id"]).to_owned();
500 let value = match parts {
501 [] if method == Method::GET => {
502 user["commitIdentity"] = identity::account(&app.auth.db.lock().unwrap(), &id)?;
503 user["picture"] = user["attributes"]["picture"][0].clone();
504 user["credentials"] = auth::credentials(&app.auth.db.lock().unwrap(), &id)?;
505 user.as_object_mut().unwrap().remove("attributes");
506 user
507 }
508 [] if method == Method::PATCH => {
509 let body: Value =
510 serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 8192).await?)?;
511 for key in ["firstName", "lastName", "email"] {
512 if body.get(key).is_some() {
513 let mut field = serde_json::Map::new();
514 field.insert(key.to_owned(), body[key].clone());
515 let patch = profile(&Value::Object(field), false)?;
516 user[key] = patch[key].clone();
517 if key == "email" {
518 user["emailVerified"] = json!(false);
519 }
520 }
521 }
522 user["requiredActions"] = json!(
523 array(&user["requiredActions"])
524 .iter()
525 .filter(|v| **v != "UPDATE_PROFILE")
526 .collect::<Vec<_>>()
527 );
528 auth::save_user(&app.auth.db.lock().unwrap(), &id, user)?;
529 Value::Null
530 }
531 ["commit-emails"] if method == Method::POST => {
532 app.auth.recent(request.headers())?;
533 let body: Value = serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 8192).await?)?;
534 let mut db = app.auth.db.lock().unwrap();
535 let tx = db.transaction()?;
536 identity::add_email(&tx, &id, &body["email"], false)?;
537 tx.commit()?;
538 Value::Null
539 }
540 ["commit-emails", email] if method == Method::PUT || method == Method::DELETE => {
541 app.auth.recent(request.headers())?;
542 let email = identity::email(&json!(percent_encoding::percent_decode_str(email).decode_utf8().map_err(|_| Error::new(400,"Enter a full email address."))?))?;
543 let mut db = app.auth.db.lock().unwrap();
544 let tx = db.transaction()?;
545 if method == Method::PUT {
546 if !array(&user["groups"]).iter().any(|group| group["name"] == "infra-admin") {
547 return Err(Error::new(403, "Ask an admin to confirm ownership of this email."));
548 }
549 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))?;
550 if !exists { return Err(Error::new(404, "Add this email before confirming ownership.")); }
551 identity::add_email(&tx, &id, &json!(email), true)?;
552 } else {
553 tx.execute("DELETE FROM commit_emails WHERE user_id=? AND email=?",sql![id,email])?;
554 }
555 tx.commit()?;
556 Value::Null
557 }
558 ["signing-keys"] if method == Method::POST => {
559 app.auth.recent(request.headers())?;
560 let body: Value = serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 32768).await?)?;
561 let mut db = app.auth.db.lock().unwrap();
562 let tx = db.transaction()?;
563 identity::add_key(&tx, &id, &body, false)?;
564 tx.commit()?;
565 Value::Null
566 }
567 ["signing-keys", fingerprint] if method == Method::PUT || method == Method::DELETE => {
568 let fingerprint = percent_encoding::percent_decode_str(fingerprint).decode_utf8().map_err(|_| Error::new(400,"Choose a signing key."))?;
569 app.auth.recent(request.headers())?;
570 let mut db = app.auth.db.lock().unwrap();
571 let tx = db.transaction()?;
572 if method == Method::PUT {
573 if !array(&user["groups"]).iter().any(|group| group["name"] == "infra-admin") {
574 return Err(Error::new(403, "Ask an admin to confirm ownership of this signing key."));
575 }
576 identity::confirm_key(&tx,&id,&fingerprint)?;
577 } else { tx.execute("DELETE FROM signing_keys WHERE user_id=? AND fingerprint=?",sql![id,fingerprint.as_ref()])?; }
578 tx.commit()?;
579 Value::Null
580 }
581 ["credentials", credential] if method == Method::DELETE => {
582 app.auth.recent(request.headers())?;
583 let mut db = app.auth.db.lock().unwrap();
584 let transaction = db.transaction()?;
585 let count: i64 = transaction.query_row(
586 "SELECT count(*) FROM credentials WHERE user_id=?",
587 [&id],
588 |r| r.get(0),
589 )?;
590 if count <= 1 {
591 return Err(Error::new(
592 400,
593 "Add another sign-in method before removing this one.",
594 ));
595 }
596 if transaction.execute(
597 "DELETE FROM credentials WHERE user_id=? AND id=?",
598 sql![id, credential],
599 )? == 0
600 {
601 return Err(Error::new(404, "This sign-in method was already removed."));
602 }
603 transaction.execute("DELETE FROM pending WHERE kind IN ('authentication','registration') AND json_extract(data,'$.user')=?",[&id])?;
604 transaction.commit()?;
605 Value::Null
606 }
607 ["picture"] if method == Method::PUT => {
608 let (parts, body) = request.into_parts();
609 let bytes = axum::body::to_bytes(body, 512 * 1024)
610 .await
611 .map_err(|_| Error::new(413, "That picture is over 512 KB. Pick a smaller one."))?;
612 let request = Request::from_parts(parts, axum::body::Body::from(bytes));
613 let mut multipart = Multipart::from_request(request, &())
614 .await
615 .map_err(|_| Error::new(400, "Pick a picture to upload"))?;
616 let mut picture = None;
617 while let Some(field) = multipart
618 .next_field()
619 .await
620 .map_err(|_| Error::new(400, "Pick a picture to upload"))?
621 {
622 if field.name() == Some("picture") && field.file_name().is_some() {
623 picture = Some(
624 field
625 .bytes()
626 .await
627 .map_err(|_| Error::new(400, "Pick a picture to upload"))?,
628 );
629 break;
630 }
631 }
632 let bytes = picture.ok_or_else(|| Error::new(400, "Pick a picture to upload"))?;
633 if image_type(&bytes).is_none() {
634 return Err(Error::new(415, "Upload a WebP or PNG picture"));
635 }
636 tokio::fs::create_dir_all(app.data.join("pictures")).await?;
637 tokio::fs::write(app.data.join("pictures").join(&id), bytes).await?;
638 let picture = format!(
639 "{}/api/account/pictures/{id}?v={}",
640 app.auth.origin.origin().ascii_serialization(),
641 (now() * 1000.0) as u64
642 );
643 user["attributes"]["picture"] = json!([picture]);
644 auth::save_user(&app.auth.db.lock().unwrap(), &id, user)?;
645 json!({"picture":picture})
646 }
647 ["picture"] if method == Method::DELETE => {
648 user["attributes"]["picture"] = Value::Null;
649 auth::save_user(&app.auth.db.lock().unwrap(), &id, user)?;
650 let _ = tokio::fs::remove_file(app.data.join("pictures").join(id)).await;
651 Value::Null
652 }
653 _ => return Err(Error::new(404, "No account action here.")),
654 };
655 Ok(if value.is_null() {
656 StatusCode::NO_CONTENT.into_response()
657 } else {
658 Document::new(value).response()
659 })
660}
661
662#[cfg(test)]
663mod tests {
664 use super::*;
665
666 #[test]
667 fn people_cannot_claim_service_account_usernames() {
668 for username in ["api-account", "API-account", "ai-account"] {
669 assert!(profile(&json!({"username":username}), false).is_err());
670 }
671 assert!(profile(&json!({"username":"person"}), false).is_ok());
672 }
673}