Skip to main content

swarmhive_api_types/
api_token.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use utoipa::ToSchema;
4use uuid::Uuid;
5
6use crate::role::PermissionName;
7
8/// Wire kind discriminator. PAT inherits the owner's live permissions; API
9/// Token carries a snapshot subset chosen at create time.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
11#[serde(rename_all = "snake_case")]
12pub enum ApiTokenKind {
13    Pat,
14    Api,
15}
16
17/// Listed / detail representation of an `api_token` row. Never includes the
18/// plaintext token — that field exists only on [`CreateTokenResponse`].
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
20pub struct ApiToken {
21    pub id: Uuid,
22    pub owner_user_id: Uuid,
23    pub kind: ApiTokenKind,
24    pub name: String,
25    /// First 12 chars of the plaintext token, e.g. `swhv_pat_AbC`. Safe to
26    /// display in lists to disambiguate tokens with similar names.
27    pub prefix: String,
28    /// `None` for PAT (live from owner roles); `Some(subset)` for API Token.
29    pub permissions: Option<Vec<PermissionName>>,
30    pub last_used_at: Option<DateTime<Utc>>,
31    pub expires_at: Option<DateTime<Utc>>,
32    pub revoked_at: Option<DateTime<Utc>>,
33    pub created_at: DateTime<Utc>,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
37pub struct CreateTokenRequest {
38    pub kind: ApiTokenKind,
39    pub name: String,
40    /// Required when `kind = api` — must be a subset of the creator's current
41    /// permissions. Must be `None` when `kind = pat` (server returns 422
42    /// otherwise).
43    #[serde(default)]
44    pub permissions: Option<Vec<PermissionName>>,
45    #[serde(default)]
46    pub expires_at: Option<DateTime<Utc>>,
47}
48
49/// Returned exactly once by `POST /api/v1/tokens`. The plaintext `token` is
50/// the only opportunity to record it — server stores only the blake3 hash.
51#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
52pub struct CreateTokenResponse {
53    /// Plaintext bearer token, format `swhv_(pat|api)_<43char base64url>`.
54    pub token: String,
55    #[serde(flatten)]
56    pub api_token: ApiToken,
57}