Skip to main content

fastauth_plugin_api_key/
model.rs

1//! The `apikey` table.
2
3use std::collections::BTreeMap;
4
5use fastauth_core::plugin_prelude::*;
6
7/// What a key may do: resource name to allowed actions, `{ "files": ["read", "write"] }`.
8pub type Permissions = BTreeMap<String, Vec<String>>;
9
10/// A row of `apikey`. Only the SHA-256 of the key is stored; the key itself is returned
11/// once, by `/api-key/create`.
12#[derive(Model, Clone)]
13#[model(table = "apikey")]
14pub struct ApiKey {
15    #[model(id)]
16    pub id: Id,
17    /// A label the owner picked.
18    pub name: Option<String>,
19    /// The first characters of the key, so owners can tell keys apart.
20    pub start: Option<String>,
21    /// The prefix the key starts with, when it has one.
22    pub prefix: Option<String>,
23    /// SHA-256 of the full key.
24    #[model(unique, hidden)]
25    pub key_hash: Hash,
26    /// The user the key acts as.
27    #[model(references = User, on_delete = Cascade, index)]
28    pub user_id: Id,
29    /// A disabled key fails verification with `KEY_DISABLED`.
30    #[model(default = true)]
31    pub enabled: bool,
32    /// After this, verification deletes the key and fails with `KEY_EXPIRED`.
33    pub expires_at: Option<OffsetDateTime>,
34    /// Whether the per-key rate limit applies.
35    #[model(default = true)]
36    pub rate_limit_enabled: bool,
37    /// The rate-limit window in milliseconds.
38    pub rate_limit_time_window: Option<i64>,
39    /// Requests allowed per window.
40    pub rate_limit_max: Option<i64>,
41    /// Requests counted in the current window.
42    #[model(default = 0)]
43    pub request_count: i64,
44    /// When the key was last verified.
45    pub last_request: Option<OffsetDateTime>,
46    /// Verifications left; `None` is unlimited.
47    pub remaining: Option<i64>,
48    /// What `remaining` is reset to every `refill_interval`.
49    pub refill_amount: Option<i64>,
50    /// The refill interval in milliseconds.
51    pub refill_interval: Option<i64>,
52    /// When `remaining` was last refilled.
53    pub last_refill_at: Option<OffsetDateTime>,
54    pub permissions: Option<Json<Permissions>>,
55    pub metadata: Option<Json<serde_json::Value>>,
56    #[model(default = now)]
57    pub created_at: OffsetDateTime,
58    #[model(default = now)]
59    pub updated_at: OffsetDateTime,
60}
61
62impl std::fmt::Debug for ApiKey {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("ApiKey")
65            .field("id", &self.id)
66            .field("user_id", &self.user_id)
67            .field("name", &self.name)
68            .field("start", &self.start)
69            .finish_non_exhaustive()
70    }
71}