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
This commit is contained in:
zhenyi
2026-06-10 18:49:32 +08:00
parent cec6dce955
commit 420dedbc1e
100 changed files with 3797 additions and 3839 deletions
+190 -40
View File
@@ -3,11 +3,12 @@ use serde::{Deserialize, Serialize};
use crate::error::AppError;
use crate::models::common::Visibility;
use crate::models::users::User;
use crate::pb::email::{EmailAddress, SendEmailRequest};
use crate::service::UserService;
use crate::session::Session;
use super::util::{merge_optional_text, parse_enum};
use crate::service::util::extract_storage_key_from_url;
use crate::service::util::{extract_storage_key_from_url, sha256_hex};
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct UpdateUserAccountParams {
@@ -17,20 +18,9 @@ pub struct UpdateUserAccountParams {
pub visibility: Option<String>,
}
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct UploadUserAvatarParams {
pub data: Vec<u8>,
pub content_type: Option<String>,
pub file_name: Option<String>,
}
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct UserAvatarResponse {
pub avatar_url: String,
pub storage_key: String,
}
impl UserService {
const RESTORE_TOKEN_VALIDITY_DAYS: i64 = 30;
pub async fn user_account(&self, ctx: &Session) -> Result<User, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
crate::models::users::User::find_by_id(self.ctx.db.reader(), user_uid)
@@ -83,11 +73,13 @@ impl UserService {
pub async fn user_upload_avatar(
&self,
ctx: &Session,
params: UploadUserAvatarParams,
) -> Result<UserAvatarResponse, AppError> {
data: Vec<u8>,
content_type: Option<String>,
file_name: Option<String>,
) -> Result<(String, String), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let ext = avatar_extension(params.content_type.as_deref(), params.file_name.as_deref())?;
validate_avatar_size(params.data.len(), self.ctx.config.s3_max_upload_size()?)?;
let ext = avatar_extension(content_type.as_deref(), file_name.as_deref())?;
validate_avatar_size(data.len(), self.ctx.config.s3_max_upload_size()?)?;
let current = crate::models::users::User::find_by_id(self.ctx.db.reader(), user_uid)
.await
@@ -96,7 +88,7 @@ impl UserService {
let old_avatar_url = current.avatar_url.clone();
let storage_key = format!("users/{}/avatar/{}.{}", user_uid, uuid::Uuid::now_v7(), ext);
self.ctx.storage.put(&storage_key, params.data).await?;
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())
})?;
@@ -123,10 +115,7 @@ impl UserService {
let _ = self.ctx.storage.delete(&old_key).await;
}
Ok(UserAvatarResponse {
avatar_url,
storage_key,
})
Ok((avatar_url, storage_key))
}
pub async fn user_delete_account(&self, ctx: &Session) -> Result<(), AppError> {
@@ -158,6 +147,120 @@ impl UserService {
));
}
let has_verified_email: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM user_mail WHERE user_id = $1 AND is_verified = true AND deleted_at IS NULL)",
)
.bind(user_uid)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
if !has_verified_email {
return Err(AppError::BadRequest(
"please add and verify an email address before deleting your account".into(),
));
}
let primary_email: Option<String> = sqlx::query_scalar(
"SELECT email FROM user_mail WHERE user_id = $1 AND is_verified = true AND is_primary = true AND deleted_at IS NULL LIMIT 1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
let fallback_email: Option<String> = sqlx::query_scalar(
"SELECT email FROM user_mail WHERE user_id = $1 AND is_verified = true AND deleted_at IS NULL ORDER BY created_at LIMIT 1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
let email = primary_email.or(fallback_email);
let now = chrono::Utc::now();
let restore_token = uuid::Uuid::now_v7().to_string();
let token_hash = sha256_hex(restore_token.as_bytes());
let expires_at = now + chrono::Duration::days(Self::RESTORE_TOKEN_VALIDITY_DAYS);
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
for statement in [
"UPDATE user_personal_access_token SET revoked_at = $1 WHERE user_id = $2 AND revoked_at IS NULL",
"UPDATE user_session SET revoked_at = $1 WHERE user_id = $2 AND revoked_at IS NULL",
"UPDATE user_ssh_key SET revoked_at = $1 WHERE user_id = $2 AND revoked_at IS NULL",
"UPDATE user_gpg_key SET revoked_at = $1 WHERE user_id = $2 AND revoked_at IS NULL",
"UPDATE workspace_member SET status = 'deleted' WHERE user_id = $2 AND status != 'deleted'",
"UPDATE repo_member SET status = 'deleted' WHERE user_id = $2 AND status != 'deleted'",
"UPDATE user_2fa SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_activity SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_appearance SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_block SET deleted_at = $1 WHERE (user_id = $2 OR blocked_user_id = $2) AND deleted_at IS NULL",
"UPDATE user_device SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_follow SET deleted_at = $1 WHERE (user_id = $2 OR following_user_id = $2) AND deleted_at IS NULL",
"UPDATE user_mail SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_notify_setting SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_oauth SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_password SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_password_reset SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_presence SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_profile SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
"UPDATE user_security_log SET deleted_at = $1 WHERE user_id = $2 AND deleted_at IS NULL",
] {
sqlx::query(statement)
.bind(now)
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
}
let result = sqlx::query(
"UPDATE \"user\" SET deleted_at = $1, is_active = false, status = 'deleted', \
restore_token_hash = $2, restore_token_expires_at = $3, updated_at = $1 \
WHERE id = $4 AND deleted_at IS NULL",
)
.bind(now)
.bind(&token_hash)
.bind(expires_at)
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
if result.rows_affected() == 0 {
return Err(AppError::UserNotFound);
}
txn.commit().await.map_err(|_| AppError::TxnError)?;
if let Some(email) = email {
let _ = self.send_restore_email(&email, &restore_token).await;
}
ctx.clear();
Ok(())
}
pub async fn user_restore(&self, token: &str) -> Result<(), AppError> {
let token_hash = sha256_hex(token.as_bytes());
let user_id: Option<uuid::Uuid> = sqlx::query_scalar(
"SELECT id FROM \"user\" WHERE restore_token_hash = $1 \
AND deleted_at IS NOT NULL \
AND restore_token_expires_at > NOW()",
)
.bind(&token_hash)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
let user_uid =
user_id.ok_or(AppError::NotFound("invalid or expired restore link".into()))?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
@@ -168,20 +271,26 @@ impl UserService {
.map_err(|_| AppError::TxnError)?;
for statement in [
"DELETE FROM user_personal_access_token WHERE user_id = $1",
"DELETE FROM user_security_log WHERE user_id = $1",
"DELETE FROM user_session WHERE user_id = $1",
"DELETE FROM user_device WHERE user_id = $1",
"DELETE FROM user_oauth WHERE user_id = $1",
"DELETE FROM user_ssh_key WHERE user_id = $1",
"DELETE FROM user_gpg_key WHERE user_id = $1",
"DELETE FROM user_2fa WHERE user_id = $1",
"DELETE FROM user_notify_setting WHERE user_id = $1",
"DELETE FROM user_appearance WHERE user_id = $1",
"DELETE FROM user_profile WHERE user_id = $1",
"DELETE FROM user_mail WHERE user_id = $1",
"DELETE FROM workspace_member WHERE user_id = $1",
"DELETE FROM repo_member WHERE user_id = $1",
"UPDATE user_personal_access_token SET revoked_at = NULL WHERE user_id = $1 AND revoked_at IS NOT NULL",
"UPDATE user_session SET revoked_at = NULL WHERE user_id = $1 AND revoked_at IS NOT NULL",
"UPDATE user_ssh_key SET revoked_at = NULL WHERE user_id = $1 AND revoked_at IS NOT NULL",
"UPDATE user_gpg_key SET revoked_at = NULL WHERE user_id = $1 AND revoked_at IS NOT NULL",
"UPDATE workspace_member SET status = 'active' WHERE user_id = $1 AND status = 'deleted'",
"UPDATE repo_member SET status = 'active' WHERE user_id = $1 AND status = 'deleted'",
"UPDATE user_2fa SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_activity SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_appearance SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_block SET deleted_at = NULL WHERE (user_id = $1 OR blocked_user_id = $1) AND deleted_at IS NOT NULL",
"UPDATE user_device SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_follow SET deleted_at = NULL WHERE (user_id = $1 OR following_user_id = $1) AND deleted_at IS NOT NULL",
"UPDATE user_mail SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_notify_setting SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_oauth SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_password SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_password_reset SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_presence SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_profile SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
"UPDATE user_security_log SET deleted_at = NULL WHERE user_id = $1 AND deleted_at IS NOT NULL",
] {
sqlx::query(statement)
.bind(user_uid)
@@ -191,7 +300,9 @@ impl UserService {
}
let result = sqlx::query(
"UPDATE \"user\" SET deleted_at = $1, is_active = false, status = 'deleted', updated_at = $1 WHERE id = $2 AND deleted_at IS NULL",
"UPDATE \"user\" SET deleted_at = NULL, is_active = true, status = 'active', \
restore_token_hash = NULL, restore_token_expires_at = NULL, updated_at = $1 \
WHERE id = $2 AND deleted_at IS NOT NULL",
)
.bind(now)
.bind(user_uid)
@@ -199,14 +310,53 @@ impl UserService {
.await
.map_err(AppError::Database)?;
if result.rows_affected() == 0 {
return Err(AppError::UserNotFound);
return Err(AppError::NotFound("user not found".into()));
}
txn.commit().await.map_err(|_| AppError::TxnError)?;
ctx.clear();
Ok(())
}
async fn send_restore_email(&self, email: &str, token: &str) -> Result<(), AppError> {
let app_url = self
.ctx
.config
.get_env::<String>("APP_URL")
.ok()
.flatten()
.unwrap_or_else(|| "http://localhost:8000".to_string());
let base = app_url.trim_end_matches('/');
let restore_url = format!("{}/account/restore?token={}", base, 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.to_string(),
name: String::new(),
}],
subject: "Account Deletion - Restore Link".into(),
text_body: format!(
"Your account has been marked for deletion.\n\n\
If you did not request this, you can restore your account within 30 days \
by visiting the following link:\n\n\
{}\n\n\
This link expires in 30 days. After that, your data will be retained but \
the restore link will no longer work.",
restore_url,
),
..Default::default()
}))
.await
.map(|_| ())
.map_err(|e| {
tracing::warn!(?e, "failed to send restore email");
AppError::InternalServerError(e.to_string())
})
}
async fn ensure_username_available(
&self,
username: &str,
+11 -3
View File
@@ -85,9 +85,17 @@ impl UserService {
.execute(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
self.find_user_appearance(user_uid)
.await?
.ok_or(AppError::UserNotFound)
// Read from writer to avoid replication lag
sqlx::query_as::<_, UserAppearance>(
"SELECT user_id, theme, color_scheme, density, font_size, editor_theme, \
markdown_preview, reduced_motion, created_at, updated_at \
FROM user_appearance WHERE user_id = $1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.writer())
.await
.map_err(AppError::Database)?
.ok_or(AppError::UserNotFound)
}
async fn find_user_appearance(
+22 -4
View File
@@ -26,14 +26,23 @@ pub struct AddGpgKeyParams {
}
impl UserService {
pub async fn user_ssh_keys(&self, ctx: &Session) -> Result<Vec<UserSshKey>, AppError> {
pub async fn user_ssh_keys(
&self,
ctx: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<UserSshKey>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let limit = limit.clamp(1, 100);
let offset = offset.max(0);
sqlx::query_as::<_, UserSshKey>(
"SELECT id, user_id, title, public_key, fingerprint_sha256, key_type, last_used_at, \
expires_at, revoked_at, created_at, updated_at FROM user_ssh_key \
WHERE user_id = $1 AND revoked_at IS NULL ORDER BY created_at DESC",
WHERE user_id = $1 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
@@ -98,14 +107,23 @@ impl UserService {
ensure_affected(result.rows_affected(), "key not found")
}
pub async fn user_gpg_keys(&self, ctx: &Session) -> Result<Vec<UserGpgKey>, AppError> {
pub async fn user_gpg_keys(
&self,
ctx: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<UserGpgKey>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let limit = limit.clamp(1, 100);
let offset = offset.max(0);
sqlx::query_as::<_, UserGpgKey>(
"SELECT id, user_id, key_id, public_key, fingerprint, primary_email, expires_at, \
verified_at, revoked_at, created_at, updated_at FROM user_gpg_key \
WHERE user_id = $1 AND revoked_at IS NULL ORDER BY created_at DESC",
WHERE user_id = $1 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
+1
View File
@@ -4,4 +4,5 @@ pub mod keys;
pub mod notify;
pub mod profile;
pub mod security;
pub mod social;
pub mod util;
+11 -3
View File
@@ -100,9 +100,17 @@ impl UserService {
.execute(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
self.find_user_notify_setting(user_uid)
.await?
.ok_or(AppError::UserNotFound)
// Read from writer to avoid replication lag
sqlx::query_as::<_, UserNotifySetting>(
"SELECT user_id, email_notifications, web_notifications, mention_notifications, \
review_notifications, security_notifications, marketing_emails, digest_frequency, \
created_at, updated_at FROM user_notify_setting WHERE user_id = $1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.writer())
.await
.map_err(AppError::Database)?
.ok_or(AppError::UserNotFound)
}
async fn find_user_notify_setting(
+11 -3
View File
@@ -68,9 +68,17 @@ impl UserService {
.execute(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
self.find_user_profile(user_uid)
.await?
.ok_or(AppError::UserNotFound)
// Read from writer to avoid replication lag
sqlx::query_as::<_, UserProfile>(
"SELECT user_id, full_name, company, location, website_url, twitter_username, \
timezone, language, profile_readme, created_at, updated_at \
FROM user_profile WHERE user_id = $1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.writer())
.await
.map_err(AppError::Database)?
.ok_or(AppError::UserNotFound)
}
async fn find_user_profile(
+138 -16
View File
@@ -1,4 +1,5 @@
use chrono::{DateTime, Utc};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -8,7 +9,7 @@ use crate::models::users::{UserDevice, UserSecurityLog};
use crate::service::UserService;
use crate::session::Session;
use super::util::ensure_affected;
use super::util::{ensure_affected, sha256_hex};
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct UserSessionInfo {
@@ -81,14 +82,23 @@ struct UserPersonalAccessTokenRow {
}
impl UserService {
pub async fn user_devices(&self, ctx: &Session) -> Result<Vec<UserDevice>, AppError> {
pub async fn user_devices(
&self,
ctx: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<UserDevice>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let limit = limit.clamp(1, 100);
let offset = offset.max(0);
sqlx::query_as::<_, UserDevice>(
"SELECT id, user_id, device_name, device_type, fingerprint, ip_address, user_agent, \
trusted, last_seen_at, created_at, updated_at FROM user_device \
WHERE user_id = $1 ORDER BY last_seen_at DESC NULLS LAST, created_at DESC",
WHERE user_id = $1 ORDER BY last_seen_at DESC NULLS LAST, created_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
@@ -137,27 +147,63 @@ impl UserService {
session_uid: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let result = sqlx::query(
"UPDATE user_session SET revoked_at = $1 \
WHERE id = $2 AND user_id = $3 AND revoked_at IS NULL",
// Use transaction with SELECT FOR UPDATE to prevent race conditions
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
let session = sqlx::query(
"SELECT id FROM user_session WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL FOR UPDATE",
)
.bind(chrono::Utc::now())
.bind(session_uid)
.bind(user_uid)
.execute(self.ctx.db.writer())
.fetch_optional(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "session not found")
if session.is_none() {
return Err(AppError::NotFound("session not found".into()));
}
sqlx::query("UPDATE user_session SET revoked_at = $1 WHERE id = $2 AND user_id = $3")
.bind(chrono::Utc::now())
.bind(session_uid)
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
// Also try to delete from Redis if this is a cookie session
// The session key might be stored as the session id in Redis
let _ = self.ctx.cache.delete(&session_uid.to_string()).await;
Ok(())
}
pub async fn user_oauth_accounts(&self, ctx: &Session) -> Result<Vec<UserOAuthInfo>, AppError> {
pub async fn user_oauth_accounts(
&self,
ctx: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<UserOAuthInfo>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let limit = limit.clamp(1, 100);
let offset = offset.max(0);
let rows = sqlx::query_as::<_, UserOAuthRow>(
"SELECT id, provider, provider_user_id, provider_username, provider_email, \
token_expires_at, linked_at, last_used_at FROM user_oauth \
WHERE user_id = $1 ORDER BY linked_at DESC",
WHERE user_id = $1 ORDER BY linked_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
@@ -167,17 +213,27 @@ impl UserService {
pub async fn user_unlink_oauth(&self, ctx: &Session, oauth_uid: Uuid) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
// Use transaction with SELECT FOR UPDATE to prevent race condition
// where concurrent unlink requests could remove the last login method
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
let has_password: bool =
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM user_password WHERE user_id = $1)")
.bind(user_uid)
.fetch_one(self.ctx.db.reader())
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
let oauth_count: i64 =
sqlx::query_scalar("SELECT COUNT(*) FROM user_oauth WHERE user_id = $1")
sqlx::query_scalar("SELECT COUNT(*) FROM user_oauth WHERE user_id = $1 FOR UPDATE")
.bind(user_uid)
.fetch_one(self.ctx.db.reader())
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
@@ -190,10 +246,16 @@ impl UserService {
let result = sqlx::query("DELETE FROM user_oauth WHERE id = $1 AND user_id = $2")
.bind(oauth_uid)
.bind(user_uid)
.execute(self.ctx.db.writer())
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "oauth account not found")
if result.rows_affected() == 0 {
return Err(AppError::NotFound("oauth account not found".into()));
}
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(())
}
pub async fn user_security_logs(
@@ -284,6 +346,66 @@ impl UserService {
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "token not found")
}
pub async fn user_create_personal_access_token(
&self,
ctx: &Session,
params: CreatePersonalAccessTokenParams,
) -> Result<CreatePersonalAccessTokenResponse, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let mut raw_bytes = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut raw_bytes);
let raw_token = raw_bytes
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>();
let token_hash = sha256_hex(raw_token.as_bytes());
let id = Uuid::now_v7();
let now = chrono::Utc::now();
sqlx::query(
"INSERT INTO user_personal_access_token (id, user_id, name, token_hash, scopes, expires_at, created_at, updated_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $7)",
)
.bind(id)
.bind(user_uid)
.bind(&params.name)
.bind(&token_hash)
.bind(&params.scopes)
.bind(params.expires_at)
.bind(now)
.execute(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
Ok(CreatePersonalAccessTokenResponse {
id,
name: params.name,
scopes: params.scopes,
token: raw_token,
expires_at: params.expires_at,
created_at: now,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct CreatePersonalAccessTokenParams {
pub name: String,
pub scopes: Vec<Scope>,
pub expires_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct CreatePersonalAccessTokenResponse {
pub id: Uuid,
pub name: String,
pub scopes: Vec<Scope>,
pub token: String,
pub expires_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
impl From<UserSessionRow> for UserSessionInfo {
+226
View File
@@ -0,0 +1,226 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::{DeviceType, PresenceStatus};
use crate::models::users::{UserBlock, UserFollow, UserPresence};
use crate::service::UserService;
use crate::session::Session;
use super::util::ensure_affected;
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct UpdatePresenceParams {
pub status: PresenceStatus,
pub custom_status_text: Option<String>,
pub custom_status_emoji: Option<String>,
pub device_type: Option<DeviceType>,
pub ip_address: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
struct UserPresenceRow {
id: Uuid,
user_id: Uuid,
status: PresenceStatus,
custom_status_text: Option<String>,
custom_status_emoji: Option<String>,
device_type: Option<DeviceType>,
ip_address: Option<String>,
last_active_at: DateTime<Utc>,
last_seen_at: Option<DateTime<Utc>>,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl From<UserPresenceRow> for UserPresence {
fn from(row: UserPresenceRow) -> Self {
Self {
id: row.id,
user_id: row.user_id,
status: row.status,
custom_status_text: row.custom_status_text,
custom_status_emoji: row.custom_status_emoji,
device_type: row.device_type,
ip_address: row.ip_address,
last_active_at: row.last_active_at,
last_seen_at: row.last_seen_at,
created_at: row.created_at,
updated_at: row.updated_at,
}
}
}
impl UserService {
pub async fn user_presence_get(&self, session: &Session) -> Result<UserPresence, AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
let row = sqlx::query_as::<_, UserPresenceRow>(
"SELECT id, user_id, status, custom_status_text, custom_status_emoji, device_type, ip_address, \
last_active_at, last_seen_at, created_at, updated_at \
FROM user_presence WHERE user_id = $1",
)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
row.map(Into::into)
.ok_or_else(|| AppError::NotFound("presence not found".into()))
}
pub async fn user_presence_update(
&self,
session: &Session,
params: UpdatePresenceParams,
) -> Result<UserPresence, AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
let id = Uuid::now_v7();
let now = chrono::Utc::now();
let row = sqlx::query_as::<_, UserPresenceRow>(
"INSERT INTO user_presence (id, user_id, status, custom_status_text, custom_status_emoji, \
device_type, ip_address, last_active_at, last_seen_at, created_at, updated_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULL, $9, $9) \
ON CONFLICT (user_id) DO UPDATE SET \
status = $3, custom_status_text = $4, custom_status_emoji = $5, \
device_type = $6, ip_address = $7, last_active_at = $8, updated_at = $9 \
RETURNING id, user_id, status, custom_status_text, custom_status_emoji, device_type, ip_address, \
last_active_at, last_seen_at, created_at, updated_at",
)
.bind(id)
.bind(user_uid)
.bind(&params.status)
.bind(&params.custom_status_text)
.bind(&params.custom_status_emoji)
.bind(&params.device_type)
.bind(&params.ip_address)
.bind(now)
.bind(now)
.fetch_one(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
Ok(row.into())
}
pub async fn user_blocks_list(
&self,
session: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<UserBlock>, AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
let limit = limit.clamp(1, 100);
let offset = offset.max(0);
sqlx::query_as::<_, UserBlock>(
"SELECT blocker_id, blocked_id, reason, created_at \
FROM user_block WHERE blocker_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
}
pub async fn user_block_create(
&self,
session: &Session,
target_user_id: Uuid,
reason: Option<String>,
) -> Result<UserBlock, AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
if user_uid == target_user_id {
return Err(AppError::BadRequest("cannot block yourself".into()));
}
let now = chrono::Utc::now();
sqlx::query_as::<_, UserBlock>(
"INSERT INTO user_block (blocker_id, blocked_id, reason, created_at) \
VALUES ($1, $2, $3, $4) \
RETURNING blocker_id, blocked_id, reason, created_at",
)
.bind(user_uid)
.bind(target_user_id)
.bind(&reason)
.bind(now)
.fetch_one(self.ctx.db.writer())
.await
.map_err(AppError::Database)
}
pub async fn user_block_delete(
&self,
session: &Session,
target_user_id: Uuid,
) -> Result<(), AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
let result =
sqlx::query("DELETE FROM user_block WHERE blocker_id = $1 AND blocked_id = $2")
.bind(user_uid)
.bind(target_user_id)
.execute(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "block not found")
}
pub async fn user_follows_list(
&self,
session: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<UserFollow>, AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
let limit = limit.clamp(1, 100);
let offset = offset.max(0);
sqlx::query_as::<_, UserFollow>(
"SELECT follower_id, following_id, created_at \
FROM user_follow WHERE follower_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
}
pub async fn user_follow_create(
&self,
session: &Session,
target_user_id: Uuid,
) -> Result<UserFollow, AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
if user_uid == target_user_id {
return Err(AppError::BadRequest("cannot follow yourself".into()));
}
let now = chrono::Utc::now();
sqlx::query_as::<_, UserFollow>(
"INSERT INTO user_follow (follower_id, following_id, created_at) \
VALUES ($1, $2, $3) \
RETURNING follower_id, following_id, created_at",
)
.bind(user_uid)
.bind(target_user_id)
.bind(now)
.fetch_one(self.ctx.db.writer())
.await
.map_err(AppError::Database)
}
pub async fn user_follow_delete(
&self,
session: &Session,
target_user_id: Uuid,
) -> Result<(), AppError> {
let user_uid = session.user().ok_or(AppError::Unauthorized)?;
let result =
sqlx::query("DELETE FROM user_follow WHERE follower_id = $1 AND following_id = $2")
.bind(user_uid)
.bind(target_user_id)
.execute(self.ctx.db.writer())
.await
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "follow not found")
}
}