Files
Oxicloud/src/infrastructure/repositories/pg/user_pg_repository.rs
T

1214 lines
42 KiB
Rust
Raw Normal View History

2026-02-14 01:29:34 +01:00
use futures::future::BoxFuture;
2025-04-10 01:43:25 +02:00
use sqlx::{PgPool, Row};
2025-03-20 09:22:31 +01:00
use std::sync::Arc;
use uuid::Uuid;
2025-03-20 09:22:31 +01:00
use crate::application::ports::auth_ports::UserStoragePort;
use crate::common::errors::DomainError;
use crate::domain::entities::user::{User, UserFlags, UserRole};
2026-02-14 01:29:34 +01:00
use crate::domain::repositories::user_repository::{
StorageStats, UserRepository, UserRepositoryError, UserRepositoryResult,
};
2025-04-09 00:21:20 +02:00
use crate::infrastructure::repositories::pg::transaction_utils::with_transaction;
// Implement From<sqlx::Error> for UserRepositoryError to allow automatic conversions
2025-04-09 00:21:20 +02:00
impl From<sqlx::Error> for UserRepositoryError {
fn from(err: sqlx::Error) -> Self {
UserPgRepository::map_sqlx_error(err)
}
}
2025-03-20 09:22:31 +01:00
pub struct UserPgRepository {
pool: Arc<PgPool>,
}
impl UserPgRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
2026-02-14 01:29:34 +01:00
/// Borrowed access to the connection pool. Exposed so callers can
/// open transactions that span this repo and other repos / hooks
/// (e.g. `AuthApplicationService::delete_user_admin` opening a tx
/// that wraps the lifecycle dispatcher + the DELETE).
pub fn pool(&self) -> &PgPool {
&self.pool
}
// Helper method to map SQL errors to domain errors
2025-04-09 00:21:20 +02:00
pub fn map_sqlx_error(err: sqlx::Error) -> UserRepositoryError {
2025-03-20 09:22:31 +01:00
match err {
2026-02-14 01:29:34 +01:00
sqlx::Error::RowNotFound => UserRepositoryError::NotFound("User not found".to_string()),
2025-03-20 09:22:31 +01:00
sqlx::Error::Database(db_err) => {
if db_err.code().is_some_and(|code| code == "23505") {
// PostgreSQL uniqueness violation code
2026-02-14 01:29:34 +01:00
UserRepositoryError::AlreadyExists("User or email already exists".to_string())
2025-03-20 09:22:31 +01:00
} else {
2026-02-14 01:29:34 +01:00
UserRepositoryError::DatabaseError(format!("Database error: {}", db_err))
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
}
_ => UserRepositoryError::DatabaseError(format!("Database error: {}", err)),
2025-03-20 09:22:31 +01:00
}
}
/// Fetch only the authorization-relevant flags of a user. Not part of
/// the `UserRepository` trait — called directly from
/// `AuthApplicationService::get_user_flags`.
///
/// Deliberately selects three tiny columns instead of the full row:
/// the full-row SELECT includes `image` (a data URI of up to 512 KiB),
/// which per-request middleware guards were paying on every WebDAV /
/// CalDAV / CardDAV request just to read `is_external` or `role`.
pub async fn get_user_flags(&self, id: Uuid) -> UserRepositoryResult<UserFlags> {
let row = sqlx::query(
r#"
SELECT role::text as role_text, is_external, active
FROM auth.users
WHERE id = $1
"#,
)
.bind(id)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
Ok(UserFlags {
role,
is_external: row.get("is_external"),
active: row.get("active"),
})
}
/// Fetch only `(storage_used_bytes, storage_quota_bytes)`. Not part of
/// the `UserRepository` trait — called from `StorageUsageService`.
///
/// Same rationale as [`Self::get_user_flags`]: the full-row SELECT drags
/// `image` (a data URI of up to 512 KiB), `password_hash`,
/// `ui_preferences`, … across the wire, and the quota path runs on every
/// folder PROPFIND and every upload quota check just to read two i64s.
/// Measured in `benches/QUOTA-PATH.md`.
pub async fn get_storage_usage(&self, id: Uuid) -> UserRepositoryResult<(i64, i64)> {
let row = sqlx::query(
r#"
SELECT storage_used_bytes, storage_quota_bytes
FROM auth.users
WHERE id = $1
"#,
)
.bind(id)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok((
row.get("storage_used_bytes"),
row.get("storage_quota_bytes"),
))
}
/// Updates a user's profile image (URL or data URI). Not part of the
/// `UserRepository` trait — called directly from `AuthApplicationService`.
pub async fn update_image(
&self,
user_id: Uuid,
image: Option<String>,
) -> UserRepositoryResult<()> {
sqlx::query(
r#"
UPDATE auth.users
SET image = $2, updated_at = NOW()
WHERE id = $1
"#,
)
.bind(user_id)
.bind(&image)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
/// Shallow-merge a partial UI-preferences patch into
/// `ui_preferences`. The Postgres `||` operator merges top-level
/// keys — `{"a":1,"b":2} || {"b":3,"c":4}` → `{"a":1,"b":3,"c":4}`,
/// which is exactly the semantic PATCH callers want: a partial
/// write only touches the keys it mentions, so a preference set on
/// one device isn't wiped by a partial write from another.
///
/// `jsonb_strip_nulls` removes any key whose incoming value is
/// null, giving callers a documented delete-a-key path (`PATCH
/// {"foo": null}` clears `foo`). Nested nulls inside a value
/// object survive — we only strip at the top level via the merge
/// result.
///
/// Not part of the `UserRepository` trait — called directly from
/// `AuthApplicationService::update_profile`. Bumps `updated_at`
/// so the standard "when did this row change" audits stay useful.
///
/// The CHECK constraints
/// (`users_ui_preferences_is_object` + `_size_cap`) enforce shape
/// and cap at the schema layer; a violating patch surfaces as an
/// sqlx error and returns to the handler as 400.
pub async fn update_ui_preferences(
&self,
user_id: Uuid,
patch: &serde_json::Value,
) -> UserRepositoryResult<()> {
sqlx::query(
r#"
UPDATE auth.users
SET ui_preferences = jsonb_strip_nulls(ui_preferences || $2::jsonb),
updated_at = NOW()
WHERE id = $1
"#,
)
.bind(user_id)
.bind(patch)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
2025-03-20 09:22:31 +01:00
}
impl UserRepository for UserPgRepository {
/// Creates a new user using a transaction
2025-03-20 09:22:31 +01:00
async fn create_user(&self, user: User) -> UserRepositoryResult<User> {
// Create a copy of the user for the closure
2025-04-09 00:21:20 +02:00
let user_clone = user.clone();
2026-02-14 01:29:34 +01:00
with_transaction(&self.pool, "create_user", |tx| {
// We need to move the closure into a BoxFuture to return inside
// the with_transaction call
Box::pin(async move {
// Use getters to extract the values
// Convert user.role() to string to pass it as plain text
let role_str = user_clone.role().to_string();
// Modify the SQL to do an explicit cast to the auth.userrole type
// `image` is included here (was missing pre-fix); without
// it a JIT-provisioned OIDC user landed in the row with
// a NULL profile picture even when the IdP's `picture`
// claim was non-empty. `update_user` already wrote the
// column so existing-user re-logins worked, but the
// first-time INSERT silently dropped it — surfaced by
// tests/oidc/oidc.hurl Step 6 asserting on `$.image`.
2026-02-14 01:29:34 +01:00
let _result = sqlx::query(
r#"
2025-04-09 00:21:20 +02:00
INSERT INTO auth.users (
id, username, email, password_hash, role,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at,
preferred_locale, notify_on_share, ui_preferences
2025-04-09 00:21:20 +02:00
) VALUES (
$1, $2, $3, $4, $5::auth.userrole, $6, $7, $8, $9, $10, $11,
$12, $13, $14, $15, $16, $17, $18, $19, $20, $21
2025-04-09 00:21:20 +02:00
)
RETURNING *
2026-02-14 01:29:34 +01:00
"#,
)
.bind(user_clone.id())
.bind(user_clone.username())
.bind(user_clone.email())
.bind(user_clone.password_hash())
.bind(&role_str) // Convert to string but with explicit cast in SQL
.bind(user_clone.storage_quota_bytes())
.bind(user_clone.storage_used_bytes())
.bind(user_clone.created_at())
.bind(user_clone.updated_at())
.bind(user_clone.last_login_at())
.bind(user_clone.is_active())
.bind(user_clone.oidc_provider())
.bind(user_clone.oidc_subject())
.bind(user_clone.image())
.bind(user_clone.is_external())
.bind(user_clone.given_name())
.bind(user_clone.family_name())
.bind(user_clone.email_verified_at())
.bind(user_clone.preferred_locale())
.bind(user_clone.notify_on_share())
// ui_preferences bind: always a JSON object. `User::new`
// initialises the bag to `{}`; ownership stays with the
// repo for shallow-merge writes via `update_ui_preferences`.
.bind(user_clone.ui_preferences())
2026-02-14 01:29:34 +01:00
.execute(&mut **tx)
.await
.map_err(Self::map_sqlx_error)?;
// We could perform additional operations here,
// such as configuring permissions, roles, etc.
Ok(user_clone)
}) as BoxFuture<'_, UserRepositoryResult<User>>
})
.await?;
Ok(user) // Return the original user for simplicity
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
/// Gets a user by ID
async fn get_user_by_id(&self, id: Uuid) -> UserRepositoryResult<User> {
2025-03-20 09:22:31 +01:00
let row = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
2025-03-20 09:22:31 +01:00
FROM auth.users
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(id)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
// Convert role string to UserRole enum
2025-03-28 08:09:18 +01:00
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
2026-02-14 01:29:34 +01:00
Ok(User::from_data_full(
2025-03-20 09:22:31 +01:00
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
2025-03-20 09:22:31 +01:00
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
2025-03-20 09:22:31 +01:00
))
}
2026-02-14 01:29:34 +01:00
/// Gets a user by username
2025-03-20 09:22:31 +01:00
async fn get_user_by_username(&self, username: &str) -> UserRepositoryResult<User> {
let row = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
2025-03-20 09:22:31 +01:00
FROM auth.users
WHERE username = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(username)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
// Convert role string to UserRole enum
2025-03-28 08:09:18 +01:00
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
2026-02-14 01:29:34 +01:00
Ok(User::from_data_full(
2025-03-20 09:22:31 +01:00
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
2025-03-20 09:22:31 +01:00
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
2025-03-20 09:22:31 +01:00
))
}
2026-02-14 01:29:34 +01:00
/// Gets a user by email
2025-03-20 09:22:31 +01:00
async fn get_user_by_email(&self, email: &str) -> UserRepositoryResult<User> {
let row = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
2025-03-20 09:22:31 +01:00
FROM auth.users
WHERE email = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(email)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
// Convert role string to UserRole enum
2025-03-28 08:09:18 +01:00
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
2026-02-14 01:29:34 +01:00
Ok(User::from_data_full(
2025-03-20 09:22:31 +01:00
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
2025-03-20 09:22:31 +01:00
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
2025-03-20 09:22:31 +01:00
))
}
2026-02-14 01:29:34 +01:00
/// Batch loads users by id in one query (avoids N+1 for group-
/// recipient expansion). Missing ids are silently skipped — the
/// caller treats absent rows as "no such recipient", same as
/// `get_user_by_id` returning `NotFound` for a single lookup.
///
/// Notification-recipient projection: the up-to-512 KiB avatar `image`
/// and the `ui_preferences` JSONB are NOT hydrated (both come back as
/// `None`/`Null`) — the sole caller
/// (`RecipientNotificationService`) reads only the email/eligibility
/// fields, and a group fan-out of M members otherwise detoasted +
/// shipped + parsed M avatars purely to discard them (the ROUND12 §Q1
/// avatar-narrowing pattern; benches/ROUND13.md §Q1). If a future
/// caller needs the avatar, add a wide sibling rather than widening
/// this one back.
async fn get_users_by_ids(&self, ids: Vec<Uuid>) -> UserRepositoryResult<Vec<User>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let rows = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share
FROM auth.users
WHERE id = ANY($1)
"#,
)
.bind(&ids)
.fetch_all(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(rows
.into_iter()
.map(|row| {
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
User::from_data_full(
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
None, // image — not projected (notification-recipient path)
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
serde_json::Value::Null, // ui_preferences — not projected
)
})
.collect())
}
/// Updates an existing user using a transaction
2025-03-20 09:22:31 +01:00
async fn update_user(&self, user: User) -> UserRepositoryResult<User> {
// Create a copy of the user for the closure
2025-04-09 00:21:20 +02:00
let user_clone = user.clone();
2026-02-14 01:29:34 +01:00
with_transaction(&self.pool, "update_user", |tx| {
Box::pin(async move {
// Update the user
sqlx::query(
r#"
2025-04-09 00:21:20 +02:00
UPDATE auth.users
SET
2025-04-09 00:21:20 +02:00
username = $2,
email = $3,
password_hash = $4,
role = $5::auth.userrole,
storage_quota_bytes = $6,
storage_used_bytes = $7,
updated_at = $8,
last_login_at = $9,
active = $10,
image = $11,
given_name = $12,
family_name = $13,
email_verified_at = $14,
preferred_locale = $15,
2026-07-14 04:12:48 +02:00
notify_on_share = $16,
-- Include `is_external` so the external →
-- internal upgrade path
-- (`AuthApplicationService::upgrade_to_internal`)
-- can flip this flag. Previously omitted
-- because no code path mutated it after
-- creation. The DB CHECK
-- `users_external_no_storage`
-- (`is_external=false OR quota=0`) is
-- satisfied by the upgrade because it
-- writes both fields in the same UPDATE:
-- `is_external=false, quota>0`.
is_external = $17
2025-04-09 00:21:20 +02:00
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
)
.bind(user_clone.id())
.bind(user_clone.username())
.bind(user_clone.email())
.bind(user_clone.password_hash())
.bind(user_clone.role().to_string())
.bind(user_clone.storage_quota_bytes())
.bind(user_clone.storage_used_bytes())
.bind(user_clone.updated_at())
.bind(user_clone.last_login_at())
.bind(user_clone.is_active())
.bind(user_clone.image())
.bind(user_clone.given_name())
.bind(user_clone.family_name())
.bind(user_clone.email_verified_at())
.bind(user_clone.preferred_locale())
.bind(user_clone.notify_on_share())
2026-07-14 04:12:48 +02:00
.bind(user_clone.is_external())
2026-02-14 01:29:34 +01:00
.execute(&mut **tx)
.await
.map_err(Self::map_sqlx_error)?;
// We could perform additional operations here inside
// the same transaction, such as updating permissions, etc.
Ok(user_clone)
}) as BoxFuture<'_, UserRepositoryResult<User>>
})
.await?;
2025-03-20 09:22:31 +01:00
Ok(user)
}
2026-02-14 01:29:34 +01:00
/// Updates only the storage usage of a user.
///
/// The `IS DISTINCT FROM` guard makes this a no-op when the value is
/// unchanged — which is the common case for the periodic reconciliation
/// sweep — so it produces no dead tuple and no WAL when nothing changed.
2026-02-14 01:29:34 +01:00
async fn update_storage_usage(
&self,
user_id: Uuid,
2026-02-14 01:29:34 +01:00
usage_bytes: i64,
) -> UserRepositoryResult<()> {
2025-03-20 09:22:31 +01:00
sqlx::query(
r#"
UPDATE auth.users
SET
2025-03-20 09:22:31 +01:00
storage_used_bytes = $2,
updated_at = NOW()
WHERE id = $1 AND storage_used_bytes IS DISTINCT FROM $2
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(user_id)
.bind(usage_bytes)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
2026-02-14 01:29:34 +01:00
/// Updates the last login date
async fn update_last_login(&self, user_id: Uuid) -> UserRepositoryResult<()> {
2025-03-20 09:22:31 +01:00
sqlx::query(
r#"
UPDATE auth.users
SET
last_login_at = NOW(),
updated_at = NOW()
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(user_id)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
2026-02-14 01:29:34 +01:00
/// Lists users with pagination
async fn list_users(
&self,
limit: i64,
offset: i64,
include_external: bool,
) -> UserRepositoryResult<Vec<User>> {
2025-03-20 09:22:31 +01:00
let rows = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
2025-03-20 09:22:31 +01:00
FROM auth.users
WHERE ($3 OR is_external = FALSE)
2025-03-20 09:22:31 +01:00
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(limit)
.bind(offset)
.bind(include_external)
2025-03-20 09:22:31 +01:00
.fetch_all(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
2026-02-14 01:29:34 +01:00
let users = rows
.into_iter()
2025-03-20 09:22:31 +01:00
.map(|row| {
// Convert role string to UserRole enum for each row
2025-03-28 08:09:18 +01:00
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
2026-02-14 01:29:34 +01:00
User::from_data_full(
2025-03-20 09:22:31 +01:00
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
2025-03-20 09:22:31 +01:00
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
2025-03-20 09:22:31 +01:00
)
})
.collect();
Ok(users)
}
2026-02-14 01:29:34 +01:00
async fn search_users(
&self,
query: &str,
limit: i64,
include_external: bool,
) -> UserRepositoryResult<Vec<User>> {
let pattern = format!("%{}%", query);
let rows = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
FROM auth.users
WHERE (username ILIKE $1 OR email ILIKE $1)
AND ($3 OR is_external = FALSE)
ORDER BY username
LIMIT $2
"#,
)
.bind(&pattern)
.bind(limit)
.bind(include_external)
.fetch_all(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
let users = rows
.into_iter()
.map(|row| {
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
User::from_data_full(
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
)
})
.collect();
Ok(users)
}
/// Activates or deactivates a user
2026-02-14 01:29:34 +01:00
async fn set_user_active_status(
&self,
user_id: Uuid,
2026-02-14 01:29:34 +01:00
active: bool,
) -> UserRepositoryResult<()> {
2025-03-20 09:22:31 +01:00
sqlx::query(
r#"
UPDATE auth.users
SET
active = $2,
updated_at = NOW()
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(user_id)
.bind(active)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
2026-02-14 01:29:34 +01:00
/// Changes a user's password
2026-02-14 01:29:34 +01:00
async fn change_password(
&self,
user_id: Uuid,
2026-02-14 01:29:34 +01:00
password_hash: &str,
) -> UserRepositoryResult<()> {
2025-03-20 09:22:31 +01:00
sqlx::query(
r#"
UPDATE auth.users
SET
password_hash = $2,
updated_at = NOW()
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(user_id)
.bind(password_hash)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
2026-02-14 01:29:34 +01:00
/// Changes a user's role
async fn change_role(&self, user_id: Uuid, role: UserRole) -> UserRepositoryResult<()> {
// Convert the role to string for the binding
let role_str = role.to_string();
2026-02-14 01:29:34 +01:00
2025-03-20 09:22:31 +01:00
sqlx::query(
r#"
UPDATE auth.users
SET
role = $2::auth.userrole,
2025-03-20 09:22:31 +01:00
updated_at = NOW()
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(user_id)
.bind(&role_str)
2025-03-20 09:22:31 +01:00
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
2026-02-14 01:29:34 +01:00
/// Lists users by role
2025-04-12 18:58:21 +02:00
async fn list_users_by_role(&self, role: &str) -> UserRepositoryResult<Vec<User>> {
let rows = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
2025-04-12 18:58:21 +02:00
FROM auth.users
WHERE role::text = $1
ORDER BY created_at DESC
2026-02-14 01:29:34 +01:00
"#,
2025-04-12 18:58:21 +02:00
)
.bind(role)
.fetch_all(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
2026-02-14 01:29:34 +01:00
let users = rows
.into_iter()
2025-04-12 18:58:21 +02:00
.map(|row| {
// Convert role string to UserRole enum for each row
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
2026-02-14 01:29:34 +01:00
User::from_data_full(
2025-04-12 18:58:21 +02:00
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
2025-04-12 18:58:21 +02:00
)
})
.collect();
Ok(users)
}
2026-02-14 01:29:34 +01:00
/// Deletes a user
async fn delete_user(&self, user_id: Uuid) -> UserRepositoryResult<()> {
2025-03-20 09:22:31 +01:00
sqlx::query(
r#"
DELETE FROM auth.users
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
2025-03-20 09:22:31 +01:00
)
.bind(user_id)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
/// Finds a user by OIDC provider + subject pair
2026-02-14 01:29:34 +01:00
async fn get_user_by_oidc_subject(
&self,
provider: &str,
subject: &str,
) -> UserRepositoryResult<User> {
let row = sqlx::query(
r#"
SELECT
id, username, email, password_hash, role::text as role_text,
storage_quota_bytes, storage_used_bytes,
created_at, updated_at, last_login_at, active,
oidc_provider, oidc_subject, image, is_external,
given_name, family_name, email_verified_at, preferred_locale, notify_on_share,
ui_preferences
FROM auth.users
WHERE oidc_provider = $1 AND oidc_subject = $2
2026-02-14 01:29:34 +01:00
"#,
)
.bind(provider)
.bind(subject)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
let role_str: Option<String> = row.try_get("role_text").unwrap_or(None);
let role = match role_str.as_deref() {
Some("admin") => UserRole::Admin,
_ => UserRole::User,
};
Ok(User::from_data_full(
row.get("id"),
row.get("username"),
row.get("email"),
row.get("password_hash"),
role,
row.get("storage_quota_bytes"),
row.get("storage_used_bytes"),
row.get("created_at"),
row.get("updated_at"),
row.get("last_login_at"),
row.get("active"),
row.get("oidc_provider"),
row.get("oidc_subject"),
row.get("image"),
row.get("is_external"),
row.get("given_name"),
row.get("family_name"),
row.get("email_verified_at"),
row.get("preferred_locale"),
row.get("notify_on_share"),
row.get::<serde_json::Value, _>("ui_preferences"),
))
}
/// Updates a user's storage quota
2026-02-14 01:29:34 +01:00
async fn update_storage_quota(
&self,
user_id: Uuid,
2026-02-14 01:29:34 +01:00
quota_bytes: i64,
) -> UserRepositoryResult<()> {
sqlx::query(
r#"
UPDATE auth.users
SET
storage_quota_bytes = $2,
updated_at = NOW()
WHERE id = $1
2026-02-14 01:29:34 +01:00
"#,
)
.bind(user_id)
.bind(quota_bytes)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(())
}
/// Counts the total number of users
async fn count_users(&self) -> UserRepositoryResult<i64> {
2026-02-14 01:29:34 +01:00
let row = sqlx::query("SELECT COUNT(*) as count FROM auth.users")
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
let count: i64 = row.get("count");
Ok(count)
}
/// Gets aggregated storage statistics
async fn get_storage_stats(&self) -> UserRepositoryResult<StorageStats> {
let row = sqlx::query(
r#"
SELECT
COUNT(*) as total_users,
COUNT(*) FILTER (WHERE active = true) as active_users,
COALESCE(SUM(storage_quota_bytes), 0) as total_quota_bytes,
COALESCE(SUM(storage_used_bytes), 0) as total_used_bytes,
COUNT(*) FILTER (WHERE storage_quota_bytes > 0 AND storage_used_bytes > storage_quota_bytes * 0.8) as users_over_80_percent,
COUNT(*) FILTER (WHERE storage_quota_bytes > 0 AND storage_used_bytes > storage_quota_bytes) as users_over_quota
FROM auth.users
"#
)
.fetch_one(&*self.pool)
.await
.map_err(Self::map_sqlx_error)?;
Ok(StorageStats {
total_users: row.get("total_users"),
active_users: row.get("active_users"),
total_quota_bytes: row.get("total_quota_bytes"),
total_used_bytes: row.get("total_used_bytes"),
users_over_80_percent: row.get("users_over_80_percent"),
users_over_quota: row.get("users_over_quota"),
})
}
2025-03-20 09:22:31 +01:00
}
// Storage port implementation for the application layer
2025-03-20 09:22:31 +01:00
impl UserStoragePort for UserPgRepository {
async fn create_user(&self, user: User) -> Result<User, DomainError> {
2026-02-14 01:29:34 +01:00
UserRepository::create_user(self, user)
.await
.map_err(DomainError::from)
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
async fn get_user_by_id(&self, id: Uuid) -> Result<User, DomainError> {
2026-02-14 01:29:34 +01:00
UserRepository::get_user_by_id(self, id)
.await
.map_err(DomainError::from)
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
async fn get_users_by_ids(&self, ids: Vec<Uuid>) -> Result<Vec<User>, DomainError> {
UserRepository::get_users_by_ids(self, ids)
.await
.map_err(DomainError::from)
}
2025-03-20 09:22:31 +01:00
async fn get_user_by_username(&self, username: &str) -> Result<User, DomainError> {
2026-02-14 01:29:34 +01:00
UserRepository::get_user_by_username(self, username)
.await
.map_err(DomainError::from)
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
2025-03-20 09:22:31 +01:00
async fn get_user_by_email(&self, email: &str) -> Result<User, DomainError> {
2026-02-14 01:29:34 +01:00
UserRepository::get_user_by_email(self, email)
.await
.map_err(DomainError::from)
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
2025-03-20 09:22:31 +01:00
async fn update_user(&self, user: User) -> Result<User, DomainError> {
2026-02-14 01:29:34 +01:00
UserRepository::update_user(self, user)
.await
.map_err(DomainError::from)
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
async fn update_storage_usage(
&self,
user_id: Uuid,
2026-02-14 01:29:34 +01:00
usage_bytes: i64,
) -> Result<(), DomainError> {
2025-03-20 09:22:31 +01:00
UserRepository::update_storage_usage(self, user_id, usage_bytes)
.await
.map_err(DomainError::from)
}
2026-02-14 01:29:34 +01:00
async fn list_users(
&self,
limit: i64,
offset: i64,
include_external: bool,
) -> Result<Vec<User>, DomainError> {
UserRepository::list_users(self, limit, offset, include_external)
2026-02-14 01:29:34 +01:00
.await
.map_err(DomainError::from)
2025-03-20 09:22:31 +01:00
}
2026-02-14 01:29:34 +01:00
async fn search_users(
&self,
query: &str,
limit: i64,
include_external: bool,
) -> Result<Vec<User>, DomainError> {
UserRepository::search_users(self, query, limit, include_external)
.await
.map_err(DomainError::from)
}
async fn search_usernames(
&self,
query: &str,
limit: i64,
include_external: bool,
) -> Result<Vec<Option<String>>, DomainError> {
// Same predicate / order / limit as `search_users`, username-only
// projection — the sharee autocomplete path reads nothing else, and
// the wide row drags the avatar `image` per matched user.
let pattern = format!("%{}%", query);
let rows = sqlx::query(
r#"
SELECT username
FROM auth.users
WHERE (username ILIKE $1 OR email ILIKE $1)
AND ($3 OR is_external = FALSE)
ORDER BY username
LIMIT $2
"#,
)
.bind(&pattern)
.bind(limit)
.bind(include_external)
.fetch_all(&*self.pool)
.await
.map_err(Self::map_sqlx_error)
.map_err(DomainError::from)?;
Ok(rows.into_iter().map(|row| row.get("username")).collect())
}
async fn mark_email_verified(&self, user_id: Uuid) -> Result<(), DomainError> {
// SQL twin of `User::mark_email_verified` — stamps once, keeps the
// first timestamp, and touches only the two columns involved.
sqlx::query(
r#"
UPDATE auth.users
SET email_verified_at = NOW(), updated_at = NOW()
WHERE id = $1 AND email_verified_at IS NULL
"#,
)
.bind(user_id)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)
.map_err(DomainError::from)?;
Ok(())
}
async fn sync_oidc_login_profile(
&self,
user_id: Uuid,
image: Option<&str>,
) -> Result<(), DomainError> {
// `IS DISTINCT FROM` guard (the `update_storage_usage` pattern): the
// common repeat-login case — same IdP avatar, already verified —
// writes nothing at all (no dead tuple, no WAL).
sqlx::query(
r#"
UPDATE auth.users
SET image = $2,
email_verified_at = COALESCE(email_verified_at, NOW()),
updated_at = NOW()
WHERE id = $1
AND (image IS DISTINCT FROM $2 OR email_verified_at IS NULL)
"#,
)
.bind(user_id)
.bind(image)
.execute(&*self.pool)
.await
.map_err(Self::map_sqlx_error)
.map_err(DomainError::from)?;
Ok(())
}
2025-04-12 18:58:21 +02:00
async fn list_users_by_role(&self, role: &str) -> Result<Vec<User>, DomainError> {
2026-02-14 01:29:34 +01:00
UserRepository::list_users_by_role(self, role)
.await
.map_err(DomainError::from)
2025-04-12 18:58:21 +02:00
}
2026-02-14 01:29:34 +01:00
async fn delete_user(&self, user_id: Uuid) -> Result<(), DomainError> {
2025-04-12 18:58:21 +02:00
UserRepository::delete_user(self, user_id)
.await
.map_err(DomainError::from)
}
2026-02-14 01:29:34 +01:00
async fn change_password(&self, user_id: Uuid, password_hash: &str) -> Result<(), DomainError> {
2025-03-20 09:22:31 +01:00
UserRepository::change_password(self, user_id, password_hash)
.await
.map_err(DomainError::from)
}
2026-02-14 01:29:34 +01:00
async fn get_user_by_oidc_subject(
&self,
provider: &str,
subject: &str,
) -> Result<User, DomainError> {
UserRepository::get_user_by_oidc_subject(self, provider, subject)
.await
.map_err(DomainError::from)
}
async fn set_user_active_status(&self, user_id: Uuid, active: bool) -> Result<(), DomainError> {
UserRepository::set_user_active_status(self, user_id, active)
.await
.map_err(DomainError::from)
}
async fn change_role(&self, user_id: Uuid, role: &str) -> Result<(), DomainError> {
let user_role = match role {
"admin" => UserRole::Admin,
_ => UserRole::User,
};
UserRepository::change_role(self, user_id, user_role)
.await
.map_err(DomainError::from)
}
2026-02-14 01:29:34 +01:00
async fn update_storage_quota(
&self,
user_id: Uuid,
2026-02-14 01:29:34 +01:00
quota_bytes: i64,
) -> Result<(), DomainError> {
UserRepository::update_storage_quota(self, user_id, quota_bytes)
.await
.map_err(DomainError::from)
}
async fn count_users(&self) -> Result<i64, DomainError> {
UserRepository::count_users(self)
.await
.map_err(DomainError::from)
}
2026-02-14 01:29:34 +01:00
}