add: profile moderation ui

add: pagination ui
This commit is contained in:
trisua 2025-04-01 16:12:13 -04:00
parent d0c1fbcf9a
commit 9a9b72bdbb
14 changed files with 417 additions and 38 deletions

View file

@ -5,6 +5,8 @@ version = "1.0.0"
"general:link.home" = "Home"
"general:link.popular" = "Popular"
"general:link.communities" = "Communities"
"general:link.next" = "Next"
"general:link.previous" = "Previous"
"general:action.save" = "Save"
"general:action.delete" = "Delete"
"general:action.back" = "Back"
@ -30,6 +32,7 @@ version = "1.0.0"
"auth:label.relationship" = "Relationship"
"auth:label.joined_communities" = "Joined communities"
"auth:label.recent_posts" = "Recent posts"
"auth:label.moderation" = "Moderation"
"communities:action.create" = "Create"
"communities:action.select" = "Select"
@ -63,6 +66,7 @@ version = "1.0.0"
"settings:tab.sessions" = "Sessions"
"settings:label.change_password" = "Change password"
"settings:label.current_password" = "Current password"
"settings:label.delete_account" = "Delete account"
"settings:label.new_password" = "New password"
"settings:label.change_username" = "Change username"
"settings:label.new_username" = "New username"

View file

@ -137,7 +137,7 @@
});
};
</script>
{% endif %} {% else %}
{% endif %} {% endif %} {% if is_owner or is_manager %}
<a
href="/community/{{ community.title }}/manage"
class="button primary"

View file

@ -44,6 +44,8 @@
{% for post in feed %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false) }}
{% endfor %}
{{ components::pagination(page=page, items=feed|length) }}
</div>
</div>
</div>

View file

@ -47,8 +47,12 @@
</div>
<div class="card flex flex-col gap-4">
{% for post in replies %} {{ components::post(post=post[0],
owner=post[1], secondary=true, show_community=false) }} {% endfor %}
<!-- prettier-ignore -->
{% for post in replies %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false) }}
{% endfor %}
{{ components::pagination(page=page, items=replies|length) }}
</div>
</div>
</main>

View file

@ -246,4 +246,20 @@ show_community=true) -%} {% if community and show_community %}
<span class="fade">{{ user.username }}</span>
</div>
</a>
{%- endmacro %} {% macro pagination(page=0, items=0) -%}
<div class="flex justify-between gap-2 w-full">
{% if page > 0 %}
<a class="button quaternary" href="?page={{ page - 1 }}">
{{ icon "arrow-left" }}
<span>{{ text "general:link.previous" }}</span>
</a>
{% else %}
<div></div>
{% endif %} {% if items != 0 %}
<a class="button quaternary" href="?page={{ page + 1 }}">
<span>{{ text "general:link.next" }}</span>
{{ icon "arrow-right"}}
</a>
{% endif %}
</div>
{%- endmacro %}

View file

@ -17,11 +17,11 @@
}}
<div class="flex flex-col">
<!-- prettier-ignore -->
<h3 id="username" class="username">
<h3 id="username" class="username flex items-center gap-2">
{{ components::username(user=profile) }}
{% if profile.is_verified %}
<span title="Verified">
<span title="Verified" style="color: var(--color-primary);" class="flex items-center">
{{ icon "badge-check" }}
</span>
{% endif %}
@ -158,7 +158,7 @@
</div>
</div>
{% endif %} {% if not profile.settings.private_communities or
is_self %}
is_self or is_helper %}
<div class="card-nest">
<div class="card small flex gap-2 items-center">
{{ icon "users-round" }}
@ -177,7 +177,140 @@
{% endif %}
</div>
<div class="rhs w-full">{% block content %}{% endblock %}</div>
<div class="rhs w-full flex flex-col gap-4">
{% if is_helper %}
<div class="card-nest">
<div class="card small flex items-center gap-2">
{{ icon "shield" }}
<span>{{ text "auth:label.moderation" }}</span>
</div>
<div class="card tertiary">
<div class="flex flex-col gap-2" id="mod_options">
<div
class="card w-full flex flex-wrap gap-2"
ui_ident="actions"
>
<a
href="/settings?username={{ profile.username }}"
class="button quaternary"
>
{{ icon "settings" }}
<span>View settings</span>
</a>
<button
class="red quaternary"
onclick="delete_account(event)"
>
{{ icon "trash" }}
<span
>{{ text "settings:label.delete_account"
}}</span
>
</button>
</div>
</div>
<script>
setTimeout(() => {
const ui = ns("ui");
const element =
document.getElementById("mod_options");
async function profile_request(
do_confirm,
path,
body,
) {
if (do_confirm) {
if (
!(await trigger("atto::confirm", [
"Are you sure you would like to do this?",
]))
) {
return;
}
}
fetch(
`/api/v1/auth/profile/{{ profile.id }}/${path}`,
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify(body),
},
)
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
});
}
globalThis.delete_account = async (e) => {
e.preventDefault();
if (
!(await trigger("atto::confirm", [
"Are you sure you would like to do this?",
]))
) {
return;
}
fetch(
"/api/v1/auth/profile/{{ profile.id }}",
{
method: "DELETE",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
password: "",
}),
},
)
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
});
};
ui.refresh_container(element, ["actions"]);
ui.generate_settings_ui(
element,
[
[
["is_verified", "Is verified"],
"{{ profile.is_verified }}",
"checkbox",
],
],
null,
{
is_verified: (value) => {
profile_request(false, "verified", {
is_verified: value,
});
},
},
);
}, 150);
</script>
</div>
</div>
{% endif %} {% block content %}{% endblock %}
</div>
</div>
</div>
</article>

View file

@ -11,6 +11,8 @@ content %}
{% for post in posts %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% endfor %}
{{ components::pagination(page=page, items=posts|length) }}
</div>
</div>
{% endblock %}

View file

@ -2,6 +2,13 @@
<title>Settings - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav() }}
<main class="flex flex-col gap-2">
{% if profile.id != user.id %}
<div class="card w-full red flex gap-2 items-center">
{{ icon "skull" }}
<b>Editing other user's settings! Please be careful.</b>
</div>
{% endif %}
<div class="pillmenu">
<a data-tab-button="account" class="active" href="#/account">
{{ text "settings:tab.account" }}
@ -95,6 +102,38 @@
</div>
</div>
<div class="card-nest" ui_ident="change_password">
<div class="card small flex items-center gap-2 red">
{{ icon "skull" }}
<b>{{ text "settings:label.delete_account" }}</b>
</div>
<form
class="card flex flex-col gap-2"
onsubmit="delete_account(event)"
>
<div class="flex flex-col gap-1">
<label for="current_password"
>{{ text "settings:label.current_password" }}</label
>
<input
type="password"
name="current_password"
id="current_password"
placeholder="current_password"
required
minlength="6"
autocomplete="off"
/>
</div>
<button class="primary">
{{ icon "trash" }}
<span>{{ text "general:action.delete" }}</span>
</button>
</form>
</div>
<button onclick="save_settings()" id="save_button">
{{ icon "check" }}
<span>{{ text "general:action.save" }}</span>
@ -160,7 +199,7 @@
class="card w-full tertiary hidden flex flex-col gap-2"
data-tab="sessions"
>
{% for token in user.tokens %}
{% for token in profile.tokens %}
<div class="card w-full flex justify-between flex-collapse gap-2">
<div class="flex flex-col gap-1">
<b
@ -214,7 +253,7 @@
tokens = new_tokens;
// send request to save
fetch("/api/v1/auth/profile/{{ user.id }}/tokens", {
fetch("/api/v1/auth/profile/{{ profile.id }}/tokens", {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -231,7 +270,7 @@
};
globalThis.save_settings = () => {
fetch("/api/v1/auth/profile/{{ user.id }}/settings", {
fetch("/api/v1/auth/profile/{{ profile.id }}/settings", {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -249,7 +288,7 @@
globalThis.change_password = (e) => {
e.preventDefault();
fetch("/api/v1/auth/profile/{{ user.id }}/password", {
fetch("/api/v1/auth/profile/{{ profile.id }}/password", {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -279,7 +318,7 @@
return;
}
fetch("/api/v1/auth/profile/{{ user.id }}/username", {
fetch("/api/v1/auth/profile/{{ profile.id }}/username", {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -297,6 +336,35 @@
});
};
globalThis.delete_account = async (e) => {
e.preventDefault();
if (
!(await trigger("atto::confirm", [
"Are you sure you would like to do this?",
]))
) {
return;
}
fetch("/api/v1/auth/profile/{{ profile.id }}", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
password: e.target.current_password.value,
}),
})
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
});
};
globalThis.upload_avatar = (e) => {
e.preventDefault();
e.target.querySelector("button").style.display = "none";
@ -362,12 +430,12 @@
[
[
["display_name", "Display name"],
"{{ user.settings.display_name }}",
"{{ profile.settings.display_name }}",
"input",
],
[
["biography", "Biography"],
"{{ user.settings.biography }}",
"{{ profile.settings.biography }}",
"textarea",
],
],
@ -382,7 +450,7 @@
"private_profile",
"Only allow users I'm following to view my profile",
],
"{{ user.settings.private_profile }}",
"{{ profile.settings.private_profile }}",
"checkbox",
],
[
@ -390,7 +458,7 @@
"private_communities",
"Keep my joined communities private",
],
"{{ user.settings.private_communities }}",
"{{ profile.settings.private_communities }}",
"checkbox",
],
],

View file

@ -1,7 +1,7 @@
use crate::{
State, get_user_from_token,
model::{ApiReturn, Error},
routes::api::v1::{UpdateUserIsVerified, UpdateUserPassword, UpdateUserUsername},
routes::api::v1::{DeleteUser, UpdateUserIsVerified, UpdateUserPassword, UpdateUserUsername},
};
use axum::{
Extension, Json,
@ -32,7 +32,7 @@ pub async fn redirect_from_id(
}
/// Update the settings of the given user.
pub async fn update_profile_settings_request(
pub async fn update_user_settings_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
@ -59,7 +59,7 @@ pub async fn update_profile_settings_request(
}
/// Update the password of the given user.
pub async fn update_profile_password_request(
pub async fn update_user_password_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
@ -88,7 +88,7 @@ pub async fn update_profile_password_request(
}
}
pub async fn update_profile_username_request(
pub async fn update_user_username_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
@ -119,7 +119,7 @@ pub async fn update_profile_username_request(
}
/// Update the tokens of the given user.
pub async fn update_profile_tokens_request(
pub async fn update_user_tokens_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
@ -146,7 +146,7 @@ pub async fn update_profile_tokens_request(
}
/// Update the verification status of the given user.
pub async fn update_profile_is_verified_request(
pub async fn update_user_is_verified_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
@ -170,3 +170,33 @@ pub async fn update_profile_is_verified_request(
Err(e) => Json(e.into()),
}
}
/// Delete the given user.
pub async fn delete_user_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
Json(req): Json<DeleteUser>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
if user.id != id && !user.permissions.check(FinePermission::MANAGE_USERS) {
return Json(Error::NotAllowed.into());
}
match data
.delete_user(id, &req.password, user.permissions.check_manager())
.await
{
Ok(_) => Json(ApiReturn {
ok: true,
message: "User deleted".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}

View file

@ -119,23 +119,27 @@ pub fn routes() -> Router {
)
.route(
"/auth/profile/{id}/settings",
post(auth::profile::update_profile_settings_request),
post(auth::profile::update_user_settings_request),
)
.route(
"/auth/profile/{id}",
delete(auth::profile::delete_user_request),
)
.route(
"/auth/profile/{id}/password",
post(auth::profile::update_profile_password_request),
post(auth::profile::update_user_password_request),
)
.route(
"/auth/profile/{id}/username",
post(auth::profile::update_profile_username_request),
post(auth::profile::update_user_username_request),
)
.route(
"/auth/profile/{id}/tokens",
post(auth::profile::update_profile_tokens_request),
post(auth::profile::update_user_tokens_request),
)
.route(
"/auth/profile/{id}/verified",
post(auth::profile::update_profile_is_verified_request),
post(auth::profile::update_user_is_verified_request),
)
.route(
"/auth/profile/find/{id}",
@ -256,3 +260,8 @@ pub struct UpdateNotificationRead {
pub struct UpdateMembershipRole {
pub role: CommunityPermission,
}
#[derive(Deserialize)]
pub struct DeleteUser {
pub password: String,
}

View file

@ -12,6 +12,7 @@ use tetratto_core::model::{
auth::User,
communities::{Community, CommunityReadAccess},
communities_permissions::CommunityPermission,
permissions::FinePermission,
};
macro_rules! check_permissions {
@ -194,6 +195,7 @@ pub async fn feed_request(
community_context_bools!(data, user, community);
context.insert("feed", &feed);
context.insert("page", &props.page);
community_context(
&mut context,
&community,
@ -232,9 +234,11 @@ pub async fn settings_request(
};
if user.id != community.owner {
return Err(Html(
render_error(Error::NotAllowed, &jar, &data, &None).await,
));
if !user.permissions.check(FinePermission::MANAGE_COMMUNITIES) {
return Err(Html(
render_error(Error::NotAllowed, &jar, &data, &None).await,
));
}
}
// init context
@ -298,6 +302,7 @@ pub async fn post_request(
context.insert("post", &post);
context.insert("replies", &feed);
context.insert("page", &props.page);
context.insert(
"owner",
&data

View file

@ -6,13 +6,23 @@ use axum::{
response::{Html, IntoResponse},
};
use axum_extra::extract::CookieJar;
use serde::Deserialize;
use tera::Context;
use tetratto_core::model::{Error, auth::User, communities::Community};
use tetratto_core::model::{
Error, auth::User, communities::Community, permissions::FinePermission,
};
#[derive(Deserialize)]
pub struct SettingsProps {
#[serde(default)]
pub username: String,
}
/// `/settings`
pub async fn settings_request(
jar: CookieJar,
Extension(data): Extension<State>,
Query(req): Query<SettingsProps>,
) -> impl IntoResponse {
let data = data.read().await;
let user = match get_user_from_token!(jar, data.0) {
@ -24,12 +34,25 @@ pub async fn settings_request(
}
};
let settings = user.settings.clone();
let tokens = user.tokens.clone();
let profile = if req.username.is_empty() | !user.permissions.check(FinePermission::MANAGE_USERS)
{
user.clone()
} else {
match data.0.get_user_by_username(&req.username).await {
Ok(ua) => ua,
Err(e) => {
return Err(Html(render_error(e, &jar, &data, &None).await));
}
}
};
let settings = profile.settings.clone();
let tokens = profile.tokens.clone();
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &Some(user)).await;
context.insert("profile", &profile);
context.insert(
"user_settings_serde",
&serde_json::to_string(&settings)
@ -98,7 +121,7 @@ pub async fn posts_request(
// check for private profile
if other_user.settings.private_profile {
if let Some(ref ua) = user {
if ua.id != other_user.id {
if (ua.id != other_user.id) && !ua.permissions.check(FinePermission::MANAGE_USERS) {
if data
.0
.get_userfollow_by_initiator_receiver(other_user.id, ua.id)
@ -176,6 +199,7 @@ pub async fn posts_request(
};
context.insert("posts", &posts);
context.insert("page", &props.page);
profile_context(
&mut context,
&other_user,

View file

@ -6,6 +6,8 @@ use crate::model::{
permissions::FinePermission,
};
use crate::{auto_method, execute, get, query_row};
use pathbufd::PathBufD;
use std::fs::{exists, remove_file};
use tetratto_shared::hash::{hash_salted, salt};
#[cfg(feature = "sqlite")]
@ -151,6 +153,85 @@ impl DataManager {
self.cache_clear_user(&user).await;
// delete communities
let res = execute!(
&conn,
"DELETE FROM communities WHERE owner = $1",
&[&(id as isize)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete memberships
// member counts will remain the same... but that should probably be changed
let res = execute!(
&conn,
"DELETE FROM memberships WHERE owner = $1",
&[&(id as isize)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete notifications
let res = execute!(
&conn,
"DELETE FROM notifications WHERE owner = $1",
&[&(id as isize)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete reactions
// reactions counts will remain the same :)
let res = execute!(
&conn,
"DELETE FROM reactions WHERE owner = $1",
&[&(id as isize)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete posts
let res = execute!(
&conn,
"DELETE FROM posts WHERE owner = $1",
&[&(id as isize)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// remove images
let avatar = PathBufD::current().extend(&[
self.0.dirs.media.as_str(),
"avatars",
&format!("{}.avif", &user.id),
]);
let banner = PathBufD::current().extend(&[
self.0.dirs.media.as_str(),
"banners",
&format!("{}.avif", &user.id),
]);
if exists(&avatar).unwrap() {
remove_file(avatar).unwrap();
}
if exists(&banner).unwrap() {
remove_file(banner).unwrap();
}
// ...
Ok(())
}
@ -159,6 +240,8 @@ impl DataManager {
return Err(Error::NotAllowed);
}
let other_user = self.get_user_by_id(id).await?;
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
@ -166,10 +249,9 @@ impl DataManager {
let res = execute!(
&conn,
"UPDATE users SET is_verified = $1 WHERE id = $2",
"UPDATE users SET verified = $1 WHERE id = $2",
&[
&(if x { 1 } else { 0 }).to_string().as_str(),
&serde_json::to_string(&x).unwrap().as_str(),
&id.to_string().as_str()
]
);
@ -178,7 +260,7 @@ impl DataManager {
return Err(Error::DatabaseError(e.to_string()));
}
self.cache_clear_user(&user).await;
self.cache_clear_user(&other_user).await;
Ok(())
}

View file

@ -9,7 +9,7 @@ use tetratto_shared::{
/// `(ip, token, creation timestamp)`
pub type Token = (String, String, usize);
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct User {
pub id: usize,
pub created: usize,