use super::AppError;
use crate::AppState;
use axum::{
extract::{Path, State},
response::Response,
};
use ryuk::{
apikey::ApiKeyError,
auth::Auth,
inertia::{self, Inertia},
session::Session,
validation::Form,
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{collections::BTreeMap, time::Duration};
use utoipa::ToSchema;
use validator::Validate;
const SCOPES: [&str; 4] = ["profile", "posts:read", "posts:write", "devices"];
#[derive(Deserialize, Validate, ToSchema)]
pub struct NewKeyForm {
#[validate(length(min = 1, max = 100, message = "Name must be 1 to 100 characters"))]
name: String,
#[validate(length(min = 1, message = "Pick at least one scope"))]
scopes: Vec<String>,
#[validate(range(min = 1, max = 3650, message = "Expiry must be 1 to 3650 days"))]
expires_days: Option<u32>,
}
async fn page(s: &AppState, uid: i64, inertia: Inertia, new_key: Option<String>) -> Result<Response, AppError> {
let keys: Vec<Value> = s
.api_keys
.list(uid)
.await?
.into_iter()
.filter(|k| k.revoked_at.is_none())
.map(|k| {
json!({ "id": k.id, "name": k.name, "prefix": k.prefix, "scopes": k.scopes,
"created_at": k.created_at, "last_used_at": k.last_used_at, "expires_at": k.expires_at })
})
.collect();
Ok(inertia.render("Settings/ApiKeys", json!({ "keys": keys, "scopes": SCOPES, "new_key": new_key })))
}
#[utoipa::path(get, path = "/settings/api-keys", responses((status = 200, description = "Your API keys")))]
pub async fn index(State(s): State<AppState>, Auth(uid): Auth, inertia: Inertia) -> Result<Response, AppError> {
page(&s, uid, inertia, None).await
}
#[utoipa::path(post, path = "/settings/api-keys", request_body = NewKeyForm,
responses((status = 200, description = "The key list plus the new key, shown once")))]
pub async fn store(
State(s): State<AppState>,
Auth(uid): Auth,
session: Session,
inertia: Inertia,
Form(f): Form<NewKeyForm>,
) -> Result<Response, AppError> {
let scopes: Vec<&str> = f.scopes.iter().map(String::as_str).collect();
if let Some(bad) = scopes.iter().find(|x| !SCOPES.contains(x)) {
let e = BTreeMap::from([("scopes".to_string(), format!("Unknown scope {bad}"))]);
inertia::flash_errors(&session, e).await;
return Ok(inertia::redirect("/settings/api-keys"));
}
let ttl = f.expires_days.map(|d| Duration::from_secs(u64::from(d) * 86400));
match s.api_keys.issue(Some(uid), &f.name, &scopes, ttl).await {
Ok(k) => page(&s, uid, inertia, Some(k.plaintext)).await,
Err(ApiKeyError::Invalid(m)) => {
inertia::flash_errors(&session, BTreeMap::from([("name".to_string(), m.to_string())])).await;
Ok(inertia::redirect("/settings/api-keys"))
}
Err(e) => Err(e.into()),
}
}
#[utoipa::path(post, path = "/settings/api-keys/{id}/revoke", params(("id" = i64, Path, description = "Key id")),
responses((status = 303, description = "Back to the key list")))]
pub async fn revoke(
State(s): State<AppState>,
Auth(uid): Auth,
Path(id): Path<i64>,
session: Session,
) -> Result<Response, AppError> {
if s.api_keys.revoke(uid, id).await? {
inertia::flash(&session, "success", "API key revoked.").await;
} else {
inertia::flash(&session, "error", "API key not found.").await;
}
Ok(inertia::redirect("/settings/api-keys"))
}