201 lines
6.8 KiB
Rust
201 lines
6.8 KiB
Rust
//! Moderation: bans and the log of every moderation step (who, what, why;
|
|||
|
|
//! a person or, later, the AI). Removing posts and threads is in their modules.
|
||
|
|
|
||
|
|
use axum::Json;
|
||
|
|
use axum::extract::{Path, State};
|
||
|
|
use axum::http::StatusCode;
|
||
|
|
use axum_extra::extract::WithRejection;
|
||
|
|
use serde::Deserialize;
|
||
|
|
use serde_json::{Value, json};
|
||
|
|
use time::OffsetDateTime;
|
||
|
|
use uuid::Uuid;
|
||
|
|
|
||
|
|
use super::{Body, St, rfc3339};
|
||
|
|
use crate::auth::Viewer;
|
||
|
|
use crate::error::{ApiError, ApiResult};
|
||
|
|
use crate::text;
|
||
|
|
|
||
|
|
#[derive(Debug, Clone, Copy)]
|
||
|
|
pub enum Action {
|
||
|
|
DeletePost,
|
||
|
|
RestorePost,
|
||
|
|
DeleteThread,
|
||
|
|
RestoreThread,
|
||
|
|
Ban,
|
||
|
|
Unban,
|
||
|
|
Lock,
|
||
|
|
Unlock,
|
||
|
|
Pin,
|
||
|
|
Unpin,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Action {
|
||
|
|
fn as_str(self) -> &'static str {
|
||
|
|
match self {
|
||
|
|
Action::DeletePost => "delete_post",
|
||
|
|
Action::RestorePost => "restore_post",
|
||
|
|
Action::DeleteThread => "delete_thread",
|
||
|
|
Action::RestoreThread => "restore_thread",
|
||
|
|
Action::Ban => "ban",
|
||
|
|
Action::Unban => "unban",
|
||
|
|
Action::Lock => "lock",
|
||
|
|
Action::Unlock => "unlock",
|
||
|
|
Action::Pin => "pin",
|
||
|
|
Action::Unpin => "unpin",
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Writes one line of the moderation log (a person's step).
|
||
|
|
#[allow(clippy::too_many_arguments)]
|
||
|
|
pub async fn record(
|
||
|
|
db: impl sqlx::PgExecutor<'_>,
|
||
|
|
actor: Uuid,
|
||
|
|
action: Action,
|
||
|
|
target_user: Option<Uuid>,
|
||
|
|
thread_id: Option<i64>,
|
||
|
|
post_id: Option<i64>,
|
||
|
|
reason: Option<&str>,
|
||
|
|
until: Option<OffsetDateTime>,
|
||
|
|
) -> Result<(), sqlx::Error> {
|
||
|
|
sqlx::query(
|
||
|
|
"INSERT INTO forum.mod_log (actor_id, actor_kind, action, target_user, thread_id, post_id, reason, until) \
|
||
|
|
VALUES ($1, 'human', $2, $3, $4, $5, $6, $7)",
|
||
|
|
)
|
||
|
|
.bind(actor)
|
||
|
|
.bind(action.as_str())
|
||
|
|
.bind(target_user)
|
||
|
|
.bind(thread_id)
|
||
|
|
.bind(post_id)
|
||
|
|
.bind(reason)
|
||
|
|
.bind(until)
|
||
|
|
.execute(db)
|
||
|
|
.await?;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A ban for good: the last day of year 9999.
|
||
|
|
fn forever() -> OffsetDateTime {
|
||
|
|
let day = time::Date::from_calendar_date(9999, time::Month::December, 31).expect("valid date");
|
||
|
|
time::PrimitiveDateTime::new(day, time::Time::MIDNIGHT).assume_utc()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The longest temporary ban, in hours (a year); longer is a ban for good.
|
||
|
|
const MAX_BAN_HOURS: i64 = 24 * 365;
|
||
|
|
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
pub struct BanRequest {
|
||
|
|
/// Hours; missing or `null`: for good.
|
||
|
|
#[serde(default)]
|
||
|
|
hours: Option<i64>,
|
||
|
|
#[serde(default)]
|
||
|
|
reason: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The member behind a nickname, and whether they are a moderator or admin.
|
||
|
|
async fn target(db: &sqlx::PgPool, nickname: &str) -> ApiResult<(Uuid, bool)> {
|
||
|
|
let row: Option<(Uuid, Vec<String>)> = sqlx::query_as(
|
||
|
|
"SELECT m.user_id, u.roles FROM forum.members m JOIN users u ON u.id = m.user_id WHERE m.nickname_key = $1",
|
||
|
|
)
|
||
|
|
.bind(text::nickname_key(nickname))
|
||
|
|
.fetch_optional(db)
|
||
|
|
.await?;
|
||
|
|
let (id, roles) = row.ok_or(ApiError::NotFound("member"))?;
|
||
|
|
Ok((id, roles.iter().any(|r| r == "moderator" || r == "admin")))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A moderator bans a member for some hours or for good: they may still
|
||
|
|
/// read, not write. Moderators and admins cannot be banned this way.
|
||
|
|
pub async fn ban(
|
||
|
|
State(state): St,
|
||
|
|
viewer: Viewer,
|
||
|
|
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||
|
|
WithRejection(Json(req), _): Body<BanRequest>,
|
||
|
|
) -> ApiResult<Json<Value>> {
|
||
|
|
let moderator = viewer.require_moderator()?;
|
||
|
|
let (user, protected) = target(&state.db, &nickname).await?;
|
||
|
|
if protected {
|
||
|
|
return Err(ApiError::Forbidden("Moderátort vagy admint nem tilthatsz ki.".into()));
|
||
|
|
}
|
||
|
|
let reason = text::reason(req.reason.as_deref().unwrap_or(""))?;
|
||
|
|
let until = match req.hours {
|
||
|
|
Some(h) if (1..=MAX_BAN_HOURS).contains(&h) => OffsetDateTime::now_utc() + time::Duration::hours(h),
|
||
|
|
Some(_) => return Err(ApiError::bad(format!("Az eltiltás 1 és {MAX_BAN_HOURS} óra között lehet."))),
|
||
|
|
None => forever(),
|
||
|
|
};
|
||
|
|
let mut tx = state.db.begin().await?;
|
||
|
|
sqlx::query("UPDATE forum.members SET banned_until = $2, ban_reason = $3 WHERE user_id = $1")
|
||
|
|
.bind(user)
|
||
|
|
.bind(until)
|
||
|
|
.bind(&reason)
|
||
|
|
.execute(&mut *tx)
|
||
|
|
.await?;
|
||
|
|
record(&mut *tx, moderator.id, Action::Ban, Some(user), None, None, Some(&reason), Some(until)).await?;
|
||
|
|
tx.commit().await?;
|
||
|
|
tracing::info!(moderator = %moderator.id, member = %user, hours = ?req.hours, "member banned");
|
||
|
|
Ok(Json(json!({ "banned_until": if req.hours.is_none() { "infinity".to_string() } else { rfc3339(until) } })))
|
||
|
|
}
|
||
|
|
|
||
|
|
pub async fn unban(
|
||
|
|
State(state): St,
|
||
|
|
viewer: Viewer,
|
||
|
|
WithRejection(Path(nickname), _): WithRejection<Path<String>, ApiError>,
|
||
|
|
) -> ApiResult<StatusCode> {
|
||
|
|
let moderator = viewer.require_moderator()?;
|
||
|
|
let (user, _) = target(&state.db, &nickname).await?;
|
||
|
|
let mut tx = state.db.begin().await?;
|
||
|
|
sqlx::query("UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE user_id = $1")
|
||
|
|
.bind(user)
|
||
|
|
.execute(&mut *tx)
|
||
|
|
.await?;
|
||
|
|
record(&mut *tx, moderator.id, Action::Unban, Some(user), None, None, None, None).await?;
|
||
|
|
tx.commit().await?;
|
||
|
|
Ok(StatusCode::NO_CONTENT)
|
||
|
|
}
|
||
|
|
|
||
|
|
#[derive(sqlx::FromRow)]
|
||
|
|
struct LogRow {
|
||
|
|
id: i64,
|
||
|
|
actor: Option<String>,
|
||
|
|
actor_kind: String,
|
||
|
|
action: String,
|
||
|
|
target: Option<String>,
|
||
|
|
thread_id: Option<i64>,
|
||
|
|
thread_title: Option<String>,
|
||
|
|
post_id: Option<i64>,
|
||
|
|
reason: Option<String>,
|
||
|
|
until: Option<OffsetDateTime>,
|
||
|
|
created_at: OffsetDateTime,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The latest moderation steps, for moderators.
|
||
|
|
pub async fn log(State(state): St, viewer: Viewer) -> ApiResult<Json<Value>> {
|
||
|
|
viewer.require_moderator()?;
|
||
|
|
let rows: Vec<LogRow> = sqlx::query_as(
|
||
|
|
"SELECT l.id, COALESCE(am.nickname, au.display_name, 'admin') AS actor, l.actor_kind, l.action, \
|
||
|
|
tm.nickname AS target, l.thread_id, th.title AS thread_title, l.post_id, l.reason, l.until, l.created_at \
|
||
|
|
FROM forum.mod_log l \
|
||
|
|
LEFT JOIN forum.members am ON am.user_id = l.actor_id \
|
||
|
|
LEFT JOIN users au ON au.id = l.actor_id \
|
||
|
|
LEFT JOIN forum.members tm ON tm.user_id = l.target_user \
|
||
|
|
LEFT JOIN forum.threads th ON th.id = l.thread_id \
|
||
|
|
ORDER BY l.id DESC LIMIT 200",
|
||
|
|
)
|
||
|
|
.fetch_all(&state.db)
|
||
|
|
.await?;
|
||
|
|
Ok(Json(json!({
|
||
|
|
"entries": rows.into_iter().map(|r| json!({
|
||
|
|
"id": r.id,
|
||
|
|
"actor": r.actor,
|
||
|
|
"actor_kind": r.actor_kind,
|
||
|
|
"action": r.action,
|
||
|
|
"target": r.target,
|
||
|
|
"thread": r.thread_id.map(|id| json!({ "id": id, "title": r.thread_title })),
|
||
|
|
"post_id": r.post_id,
|
||
|
|
"reason": r.reason,
|
||
|
|
"until": r.until.map(|u| if u.year() >= 9999 { "infinity".to_string() } else { rfc3339(u) }),
|
||
|
|
"created_at": rfc3339(r.created_at),
|
||
|
|
})).collect::<Vec<_>>(),
|
||
|
|
})))
|
||
|
|
}
|