use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::error::AppError; use crate::models::common::Role; use crate::models::repos::RepoInvitation; use crate::pb::email::{EmailAddress, SendEmailRequest}; use crate::service::RepoService; use crate::session::Session; use super::util::{clamp_limit_offset, ensure_affected, role_level}; #[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)] pub struct CreateRepoInvitationParams { pub email: String, pub role: Option, } #[derive(Serialize, Clone, Debug)] pub struct CreateRepoInvitationResponse { pub invitation: RepoInvitation, } impl RepoService { pub async fn repo_invitations( &self, ctx: &Session, wk_name: &str, repo_name: &str, limit: i64, offset: i64, ) -> Result, AppError> { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let repo = self.resolve_repo(wk_name, repo_name).await?; let repo_id = repo.id; self.ensure_repo_role_at_least(user_uid, &repo, Role::Admin) .await?; let (limit, offset) = clamp_limit_offset(limit, offset); sqlx::query_as::<_, RepoInvitation>( "SELECT id, repo_id, email, role, token_hash, invited_by, accepted_by, accepted_at, revoked_at, expires_at, created_at FROM repo_invitation \ WHERE repo_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(repo_id) .bind(limit) .bind(offset) .fetch_all(self.ctx.db.reader()) .await .map_err(AppError::Database) } pub async fn repo_create_invitation( &self, ctx: &Session, wk_name: &str, repo_name: &str, params: CreateRepoInvitationParams, ) -> Result { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let repo = self.resolve_repo(wk_name, repo_name).await?; let repo_id = repo.id; let actor_role = self .ensure_repo_role_at_least(user_uid, &repo, 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 repo_invitation \ WHERE repo_id = $1 AND lower(email) = lower($2) \ AND revoked_at IS NULL AND accepted_at IS NULL AND expires_at > NOW())", ) .bind(repo_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::().ok()) .unwrap_or(Role::Member); if role == Role::Owner || role == Role::Unknown { 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(), )); } let token = generate_repo_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 app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let invitation = sqlx::query_as::<_, RepoInvitation>( "INSERT INTO repo_invitation (id, repo_id, email, role, token_hash, invited_by, expires_at, created_at) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \ RETURNING id, repo_id, email, role, token_hash, invited_by, accepted_by, accepted_at, revoked_at, expires_at, created_at", ) .bind(Uuid::now_v7()) .bind(repo_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!("{}/repo/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 repo {}", repo.name), text_body: format!( "You've been invited to join repository '{}'.\n\nAccept the invitation here:\n\n{}\n\nThis invitation expires in 7 days.", repo.name, invite_link ), ..Default::default() })) .await .map_err(|e| AppError::InternalServerError(e.to_string()))?; tracing::info!(email = %email, invitation_id = %invitation.id, repo_id = %repo_id, "Repo invitation created"); Ok(CreateRepoInvitationResponse { invitation }) } pub async fn repo_revoke_invitation( &self, ctx: &Session, wk_name: &str, repo_name: &str, invitation_id: Uuid, ) -> Result<(), AppError> { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let repo = self.resolve_repo(wk_name, repo_name).await?; let repo_id = repo.id; self.ensure_repo_role_at_least(user_uid, &repo, 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 app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query( "UPDATE repo_invitation SET revoked_at = $1 WHERE id = $2 AND repo_id = $3 \ AND revoked_at IS NULL AND accepted_at IS NULL", ) .bind(now) .bind(invitation_id) .bind(repo_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 repo_accept_invitation( &self, ctx: &Session, token: &str, ) -> Result { 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::<_, RepoInvitation>( "SELECT id, repo_id, email, role, token_hash, invited_by, accepted_by, accepted_at, revoked_at, expires_at, created_at FROM repo_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 repo_member WHERE repo_id = $1 AND user_id = $2)", ) .bind(invitation.repo_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 repo".into())); } let user_email: Option = 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 repo = self.find_repo_by_id(invitation.repo_id).await?; let role_str = invitation.role.to_string(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let workspace_member_result = sqlx::query( "INSERT INTO workspace_member (id, workspace_id, user_id, role, status, joined_at, created_at, updated_at) \ VALUES ($1, $2, $3, 'member', 'active', $4, $4, $4) ON CONFLICT (workspace_id, user_id) DO NOTHING", ) .bind(Uuid::now_v7()) .bind(repo.workspace_id) .bind(user_uid) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; if workspace_member_result.rows_affected() > 0 { sqlx::query( "UPDATE workspace_stats SET members_count = members_count + 1, updated_at = $1 WHERE workspace_id = $2", ) .bind(now) .bind(repo.workspace_id) .execute(&mut *txn) .await .map_err(AppError::Database)?; } let result = sqlx::query_as::<_, RepoInvitation>( "UPDATE repo_invitation SET accepted_by = $1, accepted_at = $2 \ WHERE id = $3 AND revoked_at IS NULL AND accepted_at IS NULL \ RETURNING id, repo_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 repo_member (id, repo_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 (repo_id, user_id) DO NOTHING", ) .bind(Uuid::now_v7()) .bind(invitation.repo_id) .bind(user_uid) .bind(&role_str) .bind(invitation.invited_by) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(result) } } fn sha256_hex(data: &[u8]) -> String { use sha2::Digest; sha2::Sha256::digest(data) .iter() .map(|b| format!("{b:02x}")) .collect() } fn generate_repo_invitation_token() -> String { (0..64) .map(|_| format!("{:02x}", rand::random::())) .collect() }