Admin dashboard and sessions

This commit is contained in:
Alphonse Paix
2025-09-01 03:08:43 +02:00
parent de1fc4a825
commit 6f6e6ab017
23 changed files with 809 additions and 56 deletions

159
src/routes/admin.rs Normal file
View File

@@ -0,0 +1,159 @@
use crate::{
authentication::{self, Credentials, validate_credentials},
routes::error_chain_fmt,
session_state::TypedSession,
startup::AppState,
};
use axum::{
Extension, Form, Json,
extract::{Request, State},
middleware::Next,
response::{Html, IntoResponse, Redirect, Response},
};
use axum_messages::Messages;
use reqwest::StatusCode;
use secrecy::{ExposeSecret, SecretString};
use std::fmt::Write;
use uuid::Uuid;
#[derive(thiserror::Error)]
pub enum AdminError {
#[error("Something went wrong.")]
UnexpectedError(#[from] anyhow::Error),
#[error("You must be logged in to access the admin dashboard.")]
NotAuthenticated,
#[error("Updating password failed.")]
ChangePassword,
}
impl std::fmt::Debug for AdminError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
error_chain_fmt(self, f)
}
}
impl IntoResponse for AdminError {
fn into_response(self) -> Response {
#[derive(serde::Serialize)]
struct ErrorResponse<'a> {
message: &'a str,
}
tracing::error!("{:?}", self);
match &self {
AdminError::UnexpectedError(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "An internal server error occured.",
}),
)
.into_response(),
AdminError::NotAuthenticated => Redirect::to("/login").into_response(),
AdminError::ChangePassword => Redirect::to("/admin/password").into_response(),
}
}
}
pub async fn require_auth(
session: TypedSession,
mut request: Request,
next: Next,
) -> Result<Response, AdminError> {
let user_id = session
.get_user_id()
.await
.map_err(|e| AdminError::UnexpectedError(e.into()))?
.ok_or(AdminError::NotAuthenticated)?;
let username = session
.get_username()
.await
.map_err(|e| AdminError::UnexpectedError(e.into()))?
.ok_or(AdminError::UnexpectedError(anyhow::anyhow!(
"Could not find username in session."
)))?;
request
.extensions_mut()
.insert(AuthenticatedUser { user_id, username });
Ok(next.run(request).await)
}
#[derive(Clone)]
pub struct AuthenticatedUser {
user_id: Uuid,
username: String,
}
pub async fn admin_dashboard(
Extension(AuthenticatedUser { username, .. }): Extension<AuthenticatedUser>,
) -> Result<Response, AdminError> {
Ok(Html(format!(include_str!("admin/dashboard.html"), username)).into_response())
}
#[derive(serde::Deserialize)]
pub struct PasswordFormData {
pub current_password: SecretString,
pub new_password: SecretString,
pub new_password_check: SecretString,
}
pub async fn change_password_form(messages: Messages) -> Result<Response, AdminError> {
let mut error_html = String::new();
for message in messages {
writeln!(error_html, "<p><i>{}</i></p>", message).unwrap();
}
Ok(Html(format!(
include_str!("admin/change_password_form.html"),
error_html
))
.into_response())
}
pub async fn change_password(
Extension(AuthenticatedUser { user_id, username }): Extension<AuthenticatedUser>,
State(AppState {
connection_pool, ..
}): State<AppState>,
messages: Messages,
Form(form): Form<PasswordFormData>,
) -> Result<Response, AdminError> {
let credentials = Credentials {
username,
password: form.current_password,
};
if form.new_password.expose_secret() != form.new_password_check.expose_secret() {
messages.error("You entered two different passwords - the field values must match.");
Err(AdminError::ChangePassword)
} else if validate_credentials(credentials, &connection_pool)
.await
.is_err()
{
messages.error("The current password is incorrect.");
Err(AdminError::ChangePassword)
} else if let Err(e) = verify_password(form.new_password.expose_secret()) {
messages.error(e);
Err(AdminError::ChangePassword)
} else {
authentication::change_password(user_id, form.new_password, &connection_pool)
.await
.map_err(|_| AdminError::ChangePassword)?;
messages.success("Your password has been changed.");
Ok(Redirect::to("/admin/password").into_response())
}
}
#[tracing::instrument(name = "Logging out", skip(messages, session))]
pub async fn logout(messages: Messages, session: TypedSession) -> Result<Response, AdminError> {
session.clear().await;
messages.success("You have successfully logged out.");
Ok(Redirect::to("/login").into_response())
}
fn verify_password(password: &str) -> Result<(), String> {
if password.len() < 12 || password.len() > 128 {
return Err("The password must contain between 12 and 128 characters.".into());
}
Ok(())
}

View File

@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Change password</title>
</head>
<body>
<form action="/admin/password" method="post">
<input
type="password"
name="current_password"
placeholder="Current password"
/>
<input type="password" name="new_password" placeholder="New password" />
<input
type="password"
name="new_password_check"
placeholder="Confirm new password"
/>
<button type="submit">Change password</button>
</form>
{}
<p><a href="/admin/dashboard">Back</a></p>
</body>
</html>

View File

@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Admin dashboard</title>
</head>
<body>
<p>Welcome {}!</p>
<p>Available actions:</p>
<ol>
<li><a href="/admin/password">Change password</a></li>
<li>
<form name="logoutForm" action="/admin/logout" method="post">
<input type="submit" value="Logout" />
</form>
</li>
</ol>
</body>
</html>

View File

@@ -1,11 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Home</title>
<body>
<p>Welcome to our newsletter!</p>
</body>
</head>
<body>
<p>Welcome to our newsletter!</p>
<p><a href="/login">Login</a></p>
</body>
</html>

View File

@@ -1,6 +1,7 @@
use crate::{
authentication::{AuthError, Credentials, validate_credentials},
routes::error_chain_fmt,
session_state::TypedSession,
startup::AppState,
};
use axum::{
@@ -63,11 +64,8 @@ pub async fn get_login(messages: Messages) -> impl IntoResponse {
Html(format!(include_str!("login/login.html"), error_html))
}
#[tracing::instrument(
skip(connection_pool, form),
fields(username=tracing::field::Empty, user_id=tracing::field::Empty)
)]
pub async fn post_login(
session: TypedSession,
messages: Messages,
State(AppState {
connection_pool, ..
@@ -75,20 +73,37 @@ pub async fn post_login(
Form(form): Form<LoginFormData>,
) -> Result<Redirect, LoginError> {
let credentials = Credentials {
username: form.username,
username: form.username.clone(),
password: form.password,
};
tracing::Span::current().record("username", tracing::field::display(&credentials.username));
let user_id = validate_credentials(credentials, &connection_pool)
.await
.map_err(|e| match e {
AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()),
AuthError::InvalidCredentials(_) => {
let e = LoginError::AuthError(e.into());
messages.error(e.to_string());
e
}
})?;
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
Ok(Redirect::to("/"))
match validate_credentials(credentials, &connection_pool).await {
Err(e) => {
let e = match e {
AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()),
AuthError::InvalidCredentials(_) => {
let e = LoginError::AuthError(e.into());
messages.error(e.to_string());
e
}
};
Err(e)
}
Ok(user_id) => {
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
session
.renew()
.await
.map_err(|e| LoginError::UnexpectedError(e.into()))?;
session
.insert_user_id(user_id)
.await
.map_err(|e| LoginError::UnexpectedError(e.into()))?;
session
.insert_username(form.username)
.await
.map_err(|e| LoginError::UnexpectedError(e.into()))?;
Ok(Redirect::to("/admin/dashboard"))
}
}
}

View File

@@ -1,16 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<body>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
{}
</body>
</head>
<body>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
{}
</body>
</html>

View File

@@ -87,7 +87,7 @@ pub async fn subscribe(
base_url,
..
}): State<AppState>,
Form(form): Form<FormData>,
Form(form): Form<SubscriptionFormData>,
) -> Result<Response, SubscribeError> {
let mut transaction = connection_pool
.begin()
@@ -195,15 +195,15 @@ Click <a href=\"{}\">here</a> to confirm your subscription.",
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct FormData {
pub struct SubscriptionFormData {
name: String,
email: String,
}
impl TryFrom<FormData> for NewSubscriber {
impl TryFrom<SubscriptionFormData> for NewSubscriber {
type Error = String;
fn try_from(value: FormData) -> Result<Self, Self::Error> {
fn try_from(value: SubscriptionFormData) -> Result<Self, Self::Error> {
let name = SubscriberName::parse(value.name)?;
let email = SubscriberEmail::parse(value.email)?;
Ok(Self { name, email })