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:
+138
-16
@@ -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(¶ms.name)
|
||||
.bind(&token_hash)
|
||||
.bind(¶ms.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 {
|
||||
|
||||
Reference in New Issue
Block a user