Files
zhenyi 420dedbc1e feat(service): expand service layer with new domain operations
- Add IM service modules: audit, channel roles, custom emojis, forum
  tags, integrations, invitations, repo links, slash commands, stages,
  voice, webhooks
- Add PR service modules: review requests, templates
- Add repo service modules: contributors, release assets, git extras
  (archive, branch rename, commit extras, diff/merge, tag, tree)
- Add user service: social (follow/block)
- Add internal auth service
- Update existing service modules with expanded functionality
- Remove deleted IM modules: articles, delivery trace, drafts,
  follows, messages, polls, presence, reactions, threads
2026-06-10 18:49:32 +08:00

317 lines
11 KiB
Rust

use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Role;
use crate::models::workspaces::{Workspace, WorkspaceInvitation};
use crate::pb::email::{EmailAddress, SendEmailRequest};
use crate::service::WorkspaceService;
use crate::session::Session;
use super::util::{clamp_limit_offset, ensure_affected, role_level, set_local_user_id};
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct CreateInvitationParams {
pub email: String,
pub role: Option<String>,
}
#[derive(Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct CreateInvitationResponse {
pub invitation: WorkspaceInvitation,
}
impl WorkspaceService {
pub async fn workspace_invitations(
&self,
ctx: &Session,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceInvitation>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
sqlx::query_as::<_, WorkspaceInvitation>(
"SELECT id, workspace_id, email, role, token_hash, invited_by, accepted_by, \
accepted_at, revoked_at, expires_at, created_at FROM workspace_invitation \
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(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
}
pub async fn workspace_create_invitation(
&self,
ctx: &Session,
ws: &Workspace,
params: CreateInvitationParams,
) -> Result<CreateInvitationResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let actor_role = self
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let email = params.email.trim().to_lowercase();
if email.is_empty() {
return Err(AppError::BadRequest("email is required".into()));
}
let existing = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM workspace_invitation \
WHERE workspace_id = $1 AND lower(email) = lower($2) \
AND revoked_at IS NULL AND accepted_at IS NULL AND expires_at > NOW())",
)
.bind(ws.id)
.bind(&email)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
if existing {
return Err(AppError::BadRequest(
"invitation already exists for this email".into(),
));
}
let role = params
.role
.as_deref()
.and_then(|r| r.parse::<Role>().ok())
.unwrap_or(ws.default_role.parse().unwrap_or(Role::Member));
if role == Role::Owner || role == Role::Unknown {
return Err(AppError::BadRequest("invalid role for invitation".into()));
}
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(),
));
}
let token = Self::generate_invitation_token();
let token_hash = sha256_hex(token.as_bytes());
let now = chrono::Utc::now();
let expires_at = now + chrono::Duration::days(7);
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query(set_local_user_id(user_uid))
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let invitation = sqlx::query_as::<_, WorkspaceInvitation>(
"INSERT INTO workspace_invitation (id, workspace_id, email, role, token_hash, invited_by, expires_at, created_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \
RETURNING id, workspace_id, email, role, token_hash, invited_by, accepted_by, \
accepted_at, revoked_at, expires_at, created_at",
)
.bind(Uuid::now_v7())
.bind(ws.id)
.bind(&email)
.bind(role.to_string())
.bind(&token_hash)
.bind(user_uid)
.bind(expires_at)
.bind(now)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
let domain = self.ctx.config.main_domain()?;
let invite_link = format!("{}/workspace/invitations/accept?token={}", domain, token);
let mut mail = self
.ctx
.registry
.get_email_client()
.ok_or(AppError::Config("mail service not available".into()))?;
mail.send_email(tonic::Request::new(SendEmailRequest {
to: vec![EmailAddress {
email: email.clone(),
name: String::new(),
}],
subject: format!("You're invited to join {}", ws.name),
text_body: format!(
"You've been invited to join workspace '{}'.\n\nAccept the invitation here:\n\n{}\n\nThis invitation expires in 7 days.",
ws.name, invite_link
),
..Default::default()
}))
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
tracing::info!(email = %email, invitation_id = %invitation.id, "Invitation created");
Ok(CreateInvitationResponse { invitation })
}
pub async fn workspace_revoke_invitation(
&self,
ctx: &Session,
ws: &Workspace,
invitation_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query(set_local_user_id(user_uid))
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query(
"UPDATE workspace_invitation SET revoked_at = $1 WHERE id = $2 AND workspace_id = $3 \
AND revoked_at IS NULL AND accepted_at IS NULL",
)
.bind(now)
.bind(invitation_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(
result.rows_affected(),
"invitation not found or already used",
)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(())
}
pub async fn workspace_accept_invitation(
&self,
ctx: &Session,
token: &str,
) -> Result<WorkspaceInvitation, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let token_hash = sha256_hex(token.as_bytes());
let now = chrono::Utc::now();
let invitation = sqlx::query_as::<_, WorkspaceInvitation>(
"SELECT id, workspace_id, email, role, token_hash, invited_by, accepted_by, \
accepted_at, revoked_at, expires_at, created_at FROM workspace_invitation \
WHERE token_hash = $1 AND revoked_at IS NULL AND accepted_at IS NULL AND expires_at > NOW()",
)
.bind(&token_hash)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
.ok_or(AppError::BadRequest("invalid or expired invitation".into()))?;
let already_member = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2)",
)
.bind(invitation.workspace_id)
.bind(user_uid)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
if already_member {
return Err(AppError::BadRequest(
"already a member of this workspace".into(),
));
}
let user_email: Option<String> = sqlx::query_scalar(
"SELECT email FROM user_mail WHERE user_id = $1 AND is_verified = true LIMIT 1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
if user_email
.as_deref()
.map(|e| e.trim().eq_ignore_ascii_case(&invitation.email))
!= Some(true)
{
return Err(AppError::Unauthorized);
}
let role_str = invitation.role.to_string();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query(set_local_user_id(user_uid))
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query_as::<_, WorkspaceInvitation>(
"UPDATE workspace_invitation SET accepted_by = $1, accepted_at = $2 \
WHERE id = $3 AND revoked_at IS NULL AND accepted_at IS NULL \
RETURNING id, workspace_id, email, role, token_hash, invited_by, accepted_by, \
accepted_at, revoked_at, expires_at, created_at",
)
.bind(user_uid)
.bind(now)
.bind(invitation.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"INSERT INTO workspace_member (id, workspace_id, user_id, role, status, invited_by, joined_at, created_at, updated_at) \
VALUES ($1, $2, $3, $4, 'active', $5, $6, $6, $6) \
ON CONFLICT (workspace_id, user_id) DO NOTHING",
)
.bind(Uuid::now_v7())
.bind(invitation.workspace_id)
.bind(user_uid)
.bind(&role_str)
.bind(invitation.invited_by)
.bind(now)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"UPDATE workspace_stats SET members_count = members_count + 1, updated_at = $1 WHERE workspace_id = $2",
)
.bind(now)
.bind(invitation.workspace_id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(result)
}
fn generate_invitation_token() -> String {
(0..64)
.map(|_| format!("{:02x}", rand::random::<u8>()))
.collect()
}
}
use crate::service::util::sha256_hex;