1use fastauth_core::plugin_prelude::*;
4use serde::Deserializer;
5
6use crate::model::{ApiKey, Permissions};
7use crate::verify::{Failure, verify};
8use crate::{ApiKeyCreated, ApiKeyDeleted, ApiKeyError, ApiKeys};
9
10const NAME_LENGTH: std::ops::RangeInclusive<usize> = 1..=32;
11const PREFIX_LENGTH: std::ops::RangeInclusive<usize> = 1..=32;
12const KEY_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
13
14#[derive(Clone, Debug, Serialize)]
17#[serde(rename_all = "camelCase")]
18pub struct ApiKeyView {
19 pub id: Id,
20 pub config_id: &'static str,
22 pub name: Option<String>,
23 pub start: Option<String>,
24 pub prefix: Option<String>,
25 pub reference_id: Id,
26 pub user_id: Id,
27 pub refill_interval: Option<i64>,
28 pub refill_amount: Option<i64>,
29 #[serde(with = "time::serde::rfc3339::option")]
30 pub last_refill_at: Option<OffsetDateTime>,
31 pub enabled: bool,
32 pub rate_limit_enabled: bool,
33 pub rate_limit_time_window: Option<i64>,
34 pub rate_limit_max: Option<i64>,
35 pub request_count: i64,
36 pub remaining: Option<i64>,
37 #[serde(with = "time::serde::rfc3339::option")]
38 pub last_request: Option<OffsetDateTime>,
39 #[serde(with = "time::serde::rfc3339::option")]
40 pub expires_at: Option<OffsetDateTime>,
41 #[serde(with = "time::serde::rfc3339")]
42 pub created_at: OffsetDateTime,
43 #[serde(with = "time::serde::rfc3339")]
44 pub updated_at: OffsetDateTime,
45 pub metadata: Option<serde_json::Value>,
46 pub permissions: Option<Permissions>,
47}
48
49impl From<ApiKey> for ApiKeyView {
50 fn from(key: ApiKey) -> Self {
51 Self {
52 id: key.id,
53 config_id: "default",
54 name: key.name,
55 start: key.start,
56 prefix: key.prefix,
57 reference_id: key.user_id.clone(),
58 user_id: key.user_id,
59 refill_interval: key.refill_interval,
60 refill_amount: key.refill_amount,
61 last_refill_at: key.last_refill_at,
62 enabled: key.enabled,
63 rate_limit_enabled: key.rate_limit_enabled,
64 rate_limit_time_window: key.rate_limit_time_window,
65 rate_limit_max: key.rate_limit_max,
66 request_count: key.request_count,
67 remaining: key.remaining,
68 last_request: key.last_request,
69 expires_at: key.expires_at,
70 created_at: key.created_at,
71 updated_at: key.updated_at,
72 metadata: key.metadata.map(|m| m.0).filter(|m| !m.is_null()),
73 permissions: key.permissions.map(|p| p.0),
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
80pub struct Success {
81 pub success: bool,
82}
83
84fn double_option<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
86 deserializer: D,
87) -> Result<Option<Option<T>>, D::Error> {
88 Option::<T>::deserialize(deserializer).map(Some)
89}
90
91fn invalid(message: &'static str) -> AuthError {
92 AuthError::bad_request(codes::INVALID_BODY, message)
93}
94
95fn owner(
98 session: Option<&SessionView>,
99 user_id: Option<Id>,
100 trusted: bool,
101 missing: AuthError,
102) -> Result<Id, AuthError> {
103 let session = session.map(|s| s.user.id.clone());
104 if !trusted {
105 if user_id.is_some() {
106 return Err(ApiKeyError::UnauthorizedSession.into());
107 }
108 return session.ok_or(missing);
109 }
110 match (session, user_id) {
111 (Some(session), Some(user)) if session != user => {
112 Err(ApiKeyError::UnauthorizedSession.into())
113 }
114 (Some(id), _) | (None, Some(id)) => Ok(id),
115 (None, None) => Err(ApiKeyError::UnauthorizedSession.into()),
116 }
117}
118
119async fn owned_key<D: Adapter, A>(
121 ctx: &Ctx<D, A>,
122 id: &Id,
123 owner: &Id,
124) -> Result<ApiKey, AuthError> {
125 ctx.db()
126 .find::<ApiKey>(ApiKey::ID.eq(id))
127 .one()
128 .await?
129 .filter(|key| &key.user_id == owner)
130 .ok_or_else(|| ApiKeyError::KeyNotFound.into())
131}
132
133fn check_expires_in(plugin: &ApiKeys, seconds: i64) -> Result<Duration, AuthError> {
134 if seconds < 1 {
135 return Err(invalid("expiresIn must be at least 1"));
136 }
137 let expires_in = Duration::seconds(seconds);
138 if expires_in < plugin.min_expires_in {
139 return Err(ApiKeyError::ExpiresInIsTooSmall.into());
140 }
141 if expires_in > plugin.max_expires_in {
142 return Err(ApiKeyError::ExpiresInIsTooLarge.into());
143 }
144 Ok(expires_in)
145}
146
147fn check_name(name: &str) -> Result<(), AuthError> {
148 if NAME_LENGTH.contains(&name.chars().count()) {
149 Ok(())
150 } else {
151 Err(ApiKeyError::InvalidNameLength.into())
152 }
153}
154
155fn check_refill(amount: Option<i64>, interval: Option<i64>) -> Result<(), AuthError> {
156 match (amount, interval) {
157 (Some(_), None) => Err(ApiKeyError::RefillAmountAndIntervalRequired.into()),
158 (None, Some(_)) => Err(ApiKeyError::RefillIntervalAndAmountRequired.into()),
159 (Some(amount), _) if amount < 1 => Err(invalid("refillAmount must be at least 1")),
160 _ => Ok(()),
161 }
162}
163
164fn check_non_negative(values: &[Option<i64>]) -> Result<(), AuthError> {
165 if values.iter().flatten().any(|v| *v < 0) {
166 return Err(invalid("numbers must not be negative"));
167 }
168 Ok(())
169}
170
171#[derive(Clone, Debug)]
173pub struct CreateApiKey {
174 plugin: Arc<ApiKeys>,
175 trusted: bool,
176}
177
178impl CreateApiKey {
179 pub fn client(plugin: Arc<ApiKeys>) -> Self {
181 Self {
182 plugin,
183 trusted: false,
184 }
185 }
186
187 pub fn server(plugin: Arc<ApiKeys>) -> Self {
190 Self {
191 plugin,
192 trusted: true,
193 }
194 }
195}
196
197#[derive(Clone, Debug, Default, Deserialize)]
200#[serde(rename_all = "camelCase")]
201pub struct CreateApiKeyInput {
202 pub name: Option<String>,
203 pub expires_in: Option<i64>,
205 pub prefix: Option<String>,
207 pub metadata: Option<serde_json::Value>,
209 pub remaining: Option<i64>,
211 pub refill_amount: Option<i64>,
213 pub refill_interval: Option<i64>,
215 pub rate_limit_time_window: Option<i64>,
217 pub rate_limit_max: Option<i64>,
219 pub rate_limit_enabled: Option<bool>,
221 pub permissions: Option<Permissions>,
223 pub user_id: Option<Id>,
225}
226
227#[derive(Clone, Debug, Serialize)]
229pub struct CreatedApiKey {
230 #[serde(flatten)]
231 pub api_key: ApiKeyView,
232 pub key: String,
233}
234
235impl<D: Adapter> Endpoint<D> for CreateApiKey {
236 const METHOD: Method = Method::POST;
237 const PATH: &'static str = "/api-key/create";
238 type Access = MaybeAuthenticated;
239 type Input = CreateApiKeyInput;
240 type Output = CreatedApiKey;
241
242 async fn call(
243 &self,
244 ctx: Ctx<D, MaybeAuthenticated>,
245 input: CreateApiKeyInput,
246 ) -> Result<CreatedApiKey, AuthError> {
247 let plugin = &self.plugin;
248 let server_only = input.remaining.is_some()
249 || input.refill_amount.is_some()
250 || input.refill_interval.is_some()
251 || input.rate_limit_time_window.is_some()
252 || input.rate_limit_max.is_some()
253 || input.rate_limit_enabled.is_some()
254 || input.permissions.is_some();
255 if !self.trusted && server_only {
256 return Err(ApiKeyError::ServerOnlyProperty.into());
257 }
258 let user_id = owner(
259 ctx.session(),
260 input.user_id,
261 self.trusted,
262 ApiKeyError::UnauthorizedSession.into(),
263 )?;
264 let metadata = input.metadata.filter(|m| !m.is_null());
265 if let Some(metadata) = &metadata {
266 if !plugin.enable_metadata {
267 return Err(ApiKeyError::MetadataDisabled.into());
268 }
269 if !metadata.is_object() {
270 return Err(ApiKeyError::InvalidMetadataType.into());
271 }
272 }
273 check_refill(input.refill_amount, input.refill_interval)?;
274 check_non_negative(&[
275 input.remaining,
276 input.refill_interval,
277 input.rate_limit_time_window,
278 input.rate_limit_max,
279 ])?;
280 let expires_in = input
281 .expires_in
282 .map(|seconds| check_expires_in(plugin, seconds))
283 .transpose()?;
284 if let Some(prefix) = &input.prefix {
285 if !PREFIX_LENGTH.contains(&prefix.len()) {
286 return Err(ApiKeyError::InvalidPrefixLength.into());
287 }
288 if !prefix
289 .bytes()
290 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
291 {
292 return Err(invalid(
293 "Invalid prefix format, must be alphanumeric and contain only underscores and hyphens.",
294 ));
295 }
296 }
297 match &input.name {
298 Some(name) => check_name(name)?,
299 None if plugin.require_name => return Err(ApiKeyError::NameRequired.into()),
300 None => {}
301 }
302
303 let prefix = input.prefix.or_else(|| plugin.default_prefix.clone());
304 let key = format!(
305 "{}{}",
306 prefix.as_deref().unwrap_or(""),
307 random_string(plugin.key_length, KEY_ALPHABET)
308 );
309 let start =
310 (plugin.start_length > 0).then(|| key.chars().take(plugin.start_length).collect());
311 let now = ctx.now();
312 let row = ApiKey {
313 id: ctx.new_id()?,
314 name: input.name,
315 start,
316 prefix,
317 key_hash: Hash::sha256(&key),
318 user_id,
319 enabled: true,
320 expires_at: expires_in
321 .or(plugin.default_expires_in)
322 .map(|ttl| now + ttl),
323 rate_limit_enabled: input
324 .rate_limit_enabled
325 .unwrap_or(plugin.rate_limit.enabled),
326 rate_limit_time_window: Some(
327 input
328 .rate_limit_time_window
329 .unwrap_or(plugin.rate_limit.window.whole_milliseconds() as i64),
330 ),
331 rate_limit_max: Some(input.rate_limit_max.unwrap_or(plugin.rate_limit.max)),
332 request_count: 0,
333 last_request: None,
334 remaining: input.remaining.or(input.refill_amount),
335 refill_amount: input.refill_amount,
336 refill_interval: input.refill_interval,
337 last_refill_at: None,
338 permissions: input
339 .permissions
340 .or_else(|| plugin.default_permissions.clone())
341 .map(Json),
342 metadata: metadata.map(Json),
343 created_at: now,
344 updated_at: now,
345 };
346 let row = ctx.db().insert(&row).await?;
347 ctx.emit(ApiKeyCreated {
348 id: row.id.clone(),
349 user_id: row.user_id.clone(),
350 });
351 Ok(CreatedApiKey {
352 api_key: row.into(),
353 key,
354 })
355 }
356}
357
358#[derive(Clone, Copy, Debug)]
360pub struct GetApiKey {
361 trusted: bool,
362}
363
364impl GetApiKey {
365 pub fn client() -> Self {
367 Self { trusted: false }
368 }
369
370 pub fn server() -> Self {
372 Self { trusted: true }
373 }
374}
375
376#[derive(Clone, Debug, Deserialize)]
378#[serde(rename_all = "camelCase")]
379pub struct GetApiKeyInput {
380 pub id: Id,
381 #[serde(default)]
383 pub user_id: Option<Id>,
384}
385
386impl<D: Adapter> Endpoint<D> for GetApiKey {
387 const METHOD: Method = Method::GET;
388 const PATH: &'static str = "/api-key/get";
389 type Access = MaybeAuthenticated;
390 type Input = GetApiKeyInput;
391 type Output = ApiKeyView;
392
393 async fn call(
394 &self,
395 ctx: Ctx<D, MaybeAuthenticated>,
396 input: GetApiKeyInput,
397 ) -> Result<ApiKeyView, AuthError> {
398 let owner = owner(
399 ctx.session(),
400 input.user_id,
401 self.trusted,
402 AuthError::unauthorized(),
403 )?;
404 Ok(owned_key(&ctx, &input.id, &owner).await?.into())
405 }
406}
407
408#[derive(Clone, Debug)]
410pub struct UpdateApiKey {
411 plugin: Arc<ApiKeys>,
412 trusted: bool,
413}
414
415impl UpdateApiKey {
416 pub fn client(plugin: Arc<ApiKeys>) -> Self {
418 Self {
419 plugin,
420 trusted: false,
421 }
422 }
423
424 pub fn server(plugin: Arc<ApiKeys>) -> Self {
426 Self {
427 plugin,
428 trusted: true,
429 }
430 }
431}
432
433#[derive(Clone, Debug, Deserialize)]
436#[serde(rename_all = "camelCase")]
437pub struct UpdateApiKeyInput {
438 pub key_id: Id,
439 #[serde(default)]
441 pub user_id: Option<Id>,
442 #[serde(default)]
443 pub name: Option<String>,
444 #[serde(default)]
445 pub enabled: Option<bool>,
446 #[serde(default, deserialize_with = "double_option")]
448 pub expires_in: Option<Option<i64>>,
449 #[serde(default, deserialize_with = "double_option")]
451 pub metadata: Option<Option<serde_json::Value>>,
452 #[serde(default)]
454 pub remaining: Option<i64>,
455 #[serde(default)]
457 pub refill_amount: Option<i64>,
458 #[serde(default)]
460 pub refill_interval: Option<i64>,
461 #[serde(default)]
463 pub rate_limit_enabled: Option<bool>,
464 #[serde(default)]
466 pub rate_limit_time_window: Option<i64>,
467 #[serde(default)]
469 pub rate_limit_max: Option<i64>,
470 #[serde(default, deserialize_with = "double_option")]
472 pub permissions: Option<Option<Permissions>>,
473}
474
475impl UpdateApiKeyInput {
476 pub fn new(key_id: impl Into<Id>) -> Self {
478 Self {
479 key_id: key_id.into(),
480 user_id: None,
481 name: None,
482 enabled: None,
483 expires_in: None,
484 metadata: None,
485 remaining: None,
486 refill_amount: None,
487 refill_interval: None,
488 rate_limit_enabled: None,
489 rate_limit_time_window: None,
490 rate_limit_max: None,
491 permissions: None,
492 }
493 }
494}
495
496impl<D: Adapter> Endpoint<D> for UpdateApiKey {
497 const METHOD: Method = Method::POST;
498 const PATH: &'static str = "/api-key/update";
499 type Access = MaybeAuthenticated;
500 type Input = UpdateApiKeyInput;
501 type Output = ApiKeyView;
502
503 async fn call(
504 &self,
505 ctx: Ctx<D, MaybeAuthenticated>,
506 input: UpdateApiKeyInput,
507 ) -> Result<ApiKeyView, AuthError> {
508 let owner = owner(
509 ctx.session(),
510 input.user_id,
511 self.trusted,
512 ApiKeyError::UnauthorizedSession.into(),
513 )?;
514 let server_only = input.remaining.is_some()
515 || input.refill_amount.is_some()
516 || input.refill_interval.is_some()
517 || input.rate_limit_enabled.is_some()
518 || input.rate_limit_time_window.is_some()
519 || input.rate_limit_max.is_some()
520 || input.permissions.is_some();
521 if !self.trusted && server_only {
522 return Err(ApiKeyError::ServerOnlyProperty.into());
523 }
524 let key = owned_key(&ctx, &input.key_id, &owner).await?;
525
526 let mut changed = false;
527 let mut update = ctx.db().update::<ApiKey>(ApiKey::ID.eq(&key.id));
528 if let Some(name) = input.name {
529 check_name(&name)?;
530 update = update.set(ApiKey::NAME, Some(name));
531 changed = true;
532 }
533 if let Some(enabled) = input.enabled {
534 update = update.set(ApiKey::ENABLED, enabled);
535 changed = true;
536 }
537 if let Some(expires_in) = input.expires_in {
538 let expires_at = expires_in
539 .map(|seconds| check_expires_in(&self.plugin, seconds))
540 .transpose()?
541 .map(|ttl| ctx.now() + ttl);
542 update = update.set(ApiKey::EXPIRES_AT, expires_at);
543 changed = true;
544 }
545 if let Some(metadata) = input.metadata.filter(|_| self.plugin.enable_metadata) {
546 let metadata = metadata.filter(|m| !m.is_null());
547 if metadata.as_ref().is_some_and(|m| !m.is_object()) {
548 return Err(ApiKeyError::InvalidMetadataType.into());
549 }
550 update = update.set(ApiKey::METADATA, metadata.map(Json));
551 changed = true;
552 }
553 if let Some(remaining) = input.remaining {
554 if remaining < 1 {
555 return Err(invalid("remaining must be at least 1"));
556 }
557 update = update.set(ApiKey::REMAINING, Some(remaining));
558 changed = true;
559 }
560 if input.refill_amount.is_some() || input.refill_interval.is_some() {
561 check_refill(input.refill_amount, input.refill_interval)?;
562 check_non_negative(&[input.refill_interval])?;
563 update = update
564 .set(ApiKey::REFILL_AMOUNT, input.refill_amount)
565 .set(ApiKey::REFILL_INTERVAL, input.refill_interval);
566 changed = true;
567 }
568 check_non_negative(&[input.rate_limit_time_window, input.rate_limit_max])?;
569 if let Some(enabled) = input.rate_limit_enabled {
570 update = update.set(ApiKey::RATE_LIMIT_ENABLED, enabled);
571 changed = true;
572 }
573 if let Some(window) = input.rate_limit_time_window {
574 update = update.set(ApiKey::RATE_LIMIT_TIME_WINDOW, Some(window));
575 changed = true;
576 }
577 if let Some(max) = input.rate_limit_max {
578 update = update.set(ApiKey::RATE_LIMIT_MAX, Some(max));
579 changed = true;
580 }
581 if let Some(permissions) = input.permissions {
582 update = update.set(ApiKey::PERMISSIONS, permissions.map(Json));
583 changed = true;
584 }
585 if !changed {
586 return Err(ApiKeyError::NoValuesToUpdate.into());
587 }
588 update.exec().await?;
589 Ok(owned_key(&ctx, &key.id, &owner).await?.into())
590 }
591}
592
593#[derive(Clone, Copy, Debug)]
595pub struct DeleteApiKey {
596 trusted: bool,
597}
598
599impl DeleteApiKey {
600 pub fn client() -> Self {
602 Self { trusted: false }
603 }
604
605 pub fn server() -> Self {
607 Self { trusted: true }
608 }
609}
610
611#[derive(Clone, Debug, Deserialize)]
613#[serde(rename_all = "camelCase")]
614pub struct DeleteApiKeyInput {
615 pub key_id: Id,
616 #[serde(default)]
618 pub user_id: Option<Id>,
619}
620
621impl<D: Adapter> Endpoint<D> for DeleteApiKey {
622 const METHOD: Method = Method::POST;
623 const PATH: &'static str = "/api-key/delete";
624 type Access = MaybeAuthenticated;
625 type Input = DeleteApiKeyInput;
626 type Output = Success;
627
628 async fn call(
629 &self,
630 ctx: Ctx<D, MaybeAuthenticated>,
631 input: DeleteApiKeyInput,
632 ) -> Result<Success, AuthError> {
633 let owner = owner(
634 ctx.session(),
635 input.user_id,
636 self.trusted,
637 AuthError::unauthorized(),
638 )?;
639 let key = owned_key(&ctx, &input.key_id, &owner).await?;
640 ctx.db().delete::<ApiKey>(ApiKey::ID.eq(&key.id)).await?;
641 ctx.emit(ApiKeyDeleted {
642 id: key.id,
643 user_id: key.user_id,
644 });
645 Ok(Success { success: true })
646 }
647}
648
649#[derive(Clone, Copy, Debug)]
651pub struct ListApiKeys {
652 trusted: bool,
653}
654
655impl ListApiKeys {
656 pub fn client() -> Self {
658 Self { trusted: false }
659 }
660
661 pub fn server() -> Self {
663 Self { trusted: true }
664 }
665}
666
667#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
669#[serde(rename_all = "lowercase")]
670pub enum SortDirection {
671 #[default]
672 Asc,
673 Desc,
674}
675
676#[derive(Clone, Debug, Default, Deserialize)]
678#[serde(rename_all = "camelCase")]
679pub struct ListApiKeysInput {
680 pub limit: Option<u64>,
681 pub offset: Option<u64>,
682 pub sort_by: Option<String>,
685 pub sort_direction: Option<SortDirection>,
686 pub user_id: Option<Id>,
688}
689
690#[derive(Clone, Debug, Serialize)]
692#[serde(rename_all = "camelCase")]
693pub struct ApiKeyList {
694 pub api_keys: Vec<ApiKeyView>,
695 pub total: u64,
697 #[serde(skip_serializing_if = "Option::is_none")]
698 pub limit: Option<u64>,
699 #[serde(skip_serializing_if = "Option::is_none")]
700 pub offset: Option<u64>,
701}
702
703impl<D: Adapter> Endpoint<D> for ListApiKeys {
704 const METHOD: Method = Method::GET;
705 const PATH: &'static str = "/api-key/list";
706 type Access = MaybeAuthenticated;
707 type Input = ListApiKeysInput;
708 type Output = ApiKeyList;
709
710 async fn call(
711 &self,
712 ctx: Ctx<D, MaybeAuthenticated>,
713 input: ListApiKeysInput,
714 ) -> Result<ApiKeyList, AuthError> {
715 let owner = owner(
716 ctx.session(),
717 input.user_id,
718 self.trusted,
719 AuthError::unauthorized(),
720 )?;
721 let column = match input.sort_by.as_deref().unwrap_or("createdAt") {
722 "createdAt" => ApiKey::CREATED_AT.name(),
723 "updatedAt" => ApiKey::UPDATED_AT.name(),
724 "name" => ApiKey::NAME.name(),
725 "expiresAt" => ApiKey::EXPIRES_AT.name(),
726 "lastRequest" => ApiKey::LAST_REQUEST.name(),
727 "remaining" => ApiKey::REMAINING.name(),
728 "requestCount" => ApiKey::REQUEST_COUNT.name(),
729 "enabled" => ApiKey::ENABLED.name(),
730 _ => return Err(invalid("sortBy names an unknown field")),
731 };
732 let order = match input.sort_direction.unwrap_or_default() {
733 SortDirection::Asc => Order::Asc,
734 SortDirection::Desc => Order::Desc,
735 };
736 let db = ctx.db();
737 let mut find = db
738 .find::<ApiKey>(ApiKey::USER_ID.eq(&owner))
739 .order_by((column, order));
740 if let Some(limit) = input.limit {
741 find = find.limit(limit);
742 }
743 if let Some(offset) = input.offset {
744 find = find.offset(offset);
745 }
746 let keys = find.all().await?;
747 let total = db.count::<ApiKey>(ApiKey::USER_ID.eq(&owner)).await?;
748 Ok(ApiKeyList {
749 api_keys: keys.into_iter().map(ApiKeyView::from).collect(),
750 total,
751 limit: input.limit,
752 offset: input.offset,
753 })
754 }
755}
756
757#[derive(Clone, Debug)]
760pub struct VerifyApiKey(pub Arc<ApiKeys>);
761
762#[derive(Clone, Debug, Deserialize)]
764#[serde(rename_all = "camelCase")]
765pub struct VerifyApiKeyInput {
766 pub key: String,
767 #[serde(default)]
769 pub permissions: Option<Permissions>,
770}
771
772#[derive(Clone, Debug, PartialEq, Serialize)]
775pub struct VerifyError {
776 pub message: String,
777 pub code: String,
778 #[serde(skip_serializing_if = "Option::is_none")]
779 pub details: Option<serde_json::Value>,
780}
781
782#[derive(Clone, Debug, Serialize)]
785pub struct VerifyOutput {
786 pub valid: bool,
787 pub error: Option<VerifyError>,
788 pub key: Option<ApiKeyView>,
789}
790
791impl<D: Adapter> Endpoint<D> for VerifyApiKey {
792 const METHOD: Method = Method::POST;
793 const PATH: &'static str = "/api-key/verify";
794 type Access = Public;
795 type Input = VerifyApiKeyInput;
796 type Output = VerifyOutput;
797
798 async fn call(&self, ctx: Ctx<D>, input: VerifyApiKeyInput) -> Result<VerifyOutput, AuthError> {
799 match verify(&ctx, &self.0, &input.key, input.permissions.as_ref()).await {
800 Ok(key) => Ok(VerifyOutput {
801 valid: true,
802 error: None,
803 key: Some(key.into()),
804 }),
805 Err(Failure::Key {
806 error,
807 try_again_in,
808 }) => {
809 let error = AuthError::from(error);
810 Ok(VerifyOutput {
811 valid: false,
812 error: Some(VerifyError {
813 message: error.message().to_owned(),
814 code: error.code().to_owned(),
815 details: try_again_in.map(|ms| serde_json::json!({ "tryAgainIn": ms })),
816 }),
817 key: None,
818 })
819 }
820 Err(Failure::Other(error)) => Err(error),
821 }
822 }
823}
824
825#[derive(Clone, Copy, Debug)]
827pub struct DeleteAllExpiredApiKeys;
828
829#[derive(Clone, Debug, Serialize)]
831pub struct DeleteExpiredOutput {
832 pub success: bool,
833 pub error: Option<String>,
834 pub deleted: u64,
836}
837
838impl<D: Adapter> Endpoint<D> for DeleteAllExpiredApiKeys {
839 const METHOD: Method = Method::POST;
840 const PATH: &'static str = "/api-key/delete-all-expired-api-keys";
841 type Access = Public;
842 type Input = Empty;
843 type Output = DeleteExpiredOutput;
844
845 async fn call(&self, ctx: Ctx<D>, _: Empty) -> Result<DeleteExpiredOutput, AuthError> {
846 let deleted = ctx
847 .db()
848 .delete::<ApiKey>(
849 ApiKey::EXPIRES_AT
850 .is_not_null()
851 .and(ApiKey::EXPIRES_AT.lt(Some(ctx.now()))),
852 )
853 .await?;
854 Ok(DeleteExpiredOutput {
855 success: true,
856 error: None,
857 deleted,
858 })
859 }
860}