1use std::time::Instant;
30
31use axum::{
32 Json,
33 extract::{Path, State},
34 http::{HeaderMap, StatusCode, header},
35 response::{IntoResponse, Response},
36};
37use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
38use serde::{Deserialize, Serialize};
39use sqlx::{PgConnection, PgPool};
40use time::OffsetDateTime;
41use ts_rs::TS;
42use utoipa::ToSchema;
43use utoipa_axum::{router::OpenApiRouter, routes};
44
45use crate::{
46 AppError, AppState, accounts, captcha,
47 email::{self, Mode},
48 legal,
49 login::{Me, Sender},
50 mail::{self, Language},
51 sessions::{self, Session},
52};
53
54pub const MAX_USES: i32 = 1000;
56pub const MAX_LINKS: i64 = 200;
58const MAX_TOKEN: usize = 100;
60
61pub(crate) fn types(types: &mut crate::typescript::Types) {
63 types
64 .add::<Registering>()
65 .add::<NewRegistration>()
66 .add::<Awaiting>()
67 .add::<Invite>()
68 .add::<Invites>()
69 .add::<NewInvite>()
70 .add::<MadeInvite>();
71}
72
73pub fn routes() -> OpenApiRouter<AppState> {
74 OpenApiRouter::new()
75 .routes(routes!(registering, register))
76 .routes(routes!(invites, invite))
77 .routes(routes!(revoke))
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Settings {
83 pub open: bool,
85 pub max_accounts: Option<i32>,
87 pub per_day: Option<i32>,
89 pub invites_per_account: i32,
91 pub invite_days: i32,
93 pub admin_invite_accounts: Option<i32>,
95 pub email: Mode,
97 pub captcha: bool,
99}
100
101pub async fn settings(db: &PgPool) -> anyhow::Result<Settings> {
102 let mut conn = db.acquire().await?;
103 read_settings(&mut conn, false).await
104}
105
106async fn read_settings(conn: &mut PgConnection, lock: bool) -> anyhow::Result<Settings> {
108 let settings = if lock {
109 sqlx::query_as!(
110 Settings,
111 r#"SELECT open, max_accounts, per_day, invites_per_account, invite_days,
112 admin_invite_accounts, email AS "email: Mode", captcha
113 FROM registration FOR UPDATE"#
114 )
115 .fetch_one(conn)
116 .await?
117 } else {
118 sqlx::query_as!(
119 Settings,
120 r#"SELECT open, max_accounts, per_day, invites_per_account, invite_days,
121 admin_invite_accounts, email AS "email: Mode", captcha
122 FROM registration"#
123 )
124 .fetch_one(conn)
125 .await?
126 };
127 Ok(settings)
128}
129
130pub async fn set_settings(db: &PgPool, settings: &Settings) -> anyhow::Result<()> {
131 let mut tx = db.begin().await?;
132 sqlx::query!(
133 "UPDATE registration
134 SET open = $1, max_accounts = $2, per_day = $3, invites_per_account = $4,
135 invite_days = $5, admin_invite_accounts = $6, email = $7, captcha = $8",
136 settings.open,
137 settings.max_accounts,
138 settings.per_day,
139 settings.invites_per_account,
140 settings.invite_days,
141 settings.admin_invite_accounts,
142 settings.email as Mode,
143 settings.captcha,
144 )
145 .execute(&mut *tx)
146 .await?;
147 if settings.email != Mode::Required {
150 sqlx::query!("UPDATE accounts SET awaiting_email = false WHERE awaiting_email")
151 .execute(&mut *tx)
152 .await?;
153 }
154 tx.commit().await?;
155 Ok(())
156}
157
158pub async fn set_quota(db: &PgPool, name: &str, quota: Option<i32>) -> anyhow::Result<bool> {
161 let changed = sqlx::query!(
162 "UPDATE accounts SET invite_quota = $2 WHERE lower(username) = lower($1)",
163 name.trim(),
164 quota,
165 )
166 .execute(db)
167 .await?;
168 Ok(changed.rows_affected() > 0)
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct Counts {
174 pub general: i64,
176 pub today: i64,
178 pub by_admins: i64,
180}
181
182pub async fn counts(conn: &mut PgConnection) -> anyhow::Result<Counts> {
183 let counts = sqlx::query_as!(
184 Counts,
185 r#"SELECT count(*) FILTER (WHERE origin <> 'admin_invite') AS "general!",
186 count(*) FILTER (WHERE origin IN ('registration', 'invite')
187 AND created_at > now() - interval '24 hours') AS "today!",
188 count(*) FILTER (WHERE origin = 'admin_invite') AS "by_admins!"
189 FROM accounts"#
190 )
191 .fetch_one(conn)
192 .await?;
193 Ok(counts)
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Refused {
199 Closed,
201 Invite,
203 Full,
205 Today,
207 Captcha,
210}
211
212impl Refused {
213 fn word(self) -> &'static str {
215 match self {
216 Self::Closed => "closed",
217 Self::Invite => "invite",
218 Self::Full => "full",
219 Self::Today => "today",
220 Self::Captcha => "captcha",
221 }
222 }
223}
224
225impl From<Refused> for AppError {
226 fn from(refused: Refused) -> Self {
227 AppError::Status(StatusCode::FORBIDDEN, refused.word().into())
228 }
229}
230
231struct Usable {
233 id: i32,
234 by_admin: bool,
235}
236
237async fn usable(
241 conn: &mut PgConnection,
242 token: &str,
243 lock: bool,
244) -> anyhow::Result<Option<Usable>> {
245 if token.len() > MAX_TOKEN {
246 return Ok(None);
247 }
248 let hash = sessions::token_hash(token);
249 let invite = if lock {
250 sqlx::query_as!(
251 Usable,
252 "SELECT id, by_admin FROM invites
253 WHERE token_hash = $1 AND NOT revoked AND expires_at > now() AND uses < max_uses
254 AND account_id IN (SELECT id FROM accounts WHERE disabled_at IS NULL)
255 FOR UPDATE",
256 hash,
257 )
258 .fetch_optional(conn)
259 .await?
260 } else {
261 sqlx::query_as!(
262 Usable,
263 "SELECT id, by_admin FROM invites
264 WHERE token_hash = $1 AND NOT revoked AND expires_at > now() AND uses < max_uses
265 AND account_id IN (SELECT id FROM accounts WHERE disabled_at IS NULL)",
266 hash,
267 )
268 .fetch_optional(conn)
269 .await?
270 };
271 Ok(invite)
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276enum Way {
277 Open,
278 Invite { id: i32, by_admin: bool },
279}
280
281impl Way {
282 fn origin(self) -> &'static str {
283 match self {
284 Self::Open => "registration",
285 Self::Invite {
286 by_admin: false, ..
287 } => "invite",
288 Self::Invite { by_admin: true, .. } => "admin_invite",
289 }
290 }
291}
292
293async fn way_in(
295 conn: &mut PgConnection,
296 token: Option<&str>,
297 lock: bool,
298) -> anyhow::Result<Result<Way, Refused>> {
299 let settings = read_settings(conn, lock).await?;
300 let way = match token {
301 None if settings.open => Way::Open,
302 None => return Ok(Err(Refused::Closed)),
303 Some(token) => match usable(conn, token, lock).await? {
304 Some(invite) => Way::Invite {
305 id: invite.id,
306 by_admin: invite.by_admin,
307 },
308 None => return Ok(Err(Refused::Invite)),
309 },
310 };
311 let counts = counts(conn).await?;
312 let over = |count: i64, limit: Option<i32>| limit.is_some_and(|limit| count >= limit.into());
313 let refused = match way {
314 Way::Invite { by_admin: true, .. } => {
315 over(counts.by_admins, settings.admin_invite_accounts).then_some(Refused::Full)
316 }
317 _ if over(counts.general, settings.max_accounts) => Some(Refused::Full),
318 _ if over(counts.today, settings.per_day) => Some(Refused::Today),
319 _ => None,
320 };
321 Ok(refused.map_or(Ok(way), Err))
322}
323
324#[derive(Debug, PartialEq, Eq)]
326pub enum Outcome {
327 Made(i32, Option<String>),
330 Awaiting(i32, String),
332 Refused(Refused),
333 Invalid(accounts::Invalid),
334 Email,
336}
337
338pub struct Applicant<'a> {
340 pub name: &'a str,
341 pub password: &'a str,
342 pub token: Option<&'a str>,
344 pub email: Option<&'a str>,
346 pub language: Language,
348 pub solved: bool,
351}
352
353pub async fn make(db: &PgPool, applicant: &Applicant<'_>) -> anyhow::Result<Outcome> {
357 let Applicant {
358 name,
359 password,
360 token,
361 ..
362 } = *applicant;
363 let mut conn = db.acquire().await?;
366 if let Err(refused) = way_in(&mut conn, token, false).await? {
367 return Ok(Outcome::Refused(refused));
368 }
369 if token.is_none() && !applicant.solved && read_settings(&mut conn, false).await?.captcha {
371 return Ok(Outcome::Refused(Refused::Captcha));
372 }
373 let mode = email::mode(&mut conn).await?;
374 drop(conn);
375 let given = applicant
376 .email
377 .map(str::trim)
378 .filter(|email| !email.is_empty());
379 let address = match (mode, given) {
380 (Mode::Off, _) | (Mode::Optional, None) => None,
381 (Mode::Required, None) => return Ok(Outcome::Email),
382 (_, Some(given)) => match mail::address(given) {
383 Some(address) => Some(address),
384 None => return Ok(Outcome::Email),
385 },
386 };
387 let awaiting = mode == Mode::Required;
388 let name = match accounts::check_name(name) {
389 Ok(name) => name,
390 Err(invalid) => return Ok(Outcome::Invalid(invalid)),
391 };
392 if let Err(invalid) = accounts::check_password(password) {
393 return Ok(Outcome::Invalid(invalid));
394 }
395 if accounts::id_of(db, name).await?.is_some() {
398 return Ok(Outcome::Invalid(accounts::Invalid::NameTaken));
399 }
400 let hash = accounts::hash_for_registration(password).await?;
401
402 let mut tx = db.begin().await?;
404 let way = match way_in(&mut tx, token, true).await? {
405 Ok(way) => way,
406 Err(refused) => return Ok(Outcome::Refused(refused)),
407 };
408 let invite_id = match way {
409 Way::Open => None,
410 Way::Invite { id, .. } => Some(id),
411 };
412 let made = sqlx::query_scalar!(
413 "INSERT INTO accounts (username, password_hash, origin, invite_id, language, awaiting_email)
414 VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING RETURNING id",
415 name,
416 hash,
417 way.origin(),
418 invite_id,
419 applicant.language as Language,
420 awaiting,
421 )
422 .fetch_optional(&mut *tx)
423 .await?;
424 let Some(id) = made else {
425 return Ok(Outcome::Invalid(accounts::Invalid::NameTaken));
426 };
427 if let Some(invite_id) = invite_id {
428 sqlx::query!(
429 "UPDATE invites SET uses = uses + 1 WHERE id = $1",
430 invite_id
431 )
432 .execute(&mut *tx)
433 .await?;
434 }
435 tx.commit().await?;
436 Ok(match address {
437 Some(address) if awaiting => Outcome::Awaiting(id, address),
438 address => Outcome::Made(id, address),
439 })
440}
441
442#[derive(Serialize, TS, ToSchema)]
448struct Registering {
449 open: bool,
451 email: Mode,
453 #[serde(skip_serializing_if = "Option::is_none")]
456 #[ts(optional)]
457 invite: Option<bool>,
458 #[serde(skip_serializing_if = "Option::is_none")]
462 #[ts(optional)]
463 captcha: Option<captcha::Challenge>,
464}
465
466pub const INVITE_HEADER: &str = "x-rueder-invite";
469
470#[utoipa::path(
474 get,
475 path = "/register",
476 tag = "Registration",
477 params(("X-Rueder-Invite" = Option<String>, Header, description = "The token of an invitation to ask about, from the `#invite=` of its link.")),
478 responses((status = OK, body = Registering)),
479)]
480async fn registering(
481 State(state): State<AppState>,
482 headers: HeaderMap,
483) -> Result<Json<Registering>, AppError> {
484 let mut conn = state.db.acquire().await?;
485 let open = way_in(&mut conn, None, false).await?.is_ok();
486 let asked = headers
487 .get(INVITE_HEADER)
488 .and_then(|value| value.to_str().ok())
489 .map(str::trim)
490 .filter(|token| !token.is_empty());
491 let invite = match asked {
494 Some(token) => Some(usable(&mut conn, token, false).await?.is_some()),
495 None => None,
496 };
497 let email = email::mode(&mut conn).await?;
498 let captcha = if open && asked.is_none() && read_settings(&mut conn, false).await?.captcha {
499 Some(
500 state
501 .captcha
502 .challenge(OffsetDateTime::now_utc().unix_timestamp())?,
503 )
504 } else {
505 None
506 };
507 Ok(Json(Registering {
508 open,
509 email,
510 invite,
511 captcha,
512 }))
513}
514
515pub(crate) async fn is_open(db: &PgPool) -> anyhow::Result<bool> {
518 let mut conn = db.acquire().await?;
519 Ok(way_in(&mut conn, None, false).await?.is_ok())
520}
521
522#[derive(Deserialize, TS, ToSchema)]
533struct NewRegistration {
534 username: String,
535 password: String,
536 #[serde(default)]
538 #[ts(optional)]
539 invite: Option<String>,
540 #[serde(default)]
542 #[ts(optional)]
543 accepted_terms: Option<String>,
544 #[serde(default)]
547 #[ts(optional)]
548 email: Option<String>,
549 #[serde(default)]
552 #[ts(optional)]
553 language: Option<String>,
554 #[serde(default)]
556 #[ts(optional)]
557 captcha: Option<captcha::Solution>,
558}
559
560#[utoipa::path(
563 post,
564 path = "/register",
565 tag = "Registration",
566 request_body = NewRegistration,
567 responses((status = CREATED, description = "Made and logged in; the answer sets the cookie `__Host-rueder`.", body = crate::login::Me), (status = ACCEPTED, description = "Made, where every account needs a confirmed address: it logs in once the link mailed to it is opened.", body = Awaiting), (status = BAD_REQUEST, description = "A name, password or address that is not allowed."), (status = SERVICE_UNAVAILABLE, description = "The link could not be mailed; no account was made."), (status = FORBIDDEN, description = "Registration is closed, the invitation is not good (any more), the server or the day is full, the terms were not agreed to (`terms`), or no captcha came that counts (`captcha`)."), (status = CONFLICT, description = "The name is taken."), (status = TOO_MANY_REQUESTS, description = "Too many registrations from the sender's network, or without an invitation on the whole server; see `Retry-After`.")),
568)]
569async fn register(
570 State(state): State<AppState>,
571 Sender(ip): Sender,
572 headers: HeaderMap,
573 Json(new): Json<NewRegistration>,
574) -> Result<Response, AppError> {
575 let terms = state.legal.terms_version.as_deref();
577 if terms.is_some() && new.accepted_terms.as_deref() != terms {
578 return Err(AppError::Status(StatusCode::FORBIDDEN, "terms".into()));
579 }
580 let now = Instant::now();
584 state.rates.registration(ip, now)?;
585 let token = new.invite.as_deref().filter(|token| !token.is_empty());
586 let language = email::language(new.language.as_deref());
587 let solved = new.captcha.as_ref().is_some_and(|solution| {
589 state
590 .captcha
591 .check(solution, OffsetDateTime::now_utc().unix_timestamp())
592 });
593 if token.is_none() && (solved || !settings(&state.db).await?.captcha) {
597 state.rates.open_registration(now)?;
598 }
599 let applicant = Applicant {
600 name: &new.username,
601 password: &new.password,
602 token,
603 email: new.email.as_deref(),
604 language,
605 solved,
606 };
607 let name = new.username.trim();
608 let (id, address) = match make(&state.db, &applicant).await? {
609 Outcome::Made(id, address) => (id, address),
610 Outcome::Awaiting(id, address) => {
611 if let Some(version) = terms {
612 legal::agreed(&state.db, id, version).await?;
613 }
614 if let Err(err) = email::send_link(&state, id, name, language, &address).await {
617 sqlx::query!(
618 "WITH gone AS (DELETE FROM accounts WHERE id = $1 RETURNING invite_id)
619 UPDATE invites SET uses = uses - 1 WHERE id IN (SELECT invite_id FROM gone)",
620 id
621 )
622 .execute(&state.db)
623 .await?;
624 return Err(err);
625 }
626 let waiting = Awaiting {
627 awaiting_email: address,
628 };
629 return Ok((StatusCode::ACCEPTED, Json(waiting)).into_response());
630 }
631 Outcome::Refused(refused) => return Err(refused.into()),
632 Outcome::Invalid(accounts::Invalid::NameTaken) => {
633 let message = accounts::Invalid::NameTaken.to_string();
634 return Err(AppError::Status(StatusCode::CONFLICT, message));
635 }
636 Outcome::Invalid(invalid) => return Err(AppError::BadRequest(invalid.to_string())),
637 Outcome::Email => {
638 return Err(AppError::BadRequest(
639 "that is no address mail can go to".into(),
640 ));
641 }
642 };
643 if let Some(old) = sessions::token(&headers) {
645 sessions::end(&state.db, old).await?;
646 }
647 if let Some(version) = terms {
648 legal::agreed(&state.db, id, version).await?;
649 }
650 if let Some(address) = &address
653 && email::send_link(&state, id, name, language, address)
654 .await
655 .is_err()
656 {
657 tracing::warn!("the link of a new account was not sent; it can ask again");
658 }
659 let token = sessions::start(&state.db, id, false).await?;
660 let me = Me::new(id, name.to_owned(), false, true)
661 .offering(&state)
662 .emailing(&state.db)
663 .await?;
664 let cookie = [(header::SET_COOKIE, sessions::cookie(&token))];
665 Ok((StatusCode::CREATED, cookie, Json(me)).into_response())
666}
667
668#[derive(Serialize, TS, ToSchema)]
672struct Awaiting {
673 awaiting_email: String,
675}
676
677#[derive(Serialize, TS, ToSchema)]
680struct Invite {
681 id: i32,
682 max_uses: i32,
684 uses: i32,
685 #[serde(with = "time::serde::rfc3339")]
686 #[ts(type = "string")]
687 #[schema(value_type = String)]
688 created_at: OffsetDateTime,
689 #[serde(with = "time::serde::rfc3339")]
690 #[ts(type = "string")]
691 #[schema(value_type = String)]
692 expires_at: OffsetDateTime,
693 revoked: bool,
694 usable: bool,
696}
697
698#[derive(Serialize, TS, ToSchema)]
702struct Invites {
703 invites: Vec<Invite>,
705 #[serde(skip_serializing_if = "Option::is_none")]
708 #[ts(optional)]
709 left: Option<i32>,
710 days: i32,
712}
713
714async fn left(
717 conn: &mut PgConnection,
718 account_id: i32,
719 settings: &Settings,
720) -> anyhow::Result<i32> {
721 let row = sqlx::query!(
722 r#"SELECT a.invite_quota,
723 coalesce(sum(CASE WHEN i.revoked OR i.expires_at <= now() THEN i.uses
724 ELSE i.max_uses END), 0) AS "taken!"
725 FROM accounts a
726 LEFT JOIN invites i ON i.account_id = a.id AND NOT i.by_admin
727 WHERE a.id = $1
728 GROUP BY a.id"#,
729 account_id
730 )
731 .fetch_one(conn)
732 .await?;
733 let quota = i64::from(row.invite_quota.unwrap_or(settings.invites_per_account));
734 Ok((quota - row.taken).clamp(0, i32::MAX.into()) as i32)
735}
736
737#[utoipa::path(
739 get,
740 path = "/invites",
741 tag = "Registration",
742 security(("session" = [])),
743 responses((status = OK, body = Invites), crate::openapi::NeedsSession),
744)]
745async fn invites(
746 State(state): State<AppState>,
747 session: Session,
748) -> Result<Json<Invites>, AppError> {
749 let mut conn = state.db.acquire().await?;
750 let settings = read_settings(&mut conn, false).await?;
751 let invites = sqlx::query_as!(
752 Invite,
753 r#"SELECT id, max_uses, uses, created_at, expires_at, revoked,
754 (NOT revoked AND expires_at > now() AND uses < max_uses) AS "usable!"
755 FROM invites WHERE account_id = $1 ORDER BY created_at DESC, id DESC"#,
756 session.account_id
757 )
758 .fetch_all(&mut *conn)
759 .await?;
760 let left = match session.is_admin {
761 true => None,
762 false => Some(left(&mut conn, session.account_id, &settings).await?),
763 };
764 Ok(Json(Invites {
765 invites,
766 left,
767 days: settings.invite_days,
768 }))
769}
770
771#[derive(Deserialize, TS, ToSchema)]
773struct NewInvite {
774 #[serde(default)]
776 #[ts(optional)]
777 uses: Option<i32>,
778}
779
780#[derive(Serialize, TS, ToSchema)]
783struct MadeInvite {
784 id: i32,
785 token: String,
786 #[serde(with = "time::serde::rfc3339")]
787 #[ts(type = "string")]
788 #[schema(value_type = String)]
789 expires_at: OffsetDateTime,
790}
791
792#[utoipa::path(
795 post,
796 path = "/invites",
797 tag = "Registration",
798 request_body = NewInvite,
799 security(("session" = [])),
800 responses((status = CREATED, description = "Made; the link is in the answer this once.", body = MadeInvite), crate::openapi::NeedsSession, (status = BAD_REQUEST, description = "More uses than allowed, or too many links."), (status = FORBIDDEN, description = "The reader has no invitations left.")),
801)]
802async fn invite(
803 State(state): State<AppState>,
804 session: Session,
805 Json(new): Json<NewInvite>,
806) -> Result<(StatusCode, Json<MadeInvite>), AppError> {
807 let uses = new.uses.unwrap_or(1);
808 if !(1..=MAX_USES).contains(&uses) {
809 let message = format!("a link is for 1 to {MAX_USES} accounts");
810 return Err(AppError::BadRequest(message));
811 }
812 let mut tx = state.db.begin().await?;
813 let settings = read_settings(&mut tx, false).await?;
814 if !session.is_admin && left(&mut tx, session.account_id, &settings).await? < uses {
815 let message = "no invitations left";
816 return Err(AppError::Status(StatusCode::FORBIDDEN, message.into()));
817 }
818 sqlx::query!(
820 "DELETE FROM invites WHERE account_id = $1 AND uses = 0
821 AND (revoked OR expires_at <= now())",
822 session.account_id
823 )
824 .execute(&mut *tx)
825 .await?;
826 let have = sqlx::query_scalar!(
827 r#"SELECT count(*) AS "n!" FROM invites WHERE account_id = $1"#,
828 session.account_id
829 )
830 .fetch_one(&mut *tx)
831 .await?;
832 if have >= MAX_LINKS {
833 return Err(AppError::BadRequest("too many links".into()));
834 }
835
836 let mut random = [0u8; 32];
837 getrandom::fill(&mut random).map_err(|err| anyhow::anyhow!("no random numbers: {err}"))?;
838 let token = URL_SAFE_NO_PAD.encode(random);
839 let made = sqlx::query!(
840 "INSERT INTO invites (token_hash, account_id, by_admin, max_uses, expires_at)
841 VALUES ($1, $2, $3, $4, now() + $5::int4 * interval '1 day')
842 RETURNING id, expires_at",
843 sessions::token_hash(&token),
844 session.account_id,
845 session.is_admin,
846 uses,
847 settings.invite_days,
848 )
849 .fetch_one(&mut *tx)
850 .await?;
851 tx.commit().await?;
852 let made = MadeInvite {
853 id: made.id,
854 token,
855 expires_at: made.expires_at,
856 };
857 Ok((StatusCode::CREATED, Json(made)))
858}
859
860#[utoipa::path(
862 delete,
863 path = "/invites/{id}",
864 operation_id = "revoke_invite",
865 tag = "Registration",
866 params(("id" = i32, Path, description = "The invitation.")),
867 security(("session" = [])),
868 responses((status = NO_CONTENT, description = "Done."), crate::openapi::NeedsSession, (status = NOT_FOUND, description = "No such invitation of the account.")),
869)]
870async fn revoke(
871 State(state): State<AppState>,
872 session: Session,
873 Path(id): Path<i32>,
874) -> Result<StatusCode, AppError> {
875 let revoked = sqlx::query!(
876 "UPDATE invites SET revoked = true WHERE account_id = $1 AND id = $2",
877 session.account_id,
878 id,
879 )
880 .execute(&state.db)
881 .await?;
882 if revoked.rows_affected() == 0 {
883 return Err(AppError::NotFound);
884 }
885 Ok(StatusCode::NO_CONTENT)
886}