|
| 1 | +// Copyright Materialize, Inc. and contributors. All rights reserved. |
| 2 | +// |
| 3 | +// Use of this software is governed by the Business Source License |
| 4 | +// included in the LICENSE file. |
| 5 | +// |
| 6 | +// As of the Change Date specified in that file, in accordance with |
| 7 | +// the Business Source License, use of this software will be governed |
| 8 | +// by the Apache License, Version 2.0. |
| 9 | + |
| 10 | +use std::collections::BTreeSet; |
| 11 | +use std::sync::Arc; |
| 12 | + |
| 13 | +use axum::Json; |
| 14 | +use axum::extract::{Path, State}; |
| 15 | +use chrono::Utc; |
| 16 | +use axum::http::StatusCode; |
| 17 | +use serde::Deserialize; |
| 18 | +use uuid::Uuid; |
| 19 | + |
| 20 | +use crate::models::{TenantConfig, TenantResponse}; |
| 21 | +use crate::server::Context; |
| 22 | + |
| 23 | +/// Handle GET /tenants/resources/tenants/v1 |
| 24 | +/// Lists all tenants. |
| 25 | +/// |
| 26 | +/// If no explicit tenants are configured, derives tenants from the users' tenant_ids. |
| 27 | +pub async fn handle_list_tenants( |
| 28 | + State(context): State<Arc<Context>>, |
| 29 | +) -> Result<Json<Vec<TenantResponse>>, StatusCode> { |
| 30 | + let tenants = context.tenants.lock().unwrap(); |
| 31 | + |
| 32 | + // If explicit tenants are configured, return those |
| 33 | + if !tenants.is_empty() { |
| 34 | + let responses: Vec<TenantResponse> = tenants.values().map(TenantResponse::from).collect(); |
| 35 | + return Ok(Json(responses)); |
| 36 | + } |
| 37 | + drop(tenants); |
| 38 | + |
| 39 | + // Otherwise, derive tenants from users |
| 40 | + let users = context.users.lock().unwrap(); |
| 41 | + let tenant_ids: BTreeSet<_> = users.values().map(|u| u.tenant_id).collect(); |
| 42 | + |
| 43 | + let now = Utc::now(); |
| 44 | + let responses: Vec<TenantResponse> = tenant_ids |
| 45 | + .into_iter() |
| 46 | + .map(|id| TenantResponse { |
| 47 | + id, |
| 48 | + name: format!("Tenant {}", &id.to_string()[..8]), |
| 49 | + metadata: serde_json::json!({}), |
| 50 | + creator_name: None, |
| 51 | + creator_email: None, |
| 52 | + created_at: now, |
| 53 | + updated_at: now, |
| 54 | + deleted_at: None, |
| 55 | + }) |
| 56 | + .collect(); |
| 57 | + |
| 58 | + Ok(Json(responses)) |
| 59 | +} |
| 60 | + |
| 61 | +/// Handle GET /tenants/resources/tenants/v1/:id |
| 62 | +/// Gets a single tenant by ID. |
| 63 | +/// |
| 64 | +/// Note: The frontegg client expects a Vec<Tenant> response (and pops the first element). |
| 65 | +pub async fn handle_get_tenant( |
| 66 | + State(context): State<Arc<Context>>, |
| 67 | + Path(id): Path<Uuid>, |
| 68 | +) -> Result<Json<Vec<TenantResponse>>, StatusCode> { |
| 69 | + let tenants = context.tenants.lock().unwrap(); |
| 70 | + |
| 71 | + // If the tenant exists in the explicit tenants map, return it |
| 72 | + if let Some(tenant) = tenants.get(&id) { |
| 73 | + return Ok(Json(vec![TenantResponse::from(tenant)])); |
| 74 | + } |
| 75 | + drop(tenants); |
| 76 | + |
| 77 | + // Check if the tenant exists in users |
| 78 | + let users = context.users.lock().unwrap(); |
| 79 | + let tenant_exists = users.values().any(|u| u.tenant_id == id); |
| 80 | + drop(users); |
| 81 | + |
| 82 | + if !tenant_exists { |
| 83 | + return Ok(Json(vec![])); // Empty vec will cause client to return NOT_FOUND |
| 84 | + } |
| 85 | + |
| 86 | + // Return a derived tenant |
| 87 | + let now = Utc::now(); |
| 88 | + let response = TenantResponse { |
| 89 | + id, |
| 90 | + name: format!("Tenant {}", &id.to_string()[..8]), |
| 91 | + metadata: serde_json::json!({}), |
| 92 | + creator_name: None, |
| 93 | + creator_email: None, |
| 94 | + created_at: now, |
| 95 | + updated_at: now, |
| 96 | + deleted_at: None, |
| 97 | + }; |
| 98 | + |
| 99 | + Ok(Json(vec![response])) |
| 100 | +} |
| 101 | + |
| 102 | +/// Request body for creating a tenant. |
| 103 | +#[derive(Debug, Deserialize)] |
| 104 | +#[serde(rename_all = "camelCase")] |
| 105 | +pub struct CreateTenantRequest { |
| 106 | + #[serde(default = "Uuid::new_v4")] |
| 107 | + pub tenant_id: Uuid, |
| 108 | + pub name: String, |
| 109 | + #[serde(default)] |
| 110 | + pub metadata: serde_json::Value, |
| 111 | + pub creator_name: Option<String>, |
| 112 | + pub creator_email: Option<String>, |
| 113 | +} |
| 114 | + |
| 115 | +/// Handle POST /tenants/resources/tenants/v1 |
| 116 | +/// Creates a new tenant. |
| 117 | +pub async fn handle_create_tenant( |
| 118 | + State(context): State<Arc<Context>>, |
| 119 | + Json(body): Json<CreateTenantRequest>, |
| 120 | +) -> Result<Json<TenantResponse>, StatusCode> { |
| 121 | + let now = Utc::now(); |
| 122 | + let tenant = TenantConfig { |
| 123 | + id: body.tenant_id, |
| 124 | + name: body.name, |
| 125 | + metadata: body.metadata, |
| 126 | + creator_name: body.creator_name, |
| 127 | + creator_email: body.creator_email, |
| 128 | + created_at: now, |
| 129 | + updated_at: now, |
| 130 | + deleted_at: None, |
| 131 | + }; |
| 132 | + |
| 133 | + let response = TenantResponse::from(&tenant); |
| 134 | + let mut tenants = context.tenants.lock().unwrap(); |
| 135 | + tenants.insert(tenant.id, tenant); |
| 136 | + |
| 137 | + Ok(Json(response)) |
| 138 | +} |
| 139 | + |
| 140 | +/// Request body for setting tenant metadata. |
| 141 | +#[derive(Debug, Deserialize)] |
| 142 | +pub struct SetTenantMetadataRequest { |
| 143 | + pub metadata: serde_json::Value, |
| 144 | +} |
| 145 | + |
| 146 | +/// Handle POST /tenants/resources/tenants/v1/:id/metadata |
| 147 | +/// Sets/updates tenant metadata. |
| 148 | +pub async fn handle_set_tenant_metadata( |
| 149 | + State(context): State<Arc<Context>>, |
| 150 | + Path(id): Path<Uuid>, |
| 151 | + Json(body): Json<SetTenantMetadataRequest>, |
| 152 | +) -> Result<Json<TenantResponse>, StatusCode> { |
| 153 | + let mut tenants = context.tenants.lock().unwrap(); |
| 154 | + |
| 155 | + // If the tenant exists in the explicit tenants map, update it |
| 156 | + if let Some(tenant) = tenants.get_mut(&id) { |
| 157 | + // Merge the new metadata with existing metadata |
| 158 | + if let Some(existing) = tenant.metadata.as_object_mut() { |
| 159 | + if let Some(new_obj) = body.metadata.as_object() { |
| 160 | + for (k, v) in new_obj { |
| 161 | + existing.insert(k.clone(), v.clone()); |
| 162 | + } |
| 163 | + } |
| 164 | + } else { |
| 165 | + tenant.metadata = body.metadata; |
| 166 | + } |
| 167 | + tenant.updated_at = Utc::now(); |
| 168 | + return Ok(Json(TenantResponse::from(&*tenant))); |
| 169 | + } |
| 170 | + drop(tenants); |
| 171 | + |
| 172 | + // Check if the tenant exists in users |
| 173 | + let users = context.users.lock().unwrap(); |
| 174 | + let tenant_exists = users.values().any(|u| u.tenant_id == id); |
| 175 | + drop(users); |
| 176 | + |
| 177 | + if !tenant_exists { |
| 178 | + return Err(StatusCode::NOT_FOUND); |
| 179 | + } |
| 180 | + |
| 181 | + // Create a new tenant entry with the metadata |
| 182 | + let now = Utc::now(); |
| 183 | + let tenant = TenantConfig { |
| 184 | + id, |
| 185 | + name: format!("Tenant {}", &id.to_string()[..8]), |
| 186 | + metadata: body.metadata, |
| 187 | + creator_name: None, |
| 188 | + creator_email: None, |
| 189 | + created_at: now, |
| 190 | + updated_at: now, |
| 191 | + deleted_at: None, |
| 192 | + }; |
| 193 | + let response = TenantResponse::from(&tenant); |
| 194 | + let mut tenants = context.tenants.lock().unwrap(); |
| 195 | + tenants.insert(id, tenant); |
| 196 | + |
| 197 | + Ok(Json(response)) |
| 198 | +} |
0 commit comments