| 1 | use axum::extract::{Path, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use utopia_core::models::{Role, Workspace}; |
| 6 | use utopia_core::AppError; |
| 7 | use uuid::Uuid; |
| 8 | |
| 9 | use crate::auth::AuthUser; |
| 10 | use crate::error::ApiResult; |
| 11 | use crate::state::AppState; |
| 12 | |
| 13 | #[derive(Deserialize)] |
| 14 | pub struct NameReq { |
| 15 | pub name: String, |
| 16 | } |
| 17 | |
| 18 | fn validate_name(name: &str) -> Result<&str, AppError> { |
| 19 | let name = name.trim(); |
| 20 | if name.is_empty() || name.chars().count() > 64 { |
| 21 | return Err(AppError::invalid( |
| 22 | "bad_name", |
| 23 | "Name must be 1-64 characters", |
| 24 | )); |
| 25 | } |
| 26 | Ok(name) |
| 27 | } |
| 28 | |
| 29 | pub async fn list( |
| 30 | State(state): State<AppState>, |
| 31 | AuthUser(user): AuthUser, |
| 32 | ) -> ApiResult<Json<Vec<Workspace>>> { |
| 33 | let list = utopia_store::workspaces::list_for_user(&state.pool, user.id).await?; |
| 34 | Ok(Json(list)) |
| 35 | } |
| 36 | |
| 37 | pub async fn create( |
| 38 | State(state): State<AppState>, |
| 39 | AuthUser(user): AuthUser, |
| 40 | Json(req): Json<NameReq>, |
| 41 | ) -> ApiResult<Json<Workspace>> { |
| 42 | let name = validate_name(&req.name)?; |
| 43 | let ws = utopia_store::workspaces::create(&state.pool, user.org_id, user.id, name).await?; |
| 44 | Ok(Json(ws)) |
| 45 | } |
| 46 | |
| 47 | pub async fn get_one( |
| 48 | State(state): State<AppState>, |
| 49 | AuthUser(user): AuthUser, |
| 50 | Path(id): Path<Uuid>, |
| 51 | ) -> ApiResult<Json<serde_json::Value>> { |
| 52 | let role = |
| 53 | utopia_store::workspaces::require_role(&state.pool, user.id, id, Role::Viewer).await?; |
| 54 | let ws = utopia_store::workspaces::get(&state.pool, id).await?; |
| 55 | Ok(Json(json!({ "workspace": ws, "role": role }))) |
| 56 | } |
| 57 | |
| 58 | pub async fn rename( |
| 59 | State(state): State<AppState>, |
| 60 | AuthUser(user): AuthUser, |
| 61 | Path(id): Path<Uuid>, |
| 62 | Json(req): Json<NameReq>, |
| 63 | ) -> ApiResult<Json<Workspace>> { |
| 64 | let name = validate_name(&req.name)?; |
| 65 | utopia_store::workspaces::require_role(&state.pool, user.id, id, Role::Admin).await?; |
| 66 | let ws = utopia_store::workspaces::rename(&state.pool, id, name).await?; |
| 67 | Ok(Json(ws)) |
| 68 | } |
| 69 | |
| 70 | pub async fn delete( |
| 71 | State(state): State<AppState>, |
| 72 | AuthUser(user): AuthUser, |
| 73 | Path(id): Path<Uuid>, |
| 74 | ) -> ApiResult<Json<serde_json::Value>> { |
| 75 | utopia_store::workspaces::require_role(&state.pool, user.id, id, Role::Owner).await?; |
| 76 | utopia_store::workspaces::delete(&state.pool, id).await?; |
| 77 | Ok(Json(json!({ "ok": true }))) |
| 78 | } |