refactor(workspace): pass workspace object instead of id to service methods

- Replace workspace_id parameter with Workspace object reference in all workspace service methods
- Remove redundant find_workspace_by_id calls that were duplicated in each method
- Update all method signatures across approval, audit, billing, branding, core, settings and stats modules
- Modify SQL queries to bind ws.id instead of separate workspace_id parameter
- Add Workspace import to all affected modules
- Adjust method calls in API handlers to pass workspace object instead of id
- Consolidate workspace retrieval logic to single location per operation flow
This commit is contained in:
zhenyi
2026-06-07 18:44:01 +08:00
parent 297a54f312
commit dca717be10
75 changed files with 2306 additions and 212 deletions
+7 -10
View File
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::{RequestType, Role, Status};
use crate::models::workspaces::WorkspacePendingApproval;
use crate::models::workspaces::{Workspace, WorkspacePendingApproval};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -19,12 +19,11 @@ impl WorkspaceService {
pub async fn workspace_pending_approvals(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspacePendingApproval>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
@@ -33,7 +32,7 @@ impl WorkspaceService {
reviewed_by, reviewed_at, expires_at, created_at, updated_at \
FROM workspace_pending_approval WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
@@ -44,11 +43,10 @@ impl WorkspaceService {
pub async fn workspace_request_approval(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: RequestApprovalParams,
) -> Result<WorkspacePendingApproval, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_readable(user_uid, &ws).await?;
let request_type = parse_enum(
@@ -79,7 +77,7 @@ impl WorkspaceService {
reviewed_by, reviewed_at, expires_at, created_at, updated_at",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(ws.id)
.bind(user_uid)
.bind(request_type)
.bind(params.reason)
@@ -96,12 +94,11 @@ impl WorkspaceService {
pub async fn workspace_review_approval(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
approval_id: Uuid,
approved: bool,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
@@ -133,7 +130,7 @@ impl WorkspaceService {
.bind(user_uid)
.bind(now)
.bind(approval_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
+3 -4
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::{EventType, JsonValue, Role, TargetType};
use crate::models::workspaces::WorkspaceAuditLog;
use crate::models::workspaces::{Workspace, WorkspaceAuditLog};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -12,12 +12,11 @@ impl WorkspaceService {
pub async fn workspace_audit_logs(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceAuditLog>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
@@ -26,7 +25,7 @@ impl WorkspaceService {
ip_address, user_agent, metadata, created_at FROM workspace_audit_log \
WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
+6 -8
View File
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::WorkspaceBilling;
use crate::models::workspaces::{Workspace, WorkspaceBilling};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -20,27 +20,25 @@ impl WorkspaceService {
pub async fn workspace_billing(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<WorkspaceBilling, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
self.ensure_workspace_billing(workspace_id).await
self.ensure_workspace_billing(ws.id).await
}
pub async fn workspace_update_billing(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: UpdateBillingParams,
) -> Result<WorkspaceBilling, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
let current = self.ensure_workspace_billing(workspace_id).await?;
let current = self.ensure_workspace_billing(ws.id).await?;
let plan = params.plan.unwrap_or(current.plan.clone());
let billing_email = merge_optional_text(params.billing_email, current.billing_email);
let seats = params.seats.unwrap_or(current.seats);
@@ -70,7 +68,7 @@ impl WorkspaceService {
.bind(&billing_email)
.bind(seats)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
+6 -8
View File
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::WorkspaceCustomBranding;
use crate::models::workspaces::{Workspace, WorkspaceCustomBranding};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -24,27 +24,25 @@ impl WorkspaceService {
pub async fn workspace_branding(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<WorkspaceCustomBranding, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
self.ensure_workspace_branding(workspace_id).await
self.ensure_workspace_branding(ws.id).await
}
pub async fn workspace_update_branding(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: UpdateBrandingParams,
) -> Result<WorkspaceCustomBranding, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let current = self.ensure_workspace_branding(workspace_id).await?;
let current = self.ensure_workspace_branding(ws.id).await?;
let now = chrono::Utc::now();
let mut txn = self
@@ -75,7 +73,7 @@ impl WorkspaceService {
.bind(merge_optional_text(params.support_url, current.support_url))
.bind(params.enabled.unwrap_or(current.enabled))
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
+21 -47
View File
@@ -52,12 +52,11 @@ impl WorkspaceService {
pub async fn workspace_get(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_readable(user_uid, &ws).await?;
Ok(ws)
Ok(ws.clone())
}
pub async fn workspace_create(
@@ -177,17 +176,16 @@ impl WorkspaceService {
pub async fn workspace_update(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: UpdateWorkspaceParams,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let name =
merge_optional_text(params.name, Some(ws.name.clone())).unwrap_or(ws.name.clone());
let description = merge_optional_text(params.description, ws.description);
let description = merge_optional_text(params.description, ws.description.clone());
let visibility = parse_enum(
params.visibility,
ws.visibility,
@@ -204,7 +202,6 @@ impl WorkspaceService {
None => ws.default_role.parse().unwrap_or(Role::Member),
};
// Restrict default_role to safe roles only
match default_role {
Role::Member | Role::Contributor | Role::Viewer | Role::Guest => {}
_ => {
@@ -239,7 +236,7 @@ impl WorkspaceService {
.bind(visibility)
.bind(default_role.to_string())
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(&mut *txn)
.await
.map_err(AppError::Database)?
@@ -249,13 +246,8 @@ impl WorkspaceService {
Ok(result)
}
pub async fn workspace_archive(
&self,
ctx: &Session,
workspace_id: Uuid,
) -> Result<(), AppError> {
pub async fn workspace_archive(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
@@ -278,7 +270,7 @@ impl WorkspaceService {
WHERE id = $2 AND deleted_at IS NULL AND status <> 'archived'",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -291,13 +283,8 @@ impl WorkspaceService {
Ok(())
}
pub async fn workspace_unarchive(
&self,
ctx: &Session,
workspace_id: Uuid,
) -> Result<(), AppError> {
pub async fn workspace_unarchive(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
@@ -320,7 +307,7 @@ impl WorkspaceService {
WHERE id = $2 AND deleted_at IS NULL AND status = 'archived'",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -333,13 +320,8 @@ impl WorkspaceService {
Ok(())
}
pub async fn workspace_delete(
&self,
ctx: &Session,
workspace_id: Uuid,
) -> Result<(), AppError> {
pub async fn workspace_delete(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
@@ -362,7 +344,7 @@ impl WorkspaceService {
WHERE id = $2 AND deleted_at IS NULL",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -375,11 +357,10 @@ impl WorkspaceService {
pub async fn workspace_transfer_owner(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
new_owner_id: Uuid,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
@@ -391,7 +372,7 @@ impl WorkspaceService {
let is_member = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active')",
)
.bind(workspace_id)
.bind(ws.id)
.bind(new_owner_id)
.fetch_one(self.ctx.db.reader())
.await
@@ -422,7 +403,7 @@ impl WorkspaceService {
WHERE workspace_id = $2 AND user_id = $3",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.bind(new_owner_id)
.execute(&mut *txn)
.await
@@ -433,7 +414,7 @@ impl WorkspaceService {
WHERE workspace_id = $2 AND user_id = $3",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.bind(user_uid)
.execute(&mut *txn)
.await
@@ -446,7 +427,7 @@ impl WorkspaceService {
)
.bind(new_owner_id)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -458,13 +439,12 @@ impl WorkspaceService {
pub async fn workspace_upload_avatar(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
data: Vec<u8>,
content_type: Option<String>,
file_name: Option<String>,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -473,12 +453,7 @@ impl WorkspaceService {
crate::service::util::validate_avatar_size(data.len(), 5 * 1024 * 1024)?;
let old_avatar_url = ws.avatar_url.clone();
let storage_key = format!(
"workspaces/{}/avatar/{}.{}",
workspace_id,
Uuid::now_v7(),
ext
);
let storage_key = format!("workspaces/{}/avatar/{}.{}", ws.id, Uuid::now_v7(), ext);
self.ctx.storage.put(&storage_key, data).await?;
let avatar_url = self.ctx.storage.public_url(&storage_key).ok_or_else(|| {
AppError::Config("APP_S3_PUBLIC_URL is required for avatar upload".into())
@@ -506,7 +481,7 @@ impl WorkspaceService {
)
.bind(&avatar_url)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -557,12 +532,12 @@ impl WorkspaceService {
pub async fn workspace_user_role(
&self,
user_uid: Uuid,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<Option<Role>, AppError> {
let role_str: Option<String> = sqlx::query_scalar(
"SELECT role FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active'",
)
.bind(workspace_id)
.bind(ws.id)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
@@ -571,7 +546,6 @@ impl WorkspaceService {
match role_str {
Some(r) => Ok(Some(r.parse().unwrap_or(Role::Unknown))),
None => {
let ws = self.find_workspace_by_id(workspace_id).await?;
if ws.owner_id == user_uid {
return Ok(Some(Role::Owner));
}
+14 -19
View File
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::WorkspaceDomain;
use crate::models::workspaces::{Workspace, WorkspaceDomain};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -18,12 +18,11 @@ impl WorkspaceService {
pub async fn workspace_domains(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceDomain>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
@@ -32,7 +31,7 @@ impl WorkspaceService {
verified_at, created_at, updated_at FROM workspace_domain \
WHERE workspace_id = $1 ORDER BY is_primary DESC, created_at ASC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
@@ -43,11 +42,10 @@ impl WorkspaceService {
pub async fn workspace_add_domain(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: AddDomainParams,
) -> Result<WorkspaceDomain, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let domain = required_text(params.domain, "domain")?.to_lowercase();
@@ -55,7 +53,7 @@ impl WorkspaceService {
let is_first = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM workspace_domain WHERE workspace_id = $1",
)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
@@ -84,7 +82,7 @@ impl WorkspaceService {
RETURNING id, workspace_id, domain, verification_token_hash, is_primary, is_verified, verified_at, created_at, updated_at",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(ws.id)
.bind(&domain)
.bind(&token_hash)
.bind(is_first)
@@ -100,11 +98,10 @@ impl WorkspaceService {
pub async fn workspace_verify_domain(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
domain_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let now = chrono::Utc::now();
@@ -128,7 +125,7 @@ impl WorkspaceService {
)
.bind(now)
.bind(domain_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -144,11 +141,10 @@ impl WorkspaceService {
pub async fn workspace_set_primary_domain(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
domain_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
let now = chrono::Utc::now();
@@ -172,7 +168,7 @@ impl WorkspaceService {
WHERE id = $1 AND workspace_id = $2",
)
.bind(domain_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(&mut *txn)
.await
.map_err(AppError::Database)?
@@ -186,7 +182,7 @@ impl WorkspaceService {
sqlx::query("UPDATE workspace_domain SET is_primary = false, updated_at = $1 WHERE workspace_id = $2 AND is_primary = true")
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -205,11 +201,10 @@ impl WorkspaceService {
pub async fn workspace_delete_domain(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
domain_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -217,7 +212,7 @@ impl WorkspaceService {
"SELECT is_primary FROM workspace_domain WHERE id = $1 AND workspace_id = $2",
)
.bind(domain_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
@@ -243,7 +238,7 @@ impl WorkspaceService {
let result =
sqlx::query("DELETE FROM workspace_domain WHERE id = $1 AND workspace_id = $2")
.bind(domain_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
+10 -14
View File
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Provider;
use crate::models::workspaces::WorkspaceIntegration;
use crate::models::workspaces::{Workspace, WorkspaceIntegration};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -30,12 +30,11 @@ impl WorkspaceService {
pub async fn workspace_integrations(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceIntegration>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
@@ -44,7 +43,7 @@ impl WorkspaceService {
installed_by, last_used_at, created_at, updated_at FROM workspace_integration \
WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
@@ -55,11 +54,10 @@ impl WorkspaceService {
pub async fn workspace_create_integration(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: CreateIntegrationParams,
) -> Result<WorkspaceIntegration, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
@@ -95,7 +93,7 @@ impl WorkspaceService {
installed_by, last_used_at, created_at, updated_at",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(ws.id)
.bind(provider)
.bind(&name)
.bind(params.config.map(sqlx::types::Json))
@@ -114,12 +112,11 @@ impl WorkspaceService {
pub async fn workspace_update_integration(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
integration_id: Uuid,
params: UpdateIntegrationParams,
) -> Result<WorkspaceIntegration, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
@@ -129,7 +126,7 @@ impl WorkspaceService {
WHERE id = $1 AND workspace_id = $2",
)
.bind(integration_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
@@ -172,7 +169,7 @@ impl WorkspaceService {
.bind(enabled)
.bind(now)
.bind(integration_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -184,11 +181,10 @@ impl WorkspaceService {
pub async fn workspace_delete_integration(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
integration_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
@@ -208,7 +204,7 @@ impl WorkspaceService {
let result =
sqlx::query("DELETE FROM workspace_integration WHERE id = $1 AND workspace_id = $2")
.bind(integration_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
+8 -12
View File
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::WorkspaceInvitation;
use crate::models::workspaces::{Workspace, WorkspaceInvitation};
use crate::pb::email::{EmailAddress, SendEmailRequest};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -25,12 +25,11 @@ impl WorkspaceService {
pub async fn workspace_invitations(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceInvitation>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
@@ -40,7 +39,7 @@ impl WorkspaceService {
WHERE workspace_id = $1 AND revoked_at IS NULL AND accepted_at IS NULL \
AND expires_at > NOW() ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
@@ -51,11 +50,10 @@ impl WorkspaceService {
pub async fn workspace_create_invitation(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: CreateInvitationParams,
) -> Result<CreateInvitationResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
let actor_role = self
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -70,7 +68,7 @@ impl WorkspaceService {
WHERE workspace_id = $1 AND lower(email) = lower($2) \
AND revoked_at IS NULL AND accepted_at IS NULL AND expires_at > NOW())",
)
.bind(workspace_id)
.bind(ws.id)
.bind(&email)
.fetch_one(self.ctx.db.reader())
.await
@@ -92,7 +90,6 @@ impl WorkspaceService {
return Err(AppError::BadRequest("invalid role for invitation".into()));
}
// Non-owner admins cannot invite with roles equal to or higher than their own
if actor_role != Role::Owner && role_level(role) >= role_level(actor_role) {
return Err(AppError::BadRequest(
"cannot invite with role equal to or higher than your own".into(),
@@ -124,7 +121,7 @@ impl WorkspaceService {
accepted_at, revoked_at, expires_at, created_at",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(ws.id)
.bind(&email)
.bind(role.to_string())
.bind(&token_hash)
@@ -167,11 +164,10 @@ impl WorkspaceService {
pub async fn workspace_revoke_invitation(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
invitation_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -195,7 +191,7 @@ impl WorkspaceService {
)
.bind(now)
.bind(invitation_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
+18 -25
View File
@@ -4,7 +4,7 @@ use uuid::Uuid;
use super::util::{clamp_limit_offset, ensure_affected, role_level};
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::WorkspaceMember;
use crate::models::workspaces::{Workspace, WorkspaceMember};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -23,12 +23,11 @@ impl WorkspaceService {
pub async fn workspace_members(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceMember>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_readable(user_uid, &ws).await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
sqlx::query_as::<_, WorkspaceMember>(
@@ -36,7 +35,7 @@ impl WorkspaceService {
last_active_at, created_at, updated_at FROM workspace_member \
WHERE workspace_id = $1 AND status = 'active' ORDER BY created_at ASC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
@@ -47,11 +46,10 @@ impl WorkspaceService {
pub async fn workspace_add_member(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: AddMemberParams,
) -> Result<WorkspaceMember, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
let actor_role = self
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -59,7 +57,7 @@ impl WorkspaceService {
let settings_allow = sqlx::query_scalar::<_, bool>(
"SELECT allow_member_invites FROM workspace_settings WHERE workspace_id = $1",
)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
@@ -73,7 +71,7 @@ impl WorkspaceService {
let existing = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2)",
)
.bind(workspace_id)
.bind(ws.id)
.bind(params.user_id)
.fetch_one(self.ctx.db.reader())
.await
@@ -96,7 +94,6 @@ impl WorkspaceService {
return Err(AppError::BadRequest("invalid role".into()));
}
// Non-owner admins cannot grant roles equal to or higher than their own
if actor_role != Role::Owner && role_level(role) >= role_level(actor_role) {
return Err(AppError::BadRequest(
"cannot grant role equal to or higher than your own".into(),
@@ -123,7 +120,7 @@ impl WorkspaceService {
RETURNING id, workspace_id, user_id, role, status, invited_by, joined_at, last_active_at, created_at, updated_at",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(ws.id)
.bind(params.user_id)
.bind(role.to_string())
.bind(user_uid)
@@ -136,7 +133,7 @@ impl WorkspaceService {
"UPDATE workspace_stats SET members_count = members_count + 1, updated_at = $1 WHERE workspace_id = $2",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -148,12 +145,11 @@ impl WorkspaceService {
pub async fn workspace_update_member_role(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
member_id: Uuid,
params: UpdateMemberRoleParams,
) -> Result<WorkspaceMember, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
let actor_role = self
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -171,7 +167,6 @@ impl WorkspaceService {
return Err(AppError::BadRequest("invalid role".into()));
}
// Non-owner admins cannot grant roles equal to or higher than their own
if actor_role != Role::Owner && role_level(new_role) >= role_level(actor_role) {
return Err(AppError::BadRequest(
"cannot grant role equal to or higher than your own".into(),
@@ -184,7 +179,7 @@ impl WorkspaceService {
WHERE id = $1 AND workspace_id = $2",
)
.bind(member_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
@@ -222,7 +217,7 @@ impl WorkspaceService {
.bind(new_role.to_string())
.bind(now)
.bind(member_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -234,11 +229,10 @@ impl WorkspaceService {
pub async fn workspace_remove_member(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
member_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
let actor_role = self
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -249,7 +243,7 @@ impl WorkspaceService {
WHERE id = $1 AND workspace_id = $2",
)
.bind(member_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
@@ -283,7 +277,7 @@ impl WorkspaceService {
let result =
sqlx::query("DELETE FROM workspace_member WHERE id = $1 AND workspace_id = $2")
.bind(member_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -293,7 +287,7 @@ impl WorkspaceService {
"UPDATE workspace_stats SET members_count = GREATEST(members_count - 1, 0), updated_at = $1 WHERE workspace_id = $2",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -302,9 +296,8 @@ impl WorkspaceService {
Ok(())
}
pub async fn workspace_leave(&self, ctx: &Session, workspace_id: Uuid) -> Result<(), AppError> {
pub async fn workspace_leave(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
if ws.owner_id == user_uid {
return Err(AppError::BadRequest(
@@ -328,7 +321,7 @@ impl WorkspaceService {
let result =
sqlx::query("DELETE FROM workspace_member WHERE workspace_id = $1 AND user_id = $2")
.bind(workspace_id)
.bind(ws.id)
.bind(user_uid)
.execute(&mut *txn)
.await
@@ -339,7 +332,7 @@ impl WorkspaceService {
"UPDATE workspace_stats SET members_count = GREATEST(members_count - 1, 0), updated_at = $1 WHERE workspace_id = $2",
)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
+6 -8
View File
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::AppError;
use crate::models::workspaces::WorkspaceSettings;
use crate::models::workspaces::{Workspace, WorkspaceSettings};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -24,26 +24,24 @@ impl WorkspaceService {
pub async fn workspace_settings(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<WorkspaceSettings, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_readable(user_uid, &ws).await?;
self.ensure_user_workspace_settings(workspace_id).await
self.ensure_user_workspace_settings(ws.id).await
}
pub async fn workspace_update_settings(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: UpdateWorkspaceSettingsParams,
) -> Result<WorkspaceSettings, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
let current = self.ensure_user_workspace_settings(workspace_id).await?;
let current = self.ensure_user_workspace_settings(ws.id).await?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
@@ -77,7 +75,7 @@ impl WorkspaceService {
.bind(params.pull_requests_enabled.unwrap_or(current.pull_requests_enabled))
.bind(params.wiki_enabled.unwrap_or(current.wiki_enabled))
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
+9 -11
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::WorkspaceStats;
use crate::models::workspaces::{Workspace, WorkspaceStats};
use crate::service::WorkspaceService;
use crate::session::Session;
@@ -10,28 +10,26 @@ impl WorkspaceService {
pub async fn workspace_stats(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<WorkspaceStats, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_readable(user_uid, &ws).await?;
self.ensure_workspace_stats(workspace_id).await
self.ensure_workspace_stats(ws.id).await
}
pub async fn workspace_refresh_stats(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
) -> Result<WorkspaceStats, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let members_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM workspace_member WHERE workspace_id = $1 AND status = 'active'",
)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
@@ -39,7 +37,7 @@ impl WorkspaceService {
let repos_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM repo WHERE workspace_id = $1 AND deleted_at IS NULL",
)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
@@ -47,7 +45,7 @@ impl WorkspaceService {
let issues_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM issue WHERE repo_id IN (SELECT id FROM repo WHERE workspace_id = $1 AND deleted_at IS NULL) AND deleted_at IS NULL",
)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
@@ -55,7 +53,7 @@ impl WorkspaceService {
let prs_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM pull_request WHERE repo_id IN (SELECT id FROM repo WHERE workspace_id = $1 AND deleted_at IS NULL) AND deleted_at IS NULL",
)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
@@ -72,7 +70,7 @@ impl WorkspaceService {
.bind(issues_count)
.bind(prs_count)
.bind(now)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
+10 -26
View File
@@ -5,35 +5,27 @@ use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::{EventType, Role};
use crate::models::workspaces::WorkspaceWebhook;
use crate::models::workspaces::{Workspace, WorkspaceWebhook};
use crate::service::WorkspaceService;
use crate::session::Session;
use super::util::{clamp_limit_offset, ensure_affected, required_text};
/// Validate webhook URL for SSRF protection
fn validate_webhook_url(url_str: &str) -> Result<(), AppError> {
let url = Url::parse(url_str).map_err(|_| AppError::BadRequest("Invalid URL format".into()))?;
// Only allow HTTPS
if url.scheme() != "https" {
return Err(AppError::BadRequest(
"Webhook URL must use HTTPS protocol".into(),
));
}
let host = url
.host_str()
.ok_or_else(|| AppError::BadRequest("URL must have a host".into()))?;
// Reject IP addresses directly (require domain names)
if host.parse::<IpAddr>().is_ok() {
return Err(AppError::BadRequest(
"Webhook URL must use a domain name, not an IP address".into(),
));
}
// Reject localhost and common local domains
let host_lower = host.to_lowercase();
if host_lower == "localhost"
|| host_lower.ends_with(".localhost")
@@ -47,14 +39,11 @@ fn validate_webhook_url(url_str: &str) -> Result<(), AppError> {
"Webhook URL cannot point to localhost or internal domains".into(),
));
}
// Reject metadata endpoints (AWS, GCP, Azure)
if host == "169.254.169.254" || host == "metadata.google.internal" {
return Err(AppError::BadRequest(
"Webhook URL cannot point to cloud metadata endpoints".into(),
));
}
Ok(())
}
@@ -78,12 +67,11 @@ impl WorkspaceService {
pub async fn workspace_webhooks(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceWebhook>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
@@ -92,7 +80,7 @@ impl WorkspaceService {
last_delivery_status, last_delivery_at, created_by, created_at, updated_at \
FROM workspace_webhook WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(workspace_id)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
@@ -103,11 +91,10 @@ impl WorkspaceService {
pub async fn workspace_create_webhook(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
params: CreateWebhookParams,
) -> Result<WorkspaceWebhook, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -141,7 +128,7 @@ impl WorkspaceService {
last_delivery_status, last_delivery_at, created_by, created_at, updated_at",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(ws.id)
.bind(&url)
.bind(&params.secret_ciphertext)
.bind(&params.events)
@@ -159,12 +146,11 @@ impl WorkspaceService {
pub async fn workspace_update_webhook(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
webhook_id: Uuid,
params: UpdateWebhookParams,
) -> Result<WorkspaceWebhook, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -174,7 +160,7 @@ impl WorkspaceService {
FROM workspace_webhook WHERE id = $1 AND workspace_id = $2",
)
.bind(webhook_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
@@ -186,7 +172,6 @@ impl WorkspaceService {
.map(|u| u.trim().to_string())
.unwrap_or(current.url);
// Validate URL if it was updated
if params.url.is_some() {
validate_webhook_url(&url)?;
}
@@ -219,7 +204,7 @@ impl WorkspaceService {
.bind(active)
.bind(now)
.bind(webhook_id)
.bind(workspace_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -231,11 +216,10 @@ impl WorkspaceService {
pub async fn workspace_delete_webhook(
&self,
ctx: &Session,
workspace_id: Uuid,
ws: &Workspace,
webhook_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ws = self.find_workspace_by_id(workspace_id).await?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
@@ -255,7 +239,7 @@ impl WorkspaceService {
let result =
sqlx::query("DELETE FROM workspace_webhook WHERE id = $1 AND workspace_id = $2")
.bind(webhook_id)
.bind(workspace_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;