Forum: a service of its own and the /forum pages
services/forum (axum, port 8083) on the same database and login, in the forum schema (migration 0038, which also adds the moderator role): nicknames, profiles with shared signs, topics, threads with listening or advice intent, two-level replies, read marks and followed threads, reactions as ratings with points and ranks, newcomer limits (lifted by a purchase), moderation with reasons, bans and a log. Integration tests run in CI. The frontend's /forum pages (light by default, dark on request, phone first with a desktop layout) are switched on by FORUM_URL; the /api/v1 proxy sends /api/v1/forum/* to the forum service. Concept and status: docs/kozosseg.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
//! Who is asking: the backend's session (cookie or Bearer token) and the
|
||||
//! member behind it. Reading needs no login; writing needs a nickname.
|
||||
//! Every request of a member also keeps the online dot fresh.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use db::{Role, User};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::rank::Rank;
|
||||
|
||||
pub const SESSION_COOKIE: &str = "sf_session";
|
||||
|
||||
/// How long a member counts as online after the last request.
|
||||
pub const ONLINE_MINUTES: i64 = 5;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct Member {
|
||||
pub user_id: Uuid,
|
||||
pub nickname: String,
|
||||
pub avatar: String,
|
||||
pub bio: String,
|
||||
pub chart_share: String,
|
||||
pub invisible: bool,
|
||||
pub points: i32,
|
||||
pub post_count: i32,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub nickname_changed_at: OffsetDateTime,
|
||||
pub banned_until: Option<OffsetDateTime>,
|
||||
pub ban_reason: Option<String>,
|
||||
}
|
||||
|
||||
pub const MEMBER_COLUMNS: &str = "user_id, nickname, avatar, bio, chart_share, invisible, points, post_count, \
|
||||
created_at, nickname_changed_at, banned_until, ban_reason";
|
||||
|
||||
impl Member {
|
||||
pub fn rank(&self, now: OffsetDateTime) -> Rank {
|
||||
Rank::of(self.points, self.created_at, now)
|
||||
}
|
||||
|
||||
pub fn banned(&self, now: OffsetDateTime) -> bool {
|
||||
self.banned_until.is_some_and(|until| until > now)
|
||||
}
|
||||
}
|
||||
|
||||
/// The visitor: maybe logged in, maybe a member (has chosen a nickname).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Viewer {
|
||||
pub user: Option<User>,
|
||||
pub member: Option<Member>,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
pub fn user_id(&self) -> Option<Uuid> {
|
||||
self.user.as_ref().map(|u| u.id)
|
||||
}
|
||||
|
||||
pub fn logged_in(&self) -> bool {
|
||||
self.user.is_some()
|
||||
}
|
||||
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.user.as_ref().is_some_and(|u| u.has_role(Role::Admin))
|
||||
}
|
||||
|
||||
/// A moderator or an admin.
|
||||
pub fn is_moderator(&self) -> bool {
|
||||
self.user.as_ref().is_some_and(|u| u.has_role(Role::Moderator) || u.has_role(Role::Admin))
|
||||
}
|
||||
|
||||
pub fn require_user(&self) -> Result<&User, ApiError> {
|
||||
self.user.as_ref().ok_or(ApiError::Unauthorized)
|
||||
}
|
||||
|
||||
pub fn require_member(&self) -> Result<&Member, ApiError> {
|
||||
self.require_user()?;
|
||||
self.member.as_ref().ok_or(ApiError::NicknameRequired)
|
||||
}
|
||||
|
||||
/// A member who may write (not banned).
|
||||
pub fn require_writer(&self) -> Result<&Member, ApiError> {
|
||||
let member = self.require_member()?;
|
||||
if member.banned(OffsetDateTime::now_utc()) {
|
||||
let reason = member.ban_reason.as_deref().map(|r| format!(" Indok: {r}")).unwrap_or_default();
|
||||
return Err(ApiError::Banned(format!("Most nem írhatsz a fórumba.{reason}")));
|
||||
}
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub fn require_moderator(&self) -> Result<&User, ApiError> {
|
||||
let user = self.require_user()?;
|
||||
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
|
||||
}
|
||||
}
|
||||
|
||||
fn session_token(parts: &Parts) -> Option<String> {
|
||||
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
|
||||
&& let Some(token) = value.strip_prefix("Bearer ")
|
||||
{
|
||||
return Some(token.trim().to_string());
|
||||
}
|
||||
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
|
||||
}
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
|
||||
let member = load_member(&state.db, user.id).await?;
|
||||
if member.is_some() {
|
||||
// At most once a minute per member: the online dot.
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET last_seen_at = now() \
|
||||
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
|
||||
)
|
||||
.bind(user.id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
}
|
||||
Ok(Viewer { user: Some(user), member })
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_member(db: &sqlx::PgPool, user_id: Uuid) -> Result<Option<Member>, sqlx::Error> {
|
||||
sqlx::query_as(&format!("SELECT {MEMBER_COLUMNS} FROM forum.members WHERE user_id = $1"))
|
||||
.bind(user_id)
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
}
|
||||
Reference in New Issue
Block a user