Compare commits
13 Commits
559f36224e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f91303b92c | ||
|
|
aff3367623 | ||
|
|
1736aeb122 | ||
|
|
37d0c33633 | ||
|
|
3bfe779425 | ||
|
|
395099d0ee | ||
|
|
b922a610e6 | ||
|
|
7010aee5b2 | ||
|
|
614f044160 | ||
|
|
5b9ab3f47d | ||
|
|
b6f03f9efb | ||
|
|
d27022b26a | ||
|
|
1904c631c5 |
@@ -3,7 +3,7 @@ name: Release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
- "v*.*.*"
|
||||
|
||||
jobs:
|
||||
build_release:
|
||||
@@ -22,6 +22,11 @@ jobs:
|
||||
- name: Build release
|
||||
run: |
|
||||
cargo build --release
|
||||
|
||||
- name: Package frontend
|
||||
run: |
|
||||
zip -r static.zip static
|
||||
|
||||
- name: Generate a changelog
|
||||
uses: orhun/git-cliff-action@v4
|
||||
id: git-cliff
|
||||
@@ -31,8 +36,10 @@ jobs:
|
||||
github_token: ""
|
||||
env:
|
||||
OUTPUT: CHANGELOG.md
|
||||
|
||||
- uses: akkuman/gitea-release-action@v1
|
||||
with:
|
||||
files: |-
|
||||
target/release/weight_tracker
|
||||
body: Release build for weight_tracker
|
||||
static.zip
|
||||
body: ${{ steps.git-cliff.outputs.content }}
|
||||
|
||||
1050
Cargo.lock
generated
1050
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "weight_tracker"
|
||||
version = "0.1.0"
|
||||
version = "0.1.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
axum = "0.8"
|
||||
askama = "0.15"
|
||||
axum-sessions = "0.6"
|
||||
async-session = "3.0"
|
||||
axum_session = "0.19"
|
||||
axum_session_sqlx = { version = "0.8", features = ["sqlite"]}
|
||||
oauth2 = "5.0"
|
||||
reqwest = { version = "0.13", features = ["json"] }
|
||||
|
||||
@@ -16,4 +16,5 @@ tokio = { version = "1.0", features = ["full"] }
|
||||
thiserror = "2.0"
|
||||
anyhow = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
config = { version = "0.13", features = ["toml"] }
|
||||
tower-http = { version = "0.6", features = ["fs", "cors"] }
|
||||
|
||||
20
config.example.toml
Normal file
20
config.example.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
# OIDC Configuration
|
||||
[oidc]
|
||||
client_id = "your_client_id"
|
||||
client_secret = "your_client_secret"
|
||||
auth_url = "https://your-provider.com/auth"
|
||||
token_url = "https://your-provider.com/token"
|
||||
redirect_url = "http://localhost:3000/auth/callback"
|
||||
|
||||
# Server Configuration
|
||||
[server]
|
||||
host = "127.0.0.1"
|
||||
port = 3000
|
||||
|
||||
# Database Configuration
|
||||
[database]
|
||||
url = "sqlite:weight_tracker.db"
|
||||
|
||||
# Session Configuration
|
||||
[session]
|
||||
secret = "your_secret_key_that_is_long_enough_so_the_library_does_not_complain"
|
||||
@@ -2,8 +2,14 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="$(git cliff --bumped-version)"
|
||||
VERSION_CLEAN="${VERSION#v}"
|
||||
VERSION_CLEAN="$(git cliff --bumped-version)"
|
||||
if [[ ! $VERSION_CLEAN =~ ^[0-9] ]]; then
|
||||
echo "Error: VERSION_CLEAN does not start with a number"
|
||||
exit 1
|
||||
fi
|
||||
VERSION="v${VERSION_CLEAN}"
|
||||
|
||||
|
||||
sed -i "s/^version = \".*\"/version = \"${VERSION_CLEAN}\"/" Cargo.toml
|
||||
cargo check
|
||||
|
||||
@@ -14,7 +20,7 @@ if [ "${CONFIRM}" != "Y" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git commit -am "chore: bump version to ${VERSION}"
|
||||
git commit --allow-empty -am "chore: bump version to ${VERSION}"
|
||||
git tag -am "Version ${VERSION}" "${VERSION}"
|
||||
|
||||
echo Press Y to push commit and tag
|
||||
|
||||
113
src/config.rs
Normal file
113
src/config.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use oauth2::{AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl, basic::BasicClient};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::OidcClient;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
pub oidc: OidcConfig,
|
||||
pub server: ServerConfig,
|
||||
pub database: DatabaseConfig,
|
||||
pub session: SessionConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct OidcConfig {
|
||||
pub client_id: String,
|
||||
pub client_secret: String,
|
||||
pub auth_url: String,
|
||||
pub token_url: String,
|
||||
pub redirect_url: String,
|
||||
}
|
||||
|
||||
impl OidcConfig {
|
||||
pub fn to_client(
|
||||
&self,
|
||||
) -> OidcClient {
|
||||
let client_id = ClientId::new(self.client_id.clone());
|
||||
let client_secret = ClientSecret::new(self.client_secret.clone());
|
||||
let auth_url = AuthUrl::new(self.auth_url.clone()).unwrap();
|
||||
let token_url = TokenUrl::new(self.token_url.clone()).unwrap();
|
||||
let redirect_url = RedirectUrl::new(self.redirect_url.clone()).unwrap();
|
||||
|
||||
BasicClient::new(client_id)
|
||||
.set_client_secret(client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(redirect_url)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ServerConfig {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DatabaseConfig {
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SessionConfig {
|
||||
pub secret: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Load configuration from a TOML file and environment variables
|
||||
/// config-rs merges file config with environment variables automatically
|
||||
pub fn load(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let mut builder = config::Config::builder();
|
||||
|
||||
// Add default values first
|
||||
let defaults = Self::defaults();
|
||||
builder = builder.add_source(
|
||||
config::Config::try_from(&defaults)
|
||||
.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?,
|
||||
);
|
||||
|
||||
// Load from file if it exists
|
||||
if Path::new(path).exists() {
|
||||
builder = builder.add_source(config::File::with_name(path).required(false));
|
||||
}
|
||||
|
||||
// Override with environment variables
|
||||
// Environment variables should be prefixed with the app name and use __ for nesting
|
||||
// e.g., WEIGHT_TRACKER_OIDC__CLIENT_ID for oidc.client_id
|
||||
builder = builder.add_source(
|
||||
config::Environment::with_prefix("WEIGHT_TRACKER")
|
||||
.try_parsing(true)
|
||||
.separator("__"),
|
||||
);
|
||||
|
||||
let config = builder.build()?;
|
||||
let result: Config = config.try_deserialize()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Get default configuration values
|
||||
fn defaults() -> Self {
|
||||
Config {
|
||||
oidc: OidcConfig {
|
||||
client_id: "your_client_id".to_string(),
|
||||
client_secret: "your_client_secret".to_string(),
|
||||
auth_url: "https://your-provider.com/auth".to_string(),
|
||||
token_url: "https://your-provider.com/token".to_string(),
|
||||
redirect_url: "http://localhost:3000/auth/callback".to_string(),
|
||||
},
|
||||
server: ServerConfig {
|
||||
host: "127.0.0.1".to_string(),
|
||||
port: 3000,
|
||||
},
|
||||
database: DatabaseConfig {
|
||||
url: "sqlite:weight_tracker.db".to_string(),
|
||||
},
|
||||
session: SessionConfig {
|
||||
secret: "your_secret_key_that_is_long_enough_so_the_library_does_not_complain"
|
||||
.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
100
src/handlers.rs
100
src/handlers.rs
@@ -1,8 +1,13 @@
|
||||
use askama::Template;
|
||||
use axum::response::{Html, Redirect};
|
||||
use axum::{Form, extract::Query, extract::State};
|
||||
use axum_sessions::extractors::{ReadableSession, WritableSession};
|
||||
use oauth2::{AuthorizationCode, CsrfToken, PkceCodeChallenge, PkceCodeVerifier, Scope};
|
||||
use axum_session::Session;
|
||||
use axum_session_sqlx::SessionSqlitePool;
|
||||
use oauth2::http;
|
||||
use oauth2::{
|
||||
AuthorizationCode, CsrfToken, HttpRequest, HttpResponse, PkceCodeChallenge, PkceCodeVerifier,
|
||||
Scope, TokenResponse,
|
||||
};
|
||||
use reqwest::Client;
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -15,6 +20,7 @@ pub struct IndexTemplate {
|
||||
#[derive(Deserialize)]
|
||||
pub struct WeightForm {
|
||||
date: String,
|
||||
time: String,
|
||||
weight: f64,
|
||||
}
|
||||
|
||||
@@ -26,7 +32,10 @@ pub async fn index(State(state): State<crate::AppState>) -> Html<String> {
|
||||
Html(template.render().unwrap())
|
||||
}
|
||||
|
||||
pub async fn login(State(state): State<crate::AppState>, mut session: WritableSession) -> Redirect {
|
||||
pub async fn login(
|
||||
State(state): State<crate::AppState>,
|
||||
session: Session<SessionSqlitePool>,
|
||||
) -> Redirect {
|
||||
// Generate PKCE challenge
|
||||
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
|
||||
@@ -40,19 +49,15 @@ pub async fn login(State(state): State<crate::AppState>, mut session: WritableSe
|
||||
.url();
|
||||
|
||||
// Store the CSRF token and PKCE verifier in the session
|
||||
session
|
||||
.insert("csrf_token", csrf_token.secret().clone())
|
||||
.unwrap();
|
||||
session
|
||||
.insert("pkce_verifier", pkce_verifier.secret().clone())
|
||||
.unwrap();
|
||||
session.set("csrf_token", csrf_token.secret().clone());
|
||||
session.set("pkce_verifier", pkce_verifier.secret().clone());
|
||||
|
||||
Redirect::to(auth_url.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub async fn test_login(mut session: WritableSession) -> Redirect {
|
||||
session.insert("user_id", "test-user").unwrap();
|
||||
pub async fn test_login(session: Session<SessionSqlitePool>) -> Redirect {
|
||||
session.set("user_id", "test-user");
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
@@ -65,7 +70,7 @@ pub struct AuthCallbackQuery {
|
||||
pub async fn callback(
|
||||
State(state): State<crate::AppState>,
|
||||
Query(query): Query<AuthCallbackQuery>,
|
||||
mut session: WritableSession,
|
||||
session: Session<SessionSqlitePool>,
|
||||
) -> Redirect {
|
||||
// Verify CSRF token
|
||||
if let Some(stored_csrf) = session.get::<String>("csrf_token") {
|
||||
@@ -88,77 +93,66 @@ pub async fn callback(
|
||||
.oidc_client
|
||||
.exchange_code(AuthorizationCode::new(query.code))
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request_async(async_http_client)
|
||||
.request_async(&async_http_client)
|
||||
.await;
|
||||
|
||||
match token_result {
|
||||
Ok(token) => {
|
||||
// For OIDC, the ID token contains user info
|
||||
if let Some(id_token) = token.id_token() {
|
||||
// Decode ID token (simplified, in practice you'd verify signature)
|
||||
// For now, assume it's valid and extract sub as user_id
|
||||
let claims = id_token.payload().clone();
|
||||
if let Some(sub) = claims.subject() {
|
||||
session.insert("user_id", sub.to_string()).unwrap();
|
||||
Redirect::to("/")
|
||||
} else {
|
||||
Redirect::to("/?error=no_subject")
|
||||
}
|
||||
} else {
|
||||
Redirect::to("/?error=no_id_token")
|
||||
}
|
||||
// For OIDC, extract user info from token
|
||||
// Using the access token as a simple user identifier
|
||||
let user_id = token.access_token().secret().clone();
|
||||
session.set("user_id", user_id);
|
||||
Redirect::to("/")
|
||||
}
|
||||
Err(_) => Redirect::to("/?error=token_exchange_failed"),
|
||||
}
|
||||
}
|
||||
|
||||
// Async HTTP client for oauth2
|
||||
async fn async_http_client(
|
||||
request: oauth2::HttpRequest,
|
||||
) -> Result<oauth2::HttpResponse, reqwest::Error> {
|
||||
async fn async_http_client(req: HttpRequest) -> Result<HttpResponse, reqwest::Error> {
|
||||
let client = Client::new();
|
||||
let method_str = request.method.as_str();
|
||||
let method = reqwest::Method::from_bytes(method_str.as_bytes()).unwrap();
|
||||
let mut req_builder = client.request(method, request.url);
|
||||
|
||||
for (name, value) in request.headers {
|
||||
let Some(header_name_str) = name.and_then(|f| Some(f.as_str().clone())) else {
|
||||
continue;
|
||||
};
|
||||
// Convert http::Method to reqwest::Method
|
||||
let method_str = format!("{}", req.method());
|
||||
let method = reqwest::Method::from_bytes(method_str.as_bytes()).unwrap();
|
||||
|
||||
// Clone the URI before consuming the request
|
||||
let uri = req.uri().clone();
|
||||
|
||||
let mut req_builder = client.request(method, uri.to_string());
|
||||
|
||||
for (name, value) in req.headers() {
|
||||
let header_name =
|
||||
reqwest::header::HeaderName::from_bytes(header_name_str.as_bytes()).unwrap();
|
||||
reqwest::header::HeaderName::from_bytes(name.as_str().as_bytes()).unwrap();
|
||||
let header_value = reqwest::header::HeaderValue::from_bytes(value.as_bytes()).unwrap();
|
||||
req_builder = req_builder.header(header_name, header_value);
|
||||
}
|
||||
|
||||
let response = req_builder.body(request.body).send().await?;
|
||||
let status_code = response.status().as_u16();
|
||||
let body = req.into_body();
|
||||
let response = req_builder.body(body).send().await?;
|
||||
let status_code = response.status();
|
||||
let headers = response.headers().clone();
|
||||
let body = response.bytes().await?;
|
||||
|
||||
// Convert headers
|
||||
let mut oauth_headers = oauth2::http::HeaderMap::new();
|
||||
// Construct an http::Response
|
||||
let mut http_response = http::Response::builder().status(status_code);
|
||||
|
||||
for (k, v) in headers.iter() {
|
||||
let name = oauth2::http::HeaderName::from_bytes(k.as_str().as_bytes()).unwrap();
|
||||
let value = oauth2::http::HeaderValue::from_bytes(v.as_bytes()).unwrap();
|
||||
oauth_headers.insert(name, value);
|
||||
http_response = http_response.header(k, v);
|
||||
}
|
||||
|
||||
Ok(oauth2::HttpResponse {
|
||||
status_code: oauth2::http::StatusCode::from_u16(status_code).unwrap(),
|
||||
headers: oauth_headers,
|
||||
body: body.to_vec(),
|
||||
})
|
||||
Ok(http_response.body(body.to_vec()).unwrap())
|
||||
}
|
||||
|
||||
pub async fn input_post(
|
||||
State(state): State<crate::AppState>,
|
||||
session: ReadableSession,
|
||||
session: Session<SessionSqlitePool>,
|
||||
Form(form): Form<WeightForm>,
|
||||
) -> Result<Html<String>, Redirect> {
|
||||
// Check if user is authenticated
|
||||
if let Some(user_id) = session.get::<String>("user_id") {
|
||||
super::models::insert_weight(&state.pool, &user_id, &form.date, form.weight)
|
||||
let datetime = format!("{}T{}", form.date, form.time);
|
||||
super::models::insert_weight(&state.pool, &user_id, &datetime, form.weight)
|
||||
.await
|
||||
.unwrap();
|
||||
let weights = super::models::get_all_weights(&state.pool)
|
||||
@@ -168,7 +162,7 @@ pub async fn input_post(
|
||||
for weight in weights {
|
||||
html.push_str(&format!(
|
||||
"<p>{}: {} kg by {}</p>\n",
|
||||
weight.date, weight.weight, weight.user_id
|
||||
weight.date, weight.weight, &user_id
|
||||
));
|
||||
}
|
||||
Ok(Html(html))
|
||||
|
||||
45
src/lib.rs
45
src/lib.rs
@@ -1,21 +1,50 @@
|
||||
pub mod handlers;
|
||||
pub mod models;
|
||||
pub mod config;
|
||||
|
||||
use axum::{routing::{get, post}, Router};
|
||||
use axum_sessions::{async_session::MemoryStore, SessionLayer};
|
||||
use oauth2::basic::BasicClient;
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{get, post},
|
||||
};
|
||||
use axum_session::{SessionConfig, SessionLayer, SessionStore};
|
||||
use axum_session_sqlx::SessionSqlitePool;
|
||||
use sqlx::SqlitePool;
|
||||
use tower_http::services::ServeDir;
|
||||
|
||||
pub type OidcClient = oauth2::Client<
|
||||
oauth2::StandardErrorResponse<oauth2::basic::BasicErrorResponseType>,
|
||||
oauth2::StandardTokenResponse<oauth2::EmptyExtraTokenFields, oauth2::basic::BasicTokenType>,
|
||||
oauth2::StandardTokenIntrospectionResponse<
|
||||
oauth2::EmptyExtraTokenFields,
|
||||
oauth2::basic::BasicTokenType,
|
||||
>,
|
||||
oauth2::StandardRevocableToken,
|
||||
oauth2::StandardErrorResponse<oauth2::RevocationErrorResponseType>,
|
||||
oauth2::EndpointSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointNotSet,
|
||||
oauth2::EndpointSet,
|
||||
>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub pool: SqlitePool,
|
||||
pub oidc_client: BasicClient,
|
||||
pub oidc_client: OidcClient,
|
||||
}
|
||||
|
||||
pub fn create_app(state: AppState, session_secret: Vec<u8>) -> Router {
|
||||
let store = MemoryStore::new();
|
||||
let session_layer = SessionLayer::new(store, &session_secret).with_secure(false);
|
||||
pub async fn create_app(state: AppState, session_secret: Vec<u8>, pool: SqlitePool) -> Router {
|
||||
//This Defaults as normal Cookies.
|
||||
//To enable Private cookies for integrity, and authenticity please check the next Example.
|
||||
let session_config = SessionConfig::default()
|
||||
.with_table_name("sessions_table")
|
||||
.with_key(axum_session::Key::from(&session_secret));
|
||||
|
||||
// create SessionStore and initiate the database tables
|
||||
let session_store =
|
||||
SessionStore::<SessionSqlitePool>::new(Some(pool.clone().into()), session_config)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(handlers::index))
|
||||
@@ -23,7 +52,7 @@ pub fn create_app(state: AppState, session_secret: Vec<u8>) -> Router {
|
||||
.route("/auth/callback", get(handlers::callback))
|
||||
.route("/input", post(handlers::input_post))
|
||||
.with_state(state)
|
||||
.layer(session_layer)
|
||||
.layer(SessionLayer::new(session_store))
|
||||
.nest_service("/static", ServeDir::new("static"));
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
45
src/main.rs
45
src/main.rs
@@ -1,36 +1,43 @@
|
||||
use oauth2::{basic::BasicClient, AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl};
|
||||
use std::str::FromStr;
|
||||
|
||||
use sqlx::SqlitePool;
|
||||
use std::env;
|
||||
use weight_tracker::{create_app, AppState};
|
||||
use weight_tracker::{AppState, config::Config, create_app};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let config = Config::load("config.toml").unwrap_or_else(|e| {
|
||||
eprintln!("Failed to load configuration: {}", e);
|
||||
eprintln!("Using default values. Set environment variables prefixed with WEIGHT_TRACKER_ to override.");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
// Set up database
|
||||
let database_url = "sqlite:weight_tracker.db";
|
||||
let pool = SqlitePool::connect(database_url).await.expect("Failed to connect to database");
|
||||
let pool = SqlitePool::connect_with(
|
||||
sqlx::sqlite::SqliteConnectOptions::from_str(&config.database.url)
|
||||
.expect("Could not parse database URL")
|
||||
.create_if_missing(true),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to connect to database");
|
||||
sqlx::migrate!()
|
||||
.run(&pool)
|
||||
.await
|
||||
.expect("Could not run database migrations");
|
||||
|
||||
// Set up OIDC client
|
||||
let client_id = ClientId::new(env::var("OIDC_CLIENT_ID").unwrap_or_else(|_| "your_client_id".to_string()));
|
||||
let client_secret = ClientSecret::new(env::var("OIDC_CLIENT_SECRET").unwrap_or_else(|_| "your_client_secret".to_string()));
|
||||
let auth_url = AuthUrl::new(env::var("OIDC_AUTH_URL").unwrap_or_else(|_| "https://your-provider.com/auth".to_string())).unwrap();
|
||||
let token_url = TokenUrl::new(env::var("OIDC_TOKEN_URL").unwrap_or_else(|_| "https://your-provider.com/token".to_string())).unwrap();
|
||||
let redirect_url = RedirectUrl::new("http://localhost:3000/auth/callback".to_string()).unwrap();
|
||||
let oidc_client = config.oidc.to_client();
|
||||
|
||||
let oidc_client = BasicClient::new(client_id, Some(client_secret), auth_url, Some(token_url))
|
||||
.set_redirect_uri(redirect_url);
|
||||
|
||||
let secret = env::var("SESSION_SECRET").unwrap_or_else(|_| "your_secret_key".to_string()).as_bytes().to_vec();
|
||||
let secret = config.session.secret.as_bytes().to_vec();
|
||||
|
||||
let app_state = AppState {
|
||||
pool,
|
||||
pool: pool.clone(),
|
||||
oidc_client,
|
||||
};
|
||||
|
||||
let app = create_app(app_state, secret);
|
||||
let app = create_app(app_state, secret, pool).await;
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
|
||||
.await
|
||||
.unwrap();
|
||||
let addr = format!("{}:{}", config.server.host, config.server.port);
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
||||
println!("listening on {}", listener.local_addr().unwrap());
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
@@ -1,10 +1,46 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Weight Tracker</title>
|
||||
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
|
||||
|
||||
<script>
|
||||
function fillCurrentDateTime() {
|
||||
// Fill date and time with current values
|
||||
const now = new Date();
|
||||
|
||||
// Format date as YYYY-MM-DD
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getDate()).padStart(2, '0');
|
||||
document.getElementById('date').value = `${year}-${month}-${day}`;
|
||||
|
||||
// Format time as HH:MM
|
||||
const hours = String(now.getHours()).padStart(2, '0');
|
||||
const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
document.getElementById('time').value = `${hours}:${minutes}`;
|
||||
|
||||
// Fill weight with the latest weight from the list
|
||||
const weightElements = document.querySelectorAll('#weights p');
|
||||
if (weightElements.length > 0) {
|
||||
const latestWeightText = weightElements[0].textContent;
|
||||
// Extract weight value from format "YYYY-MM-DD: XX.X kg by username"
|
||||
const match = latestWeightText.match(/(\d+\.?\d*)\s*kg/);
|
||||
if (match) {
|
||||
document.getElementById('weight').value = match[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showInputDialog() {
|
||||
fillCurrentDateTime();
|
||||
document.getElementById('inputDialog').showModal();
|
||||
}
|
||||
</script>
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Weight Tracker</h1>
|
||||
<div id="weights">
|
||||
@@ -12,16 +48,20 @@
|
||||
<p>{{ weight.date }}: {{ weight.weight }} kg by {{ weight.user_id }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<button onclick="document.getElementById('inputDialog').showModal()">Add Weight</button>
|
||||
<button onclick="showInputDialog()">Add Weight</button>
|
||||
<dialog id="inputDialog">
|
||||
<h1>Add Weight</h1>
|
||||
<form hx-post="/input" hx-target="#weights" hx-swap="innerHTML" hx-on:htmx:after-request="document.getElementById('inputDialog').close()">
|
||||
<form hx-post="/input" hx-target="#weights" hx-swap="innerHTML"
|
||||
hx-on:htmx:after-request="document.getElementById('inputDialog').close()">
|
||||
<label for="date">Date:</label>
|
||||
<input type="date" id="date" name="date" required><br>
|
||||
<label for="time">Time:</label>
|
||||
<input type="time" id="time" name="time" required><br>
|
||||
<label for="weight">Weight (kg):</label>
|
||||
<input type="number" step="0.1" id="weight" name="weight" required><br>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</dialog>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,20 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Add Weight</title>
|
||||
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Add Weight</h1>
|
||||
<form hx-post="/input" hx-target="#result" hx-swap="innerHTML">
|
||||
<label for="date">Date:</label>
|
||||
<input type="date" id="date" name="date" required><br>
|
||||
<label for="weight">Weight (kg):</label>
|
||||
<input type="number" step="0.1" id="weight" name="weight" required><br>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
<div id="result"></div>
|
||||
<a href="/">Back to Tracker</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -18,8 +18,8 @@ async fn make_app() -> axum::Router {
|
||||
Some(TokenUrl::new("http://localhost/token".into()).unwrap()),
|
||||
);
|
||||
|
||||
let state = AppState { pool, oidc_client };
|
||||
create_app(state, b"01234567890123456789012345678901".to_vec())
|
||||
let state = AppState { pool: pool.clone(), oidc_client };
|
||||
create_app(state, b"01234567890123456789012345678901".to_vec(), pool).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
Reference in New Issue
Block a user