Added settings and API key stuff

Signed-off-by: Marcel Müller <neikos@neikos.email>
This commit is contained in:
Marcel Müller 2026-01-23 19:31:53 +01:00
parent 9d08e23352
commit a80ad57ca9
14 changed files with 396 additions and 45 deletions

View file

@ -23,3 +23,6 @@ tracing-subscriber = { workspace = true, features = ["env-filter"] }
tera = "1.20.1"
notify-debouncer-full = "0.6.0"
tower-livereload = "0.10.2"
time = "0.3.45"
rand = "0.9.2"
serde_json.workspace = true

View file

@ -0,0 +1,3 @@
-- Add migration script here
DROP TABLE IF EXISTS api_keys;

View file

@ -0,0 +1,12 @@
-- Add migration script here
CREATE TABLE IF NOT EXISTS api_keys
(
id INTEGER PRIMARY KEY NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id),
token TEXT NOT NULL,
name TEXT NOT NULL,
expiration_date TEXT NOT NULL,
permissions TEXT NOT NULL,
revoked BOOLEAN NOT NULL
);

View file

@ -31,17 +31,21 @@ pub mod settings;
pub mod users;
pub type WebResult<T> = Result<T, AppError>;
pub type TemplatedHtml = Html<String>;
#[derive(Debug, Error, Display)]
pub enum AppError {
/// An error occurred while templating
Tera(#[from] tera::Error),
/// An error occurred while interacting with the database
Sqlx(#[from] sqlx::Error),
}
impl IntoResponse for AppError {
fn into_response(self) -> axum::response::Response {
let mut error_context = Context::new();
error_context.insert("error", &self.to_string());
error_context.insert("error", &format!("{self:?}"));
(
StatusCode::INTERNAL_SERVER_ERROR,
Html(
@ -198,7 +202,7 @@ async fn run() -> anyhow::Result<()> {
}
async fn show_index(renderer: Renderer) -> WebResult<Html<String>> {
renderer.render_template("index.tera.html", None).map(Html)
renderer.render_template("index.tera.html", None)
}
async fn shutdown_signal(handle: AbortHandle) {
@ -233,7 +237,7 @@ impl Renderer {
&self,
name: &str,
context: impl Into<Option<Context>>,
) -> WebResult<String> {
) -> WebResult<Html<String>> {
let mut main_context = Context::default();
if let Some(user) = self.auth.user.as_ref() {
main_context.insert("logged_in", &true);
@ -242,14 +246,6 @@ impl Renderer {
main_context.extend(context.into().unwrap_or_default());
Ok(TERA.read().unwrap().render(name, &main_context)?)
Ok(Html(TERA.read().unwrap().render(name, &main_context)?))
}
}
async fn show_protected(renderer: Renderer) -> Html<String> {
Html(
renderer
.render_template("protected.tera.html", None)
.unwrap(),
)
}

View file

@ -1,9 +1,29 @@
use axum::Form;
use axum::Router;
use axum::extract::State;
use axum::response::IntoResponse;
use axum::response::Redirect;
use axum::routing::get;
use axum::routing::post;
use axum_login::login_required;
use password_auth::generate_hash;
use rand::distr::Alphanumeric;
use rand::distr::SampleString;
use rand::rng;
use serde::Deserialize;
use serde::Serialize;
use sqlx::prelude::FromRow;
use tera::Context;
use time::Date;
use time::Duration;
use time::OffsetDateTime;
use time::Time;
use crate::AppState;
use crate::AuthSession;
use crate::Renderer;
use crate::TemplatedHtml;
use crate::WebResult;
pub fn routes() -> Router<AppState> {
Router::new()
@ -11,13 +31,117 @@ pub fn routes() -> Router<AppState> {
.route("/settings/change_password", get(show_change_password))
.route("/settings/change_password", post(do_change_password))
.route("/settings/api_keys", get(show_api_keys))
.route("/settings/new_api_key", post(create_new_api_key))
.route("/settings/revoke_api_key", post(revoke_api_key))
.route_layer(login_required!(crate::Backend, login_url = "/login"))
}
async fn show_settings() {}
async fn show_settings(renderer: Renderer) -> WebResult<TemplatedHtml> {
renderer.render_template("settings/index.tera.html", None)
}
async fn show_change_password() {}
async fn show_change_password(renderer: Renderer) -> WebResult<TemplatedHtml> {
renderer.render_template("settings/change_password.tera.html", None)
}
async fn do_change_password() {}
async fn show_api_keys() {}
#[derive(Debug, FromRow, Serialize)]
pub struct ApiKey {
id: i64,
user_id: i64,
token: Vec<u8>,
name: String,
expiration_date: OffsetDateTime,
permissions: String,
revoked: bool,
}
async fn show_api_keys(
renderer: Renderer,
app_state: State<AppState>,
auth: AuthSession,
) -> WebResult<TemplatedHtml> {
let mut context = Context::new();
let api_keys: Vec<ApiKey> = sqlx::query_as("SELECT * FROM api_keys WHERE user_id = ?")
.bind(auth.user.unwrap().id())
.fetch_all(&app_state.db)
.await?;
context.insert("api_keys", &api_keys.into_iter().map(|key| {
serde_json::json! {{
"id": key.id,
"name": key.name,
"revoked": key.revoked,
"expiration_date": key.expiration_date.format(&time::format_description::well_known::iso8601::Iso8601::DATE).unwrap(),
}}
}).collect::<Vec<_>>());
context.insert(
"one_year_date",
&OffsetDateTime::now_utc()
.replace_year(OffsetDateTime::now_utc().year() + 1)
.unwrap()
.format(&time::format_description::well_known::iso8601::Iso8601::DATE)
.unwrap(),
);
renderer.render_template("settings/api_keys.tera.html", context)
}
#[derive(Debug, Deserialize)]
struct NewApiKeyForm {
name: String,
expiration_date: String,
}
async fn create_new_api_key(
app_state: State<AppState>,
auth: AuthSession,
new_api_key: Form<NewApiKeyForm>,
) -> WebResult<impl IntoResponse> {
let values = Alphanumeric.sample_string(&mut rng(), 32);
let token = tokio::task::spawn_blocking(|| generate_hash(values))
.await
.unwrap();
let expiration_date = Date::parse(
&new_api_key.expiration_date,
&time::format_description::well_known::Iso8601::DATE,
)
.unwrap();
let expiration_date =
OffsetDateTime::new_utc(expiration_date, Time::from_hms(0, 0, 0).unwrap());
sqlx::query("INSERT INTO api_keys (user_id, token, name, expiration_date, permissions, revoked) VALUES (?, ?, ?, ?, ?, false)")
.bind(auth.user.unwrap().id())
.bind(token)
.bind(new_api_key.name.clone())
.bind(expiration_date)
.bind("")
.execute(&app_state.db)
.await?;
Ok(Redirect::to("/settings/api_keys"))
}
#[derive(Debug, Deserialize)]
struct RevokeApiKeyForm {
api_key_id: i64,
}
async fn revoke_api_key(
app_state: State<AppState>,
auth: AuthSession,
revoke_api_key: Form<RevokeApiKeyForm>,
) -> WebResult<impl IntoResponse> {
sqlx::query("UPDATE api_keys SET revoked = true, token = \"\" WHERE id = ? AND user_id = ?")
.bind(revoke_api_key.api_key_id)
.bind(auth.user.unwrap().id())
.execute(&app_state.db)
.await?;
Ok(Redirect::to("/settings/api_keys"))
}

View file

@ -10,9 +10,7 @@ use crate::UserCredentials;
use crate::WebResult;
pub async fn show_login(renderer: Renderer) -> WebResult<Html<String>> {
renderer
.render_template("users/login.tera.html", None)
.map(Html)
renderer.render_template("users/login.tera.html", None)
}
pub async fn do_login(

View file

@ -11,9 +11,7 @@ use crate::UserCredentials;
use crate::WebResult;
pub async fn show_register(renderer: Renderer) -> WebResult<Html<String>> {
renderer
.render_template("users/register.tera.html", None)
.map(Html)
renderer.render_template("users/register.tera.html", None)
}
pub async fn do_register(

View file

@ -1,6 +1,6 @@
{% macro text_input(label, name, id="",type="text") %}
{% macro text_input(label, name, id="",type="text",value="") %}
<div class="flex flex-col">
<label for="{{id}}" class="font-bold">{{label}}:</label>
<input class="border rounded p-1 bg-gray-50" type="{{type}}" name="{{name}}" id="{{id}}" />
<input class="border rounded p-1 bg-gray-50" type="{{type}}" name="{{name}}" id="{{id}}" {% if value %}value="{{value}}"{% endif %} />
</div>
{% endmacro text_input %}

View file

@ -0,0 +1,25 @@
{% extends "base.tera.html" %}
{% import "inputs.tera.html" as inputs %}
{% block title %}
Home
{% endblock title %}
{% block content %}
<div class="place-self-center mx-auto p-4 space-y-4 bg-red-200 md:border border-red-300 shadow-xl md:rounded">
<h1 class="font-bold text-2xl">There was an internal error</h1>
<p>
{{ error }}
</p>
<hr class="bg-red-800 border-0 h-px">
<p>
This error usually indicates that the problem is not on your side.
<br>
Additional information was logged for the operator.
<br>
Feel free to try again later.
</p>
</div>
{% endblock content %}

View file

@ -0,0 +1,69 @@
{% extends "base.tera.html" %}
{% import "inputs.tera.html" as inputs %}
{% block title %}
API Keys - {{ current_user.username }}
{% endblock title %}
{% block content %}
<div class="flex flex-col md:flex-row grow">
<div class="basis-1/4 p-4 m-4 space-y-4">
{% include "settings/sidebar.tera.html" %}
</div>
<div class="basis-3/4 p-4">
<h1 class="font-bold text-3xl">API Keys</h1>
<form action="/settings/new_api_key" method="POST" class="space-y-4">
{{ inputs::text_input(label="Name", name="name", id="name", type="text") }}
{{ inputs::text_input(label="Expiration Date", name="expiration_date", id="expiration_date", type="date", value=one_year_date)}}
<div class="flex flex-col">
<button type="submit" class="bg-blue-500 p-2 rounded-lg text-white">
Create API Key
</button>
</div>
</form>
<hr class="my-4 w-1/2 border-0 bg-zinc-300 h-0.5 mx-auto">
<h2 class="font-bold text-2xl my-4">Current API Tokens</h2>
<table class="border-collapse border-spacing-2 border border-zinc-400 w-full">
<thead class="bg-orange-50">
<tr>
<th class="border border-zinc-300 w-1/4 p-4 font-semibold">Name</th>
<th class="border border-zinc-300 w-1/4 p-4 font-semibold">Active</th>
<th class="border border-zinc-300 w-1/4 p-4 font-semibold">Expiration Date</th>
<th class="border border-zinc-300 w-1/4 p-4 font-semibold">Actions</th>
</tr>
</thead>
<tbody>
{% for api_key in api_keys %}
<tr>
<td class="border border-zinc-200 p-2">{{ api_key.name}}</td>
<td class="border border-zinc-200 p-2 text-center">
{% if api_key.revoked %}
<span class="align-middle">No Longer Active</span><span class="inline-block align-middle size-6 ml-2 bg-zinc-500 rounded-lg"></span>
{% else %}
<span class="align-middle">Currently Active</span><span class="inline-block align-middle size-6 ml-2 bg-green-500 rounded-lg"></span>
{% endif %}
</td>
<td class="border border-zinc-200 p-2 text-center">{{ api_key.expiration_date }}</td>
<td class="border border-zinc-200 p-2 text-center">
{% if api_key.revoked %}
<span class="text-zinc-700">A revoked API Key cannot be revived</span>
{% else %}
<form action="/settings/revoke_api_key" method="POST">
<input type="hidden" name="api_key_id" value="{{ api_key.id }}">
<button type="submit" class="px-4 py-2 inline-block border border-red-700 bg-red-600 text-white rounded pointer-link">
Revoke API Key
</button>
</form>
{% endif %}
</td>
</tr>
{% endfor %}
<tbody>
</table>
</div>
</div>
{% endblock content %}

View file

@ -0,0 +1,27 @@
{% extends "base.tera.html" %}
{% import "inputs.tera.html" as inputs %}
{% block title %}
Change Password - {{ current_user.username }}
{% endblock title %}
{% block content %}
<div class="flex flex-col md:flex-row grow">
<div class="basis-1/4 p-4 m-4 space-y-4">
{% include "settings/sidebar.tera.html" %}
</div>
<div class="basis-3/4 p-4">
<h1 class="font-bold text-3xl">Change Password</h1>
<form action="/settings/change_password" method="POST" class="space-y-4">
{{ inputs::text_input(label="Old Password", name="old_password", id="old_password", type="password") }}
{{ inputs::text_input(label="New Password", name="password", id="password", type="password") }}
{{ inputs::text_input(label="Repeat New Password", name="confirm_password", id="confirm_password", type="password") }}
<div class="flex flex-col">
<button type="submit" class="bg-blue-500 p-2 rounded-lg text-white">
Change Password
</button>
</div>
</form>
</div>
</div>
{% endblock content %}

View file

@ -0,0 +1,19 @@
{% extends "base.tera.html" %}
{% import "inputs.tera.html" as inputs %}
{% block title %}
Settings - {{ current_user.username }}
{% endblock title %}
{% block content %}
<div class="flex flex-col md:flex-row grow">
<div class="basis-1/4 p-4 m-4 space-y-4">
{% include "settings/sidebar.tera.html" %}
</div>
<div class="basis-3/4 p-4">
<p>THIS IS YOUR MAIN SETTINGS WOOHOOOO</p>
<p>Your username is: <em>{{ current_user.username }}</em></p>
</div>
</div>
{% endblock content %}

View file

@ -0,0 +1,12 @@
<h2 class="text-xl font-bold px-4">Settings</h2>
<ul class="space-y-2 bg-zinc-200 p-2 rounded border border-zinc-400 shadow">
<li class="hover:bg-zinc-400">
<a class="p-1 px-2 inline-block w-full" href="/settings">Overview</a>
</li>
<li class="hover:bg-zinc-400">
<a class="p-1 px-2 inline-block w-full" href="/settings/change_password">Change Password</a>
</li>
<li class="hover:bg-zinc-400">
<a class="p-1 px-2 inline-block w-full" href="/settings/api_keys">API Keys</a>
</li>
</ul>