Skip to main content

dvm_api/
api_key.rs

1use serde::{Deserialize, Serialize};
2
3use crate::Timestamp;
4
5/// One of a user's API keys, as they list them: never the key itself, of
6/// which the controller keeps only the SHA-256. A request that bears it
7/// (`Authorization: Bearer <key>`) acts as its user.
8#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
9#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
10#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
11pub struct ApiKey {
12    pub id: i64,
13    pub name: String,
14    /// The key's last four characters, to tell it from the user's others.
15    pub ending: String,
16    pub created_at: Timestamp,
17    /// When a request last bore it, to the minute; `None` if none has.
18    pub last_used_at: Option<Timestamp>,
19}
20
21impl ApiKey {
22    /// What every key starts with, so that a key pasted somewhere is known
23    /// for one.
24    pub const PREFIX: &str = "dvm_";
25
26    /// The key as shown, all but its prefix and ending left out:
27    /// `dvm_…3f9a`.
28    pub fn masked(&self) -> String {
29        format!("{}…{}", Self::PREFIX, self.ending)
30    }
31}
32
33/// A key to make: `POST /api/keys`.
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
36#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
37pub struct NewApiKey {
38    pub name: String,
39}
40
41/// A key just made, and the key itself: shown this once.
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
44#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
45pub struct CreatedApiKey {
46    pub key: ApiKey,
47    pub secret: String,
48}