Manage users on admin panel
This commit is contained in:
@@ -43,7 +43,7 @@ pub async fn change_password(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compute_pasword_hash(password: SecretString) -> Result<SecretString, anyhow::Error> {
|
||||
pub(crate) fn compute_pasword_hash(password: SecretString) -> Result<SecretString, anyhow::Error> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let password_hash = Argon2::new(
|
||||
Algorithm::Argon2id,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::authentication::Role;
|
||||
use chrono::{DateTime, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::authentication::Role;
|
||||
|
||||
pub struct UserEntry {
|
||||
pub user_id: Uuid,
|
||||
pub username: String,
|
||||
|
||||
@@ -56,7 +56,7 @@ pub async fn change_password(
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_password(password: &str) -> Result<(), anyhow::Error> {
|
||||
pub fn verify_password(password: &str) -> Result<(), anyhow::Error> {
|
||||
if password.len() < 12 || password.len() > 128 {
|
||||
anyhow::bail!("The password must contain between 12 and 128 characters.");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::routes::get_users;
|
||||
use crate::{
|
||||
authentication::AuthenticatedUser,
|
||||
routes::{AppError, get_max_page, get_subs, get_total_subs},
|
||||
@@ -45,6 +46,9 @@ pub async fn admin_dashboard(
|
||||
.await
|
||||
.context("Could not fetch total subscribers count from the database.")?;
|
||||
let max_page = get_max_page(count);
|
||||
let users = get_users(&connection_pool)
|
||||
.await
|
||||
.context("Could not fetch users")?;
|
||||
let template = DashboardTemplate {
|
||||
user,
|
||||
idempotency_key_1,
|
||||
@@ -53,6 +57,7 @@ pub async fn admin_dashboard(
|
||||
subscribers,
|
||||
current_page,
|
||||
max_page,
|
||||
users,
|
||||
};
|
||||
Ok(Html(template.render().unwrap()).into_response())
|
||||
}
|
||||
|
||||
@@ -15,10 +15,7 @@ use uuid::Uuid;
|
||||
|
||||
const SUBS_PER_PAGE: i64 = 5;
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "Retrieving most recent subscribers from database",
|
||||
skip(connection_pool)
|
||||
)]
|
||||
#[tracing::instrument(name = "Retrieving subscribers from database", skip(connection_pool))]
|
||||
pub async fn get_subscribers_page(
|
||||
State(AppState {
|
||||
connection_pool, ..
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::routes::verify_password;
|
||||
use crate::templates::MessageTemplate;
|
||||
use crate::{
|
||||
authentication::Role,
|
||||
domain::{PostEntry, UserEntry},
|
||||
@@ -7,9 +9,11 @@ use crate::{
|
||||
};
|
||||
use anyhow::Context;
|
||||
use axum::{
|
||||
Form,
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -18,6 +22,125 @@ pub struct ProfilePath {
|
||||
username: String,
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "Get users from database", skip(connection_pool))]
|
||||
pub async fn get_users(connection_pool: &PgPool) -> Result<Vec<UserEntry>, sqlx::Error> {
|
||||
sqlx::query_as!(
|
||||
UserEntry,
|
||||
r#"
|
||||
SELECT user_id, username, role as "role: Role", full_name, bio, member_since
|
||||
FROM users
|
||||
ORDER BY member_since DESC
|
||||
"#
|
||||
)
|
||||
.fetch_all(connection_pool)
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct CreateUserForm {
|
||||
username: String,
|
||||
password: SecretString,
|
||||
password_check: SecretString,
|
||||
admin: Option<bool>,
|
||||
}
|
||||
|
||||
struct NewUser {
|
||||
username: String,
|
||||
password_hash: SecretString,
|
||||
role: Role,
|
||||
}
|
||||
|
||||
impl TryFrom<CreateUserForm> for NewUser {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: CreateUserForm) -> Result<Self, Self::Error> {
|
||||
if value.username.trim().is_empty() {
|
||||
anyhow::bail!("Username cannot be empty.");
|
||||
}
|
||||
verify_password(value.password.expose_secret())?;
|
||||
if value.password.expose_secret() != value.password_check.expose_secret() {
|
||||
anyhow::bail!("Password mismatch.");
|
||||
}
|
||||
|
||||
let role = value.admin.map(|_| Role::Admin).unwrap_or(Role::Writer);
|
||||
let password_hash = crate::authentication::compute_pasword_hash(value.password)
|
||||
.context("Failed to hash password.")?;
|
||||
Ok(Self {
|
||||
username: value.username,
|
||||
password_hash,
|
||||
role,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "Creating new user", skip_all, fields(username = %form.username))]
|
||||
pub async fn create_user(
|
||||
State(AppState {
|
||||
connection_pool, ..
|
||||
}): State<AppState>,
|
||||
Form(form): Form<CreateUserForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
let new_user: NewUser = match form.try_into().map_err(|e: anyhow::Error| e.to_string()) {
|
||||
Err(e) => {
|
||||
let template = HtmlTemplate(MessageTemplate::error(e));
|
||||
return Ok(template.into_response());
|
||||
}
|
||||
Ok(new_user) => new_user,
|
||||
};
|
||||
insert_user(&connection_pool, new_user)
|
||||
.await
|
||||
.context("Could not insert user in database.")?;
|
||||
let template = HtmlTemplate(MessageTemplate::success(
|
||||
"The new user has been created.".into(),
|
||||
));
|
||||
Ok(template.into_response())
|
||||
}
|
||||
|
||||
async fn insert_user(connection_pool: &PgPool, new_user: NewUser) -> Result<Uuid, sqlx::Error> {
|
||||
let user_id = Uuid::new_v4();
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO users (user_id, username, password_hash, role)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
"#,
|
||||
user_id,
|
||||
new_user.username,
|
||||
new_user.password_hash.expose_secret(),
|
||||
new_user.role as _
|
||||
)
|
||||
.execute(connection_pool)
|
||||
.await?;
|
||||
Ok(user_id)
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct SubscriberPathParams {
|
||||
pub user_id: Uuid,
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "Delete user from database", skip(connection_pool))]
|
||||
pub async fn delete_user(
|
||||
State(AppState {
|
||||
connection_pool, ..
|
||||
}): State<AppState>,
|
||||
Path(SubscriberPathParams { user_id }): Path<SubscriberPathParams>,
|
||||
) -> Result<Response, AppError> {
|
||||
let result = sqlx::query!("DELETE FROM users WHERE user_id = $1", user_id)
|
||||
.execute(&connection_pool)
|
||||
.await
|
||||
.context("Failed to delete user from database.")?;
|
||||
let template = if result.rows_affected() == 0 {
|
||||
HtmlTemplate(MessageTemplate::error(
|
||||
"The user could not be deleted.".into(),
|
||||
))
|
||||
} else {
|
||||
HtmlTemplate(MessageTemplate::success(
|
||||
"The user has been deleted.".into(),
|
||||
))
|
||||
};
|
||||
Ok(template.into_response())
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "Fetching user data", skip(connection_pool))]
|
||||
pub async fn user_profile(
|
||||
State(AppState {
|
||||
|
||||
@@ -88,6 +88,8 @@ pub fn app(
|
||||
.route("/subscribers", get(get_subscribers_page))
|
||||
.route("/subscribers/{subscriber_id}", delete(delete_subscriber))
|
||||
.route("/posts/{post_id}", delete(delete_post))
|
||||
.route("/users", post(create_user))
|
||||
.route("/users/{user_id}", delete(delete_user))
|
||||
.layer(middleware::from_fn(require_admin));
|
||||
let auth_routes = Router::new()
|
||||
.route("/dashboard", get(admin_dashboard))
|
||||
|
||||
@@ -64,6 +64,7 @@ pub struct DashboardTemplate {
|
||||
pub subscribers: Vec<SubscriberEntry>,
|
||||
pub current_page: i64,
|
||||
pub max_page: i64,
|
||||
pub users: Vec<UserEntry>,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
|
||||
@@ -1,39 +1,44 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Dashboard{% endblock %}
|
||||
{% block content %}
|
||||
<div class="max-w-5xl mx-auto p-4 sm:p-6">
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p class="mt-2 text-gray-600 items-start">
|
||||
<div class="max-w-5xl mx-auto p-4 sm:p-6">
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p class="mt-2 text-gray-600 items-start">
|
||||
<span>Connected as
|
||||
<a href="/users/{{ user.username }}"
|
||||
class="hover:text-blue-600 hover:underline font-bold">{{ user.username }}</a></span>
|
||||
{% if user.is_admin() %}
|
||||
<span class="ml-2 inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800">
|
||||
{% if user.is_admin() %}
|
||||
<span class="ml-2 inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800">
|
||||
admin
|
||||
</span>
|
||||
{% endif %}
|
||||
</p>
|
||||
<button hx-get="/admin/logout"
|
||||
type="submit"
|
||||
class="flex items-center text-sm text-gray-500 hover:text-red-600 transition-colors cursor-pointer gap-1 mt-2">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
|
||||
</svg>
|
||||
<span>Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
{% if user.is_admin() %}
|
||||
<div class="mb-8 p-6 bg-gradient-to-br from-blue-50 to-indigo-50 bg-blue-50 rounded-lg border border-blue-200">
|
||||
<h2 class="text-lg font-semibold text-blue-900 mb-6">Administration</h2>
|
||||
{% include "stats.html" %}
|
||||
{% include "subscribers/list.html" %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</p>
|
||||
<button hx-get="/admin/logout"
|
||||
type="submit"
|
||||
class="flex items-center text-sm text-gray-500 hover:text-red-600 transition-colors cursor-pointer gap-1 mt-2">
|
||||
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/>
|
||||
</svg>
|
||||
<span>Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
{% if user.is_admin() %}
|
||||
<div class="mb-8 p-6 bg-gradient-to-br from-blue-50 to-indigo-50 bg-blue-50 rounded-lg border border-blue-200">
|
||||
<h2 class="text-lg font-semibold text-blue-900 mb-6">Administration</h2>
|
||||
{% include "stats.html" %}
|
||||
{% include "subscribers/list.html" %}
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
{% include "publish.html" %}
|
||||
{% include "send_email.html" %}
|
||||
{% include "change_password.html" %}
|
||||
{% include "users/list.html" %}
|
||||
{% include "users/form.html" %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
{% include "publish.html" %}
|
||||
{% include "send_email.html" %}
|
||||
{% include "change_password.html" %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
39
templates/dashboard/users/card.html
Normal file
39
templates/dashboard/users/card.html
Normal file
@@ -0,0 +1,39 @@
|
||||
<div id="user-{{ user.user_id }}"
|
||||
class="bg-gray-50 rounded-lg p-4 border border-gray-200">
|
||||
<div class="flex flex-col sm:flex-row sm:items-start sm:justify-between">
|
||||
<div class="flex-1">
|
||||
<div class="flex items-center space-x-2">
|
||||
<a href="/users/{{ user.username }}"
|
||||
class="font-medium text-gray-900 hover:text-blue-600 hover:underline truncate">
|
||||
{{ user.username }}
|
||||
</a>
|
||||
{% if user.role.to_string() == "admin" %}
|
||||
<span class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 flex-shrink-0">
|
||||
admin
|
||||
</span>
|
||||
{% else %}
|
||||
<span class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 flex-shrink-0">
|
||||
writer
|
||||
</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="text-sm text-gray-500 mt-1">{{ user.formatted_date() }}</div>
|
||||
</div>
|
||||
<div class="mt-3 sm:mt-0 sm:ml-4">
|
||||
<button hx-delete="/admin/users/{{ user.user_id }}"
|
||||
hx-target="#user-{{ user.user_id }}"
|
||||
hx-swap="outerHTML"
|
||||
hx-confirm="Are you sure you want to delete this user?"
|
||||
class="inline-flex items-center py-1 px-2 text-sm font-medium text-red-500 bg-red-50 border-2 border-dashed border-red-300 rounded-md hover:bg-red-100 hover:border-red-400 hover:text-red-600 transition-all duration-200 group">
|
||||
<svg class="w-4 h-4 mr-2 group-hover:scale-110 transition-transform"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
|
||||
</svg>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
78
templates/dashboard/users/form.html
Normal file
78
templates/dashboard/users/form.html
Normal file
@@ -0,0 +1,78 @@
|
||||
<div class="bg-white rounded-lg shadow-md border border-gray-200 mb-8">
|
||||
<div class="p-6 border-b border-gray-200">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold text-gray-900 flex items-center">
|
||||
<svg class="w-5 h-5 text-green-600 mr-2"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"/>
|
||||
</svg>
|
||||
Create a new user
|
||||
</h2>
|
||||
<p class="text-sm text-gray-600 mt-1">Add a new user to the system.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-6">
|
||||
<form hx-post="/admin/users"
|
||||
hx-target="#user-form-messages"
|
||||
hx-swap="innerHTML"
|
||||
class="space-y-4">
|
||||
<div>
|
||||
<label for="username" class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Username
|
||||
</label>
|
||||
<input type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500">
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Password
|
||||
</label>
|
||||
<input type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
required
|
||||
minlength="12"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500">
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password_check" class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Confirm password
|
||||
</label>
|
||||
<input type="password"
|
||||
id="password_check"
|
||||
name="password_check"
|
||||
required
|
||||
minlength="12"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500">
|
||||
</div>
|
||||
|
||||
<div class="flex items-center">
|
||||
<input type="checkbox"
|
||||
id="admin"
|
||||
name="admin"
|
||||
value="true"
|
||||
class="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded">
|
||||
<label for="admin" class="ml-2 block text-sm text-gray-700">
|
||||
Grant administrator privileges
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button type="submit"
|
||||
class="w-full bg-green-600 text-white hover:bg-green-700 font-medium py-2 px-4 rounded-md transition-colors">
|
||||
Create
|
||||
</button>
|
||||
|
||||
<div id="user-form-messages"></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
40
templates/dashboard/users/list.html
Normal file
40
templates/dashboard/users/list.html
Normal file
@@ -0,0 +1,40 @@
|
||||
<div class="bg-white rounded-lg shadow-md border border-gray-200 mb-8">
|
||||
<div class="p-6 border-b border-gray-200">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold text-gray-900 flex items-center">
|
||||
<svg class="w-5 h-5 text-purple-600 mr-2"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/>
|
||||
</svg>
|
||||
Users management
|
||||
</h2>
|
||||
<p class="text-sm text-gray-600 mt-1">View and manage users.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="users-list" class="p-6 space-y-4">
|
||||
{% if users.is_empty() %}
|
||||
<div class="bg-gray-50 rounded-lg p-8 border-2 border-dashed border-gray-300 text-center">
|
||||
<div class="w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<svg class="w-8 h-8 text-gray-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 class="text-lg font-medium text-gray-900 mb-2">No users found</h3>
|
||||
<p class="text-gray-600">No users in the system.</p>
|
||||
</div>
|
||||
{% else %}
|
||||
{% for user in users %}
|
||||
{% include "dashboard/users/card.html" %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
Reference in New Issue
Block a user