feat: timezone support and setting

This commit is contained in:
Per Stark
2025-01-27 14:44:37 +01:00
parent 9a3a8f3a1e
commit d04f3faba5
9 changed files with 130 additions and 9 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ config.yaml
flake.nix flake.nix
/target target
.aider .aider
.aider.chat.history.md .aider.input.history .aider.tags.cache.v3 .aider.tags.cache.v3/cache.db .aider.chat.history.md .aider.input.history .aider.tags.cache.v3 .aider.tags.cache.v3/cache.db
data data
Generated
+22
View File
@@ -952,6 +952,27 @@ dependencies = [
"windows-targets", "windows-targets",
] ]
[[package]]
name = "chrono-tz"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c6ac4f2c0bf0f44e9161aec9675e1050aa4a530663c4a9e37e108fa948bca9f"
dependencies = [
"chrono",
"chrono-tz-build",
"phf",
]
[[package]]
name = "chrono-tz-build"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e94fea34d77a245229e7746bd2beb786cd2a896f306ff491fb8cecb3074b10a7"
dependencies = [
"parse-zoneinfo",
"phf_codegen",
]
[[package]] [[package]]
name = "chumsky" name = "chumsky"
version = "0.9.3" version = "0.9.3"
@@ -5894,6 +5915,7 @@ dependencies = [
"axum_session_surreal", "axum_session_surreal",
"axum_typed_multipart", "axum_typed_multipart",
"chrono", "chrono",
"chrono-tz",
"config", "config",
"futures", "futures",
"lettre", "lettre",
+1
View File
@@ -13,6 +13,7 @@ axum_session_auth = "0.14.1"
axum_session_surreal = "0.2.1" axum_session_surreal = "0.2.1"
axum_typed_multipart = "0.12.1" axum_typed_multipart = "0.12.1"
chrono = { version = "0.4.39", features = ["serde"] } chrono = { version = "0.4.39", features = ["serde"] }
chrono-tz = "0.10.1"
config = "0.15.4" config = "0.15.4"
futures = "0.3.31" futures = "0.3.31"
lettre = { version = "0.11.11", features = ["rustls-tls"] } lettre = { version = "0.11.11", features = ["rustls-tls"] }
+3 -2
View File
@@ -1,7 +1,7 @@
use axum::{ use axum::{
extract::DefaultBodyLimit, extract::DefaultBodyLimit,
middleware::from_fn_with_state, middleware::from_fn_with_state,
routing::{delete, get, post}, routing::{delete, get, patch, post},
Router, Router,
}; };
use axum_session::{SessionConfig, SessionLayer, SessionStore}; use axum_session::{SessionConfig, SessionLayer, SessionStore};
@@ -27,7 +27,7 @@ use zettle_db::{
queue_length::queue_length_handler, queue_length::queue_length_handler,
}, },
html::{ html::{
account::{delete_account, set_api_key, show_account_page}, account::{delete_account, set_api_key, show_account_page, update_timezone},
admin_panel::show_admin_panel, admin_panel::show_admin_panel,
documentation::index::show_documentation_index, documentation::index::show_documentation_index,
gdpr::{accept_gdpr, deny_gdpr}, gdpr::{accept_gdpr, deny_gdpr},
@@ -173,6 +173,7 @@ fn html_routes(
.route("/account", get(show_account_page)) .route("/account", get(show_account_page))
.route("/admin", get(show_admin_panel)) .route("/admin", get(show_admin_panel))
.route("/set-api-key", post(set_api_key)) .route("/set-api-key", post(set_api_key))
.route("/update-timezone", patch(update_timezone))
.route("/delete-account", delete(delete_account)) .route("/delete-account", delete(delete_account))
.route( .route(
"/signup", "/signup",
+54 -3
View File
@@ -2,10 +2,12 @@ use axum::{
extract::State, extract::State,
http::{StatusCode, Uri}, http::{StatusCode, Uri},
response::{IntoResponse, Redirect}, response::{IntoResponse, Redirect},
Form,
}; };
use axum_htmx::HxRedirect; use axum_htmx::HxRedirect;
use axum_session_auth::AuthSession; use axum_session_auth::AuthSession;
use axum_session_surreal::SessionSurrealPool; use axum_session_surreal::SessionSurrealPool;
use chrono_tz::TZ_VARIANTS;
use surrealdb::{engine::any::Any, Surreal}; use surrealdb::{engine::any::Any, Surreal};
use crate::{ use crate::{
@@ -18,7 +20,8 @@ use crate::{
use super::render_block; use super::render_block;
page_data!(AccountData, "auth/account_settings.html", { page_data!(AccountData, "auth/account_settings.html", {
user: User user: User,
timezones: Vec<String>
}); });
pub async fn show_account_page( pub async fn show_account_page(
@@ -31,9 +34,11 @@ pub async fn show_account_page(
None => return Ok(Redirect::to("/").into_response()), None => return Ok(Redirect::to("/").into_response()),
}; };
let timezones = TZ_VARIANTS.iter().map(|tz| tz.to_string()).collect();
let output = render_template( let output = render_template(
AccountData::template_name(), AccountData::template_name(),
AccountData { user }, AccountData { user, timezones },
state.templates.clone(), state.templates.clone(),
)?; )?;
@@ -67,7 +72,10 @@ pub async fn set_api_key(
let output = render_block( let output = render_block(
AccountData::template_name(), AccountData::template_name(),
"api_key_section", "api_key_section",
AccountData { user: updated_user }, AccountData {
user: updated_user,
timezones: vec![],
},
state.templates.clone(), state.templates.clone(),
)?; )?;
@@ -94,3 +102,46 @@ pub async fn delete_account(
Ok((HxRedirect::from(Uri::from_static("/")), StatusCode::OK).into_response()) Ok((HxRedirect::from(Uri::from_static("/")), StatusCode::OK).into_response())
} }
#[derive(Deserialize)]
pub struct UpdateTimezoneForm {
timezone: String,
}
pub async fn update_timezone(
State(state): State<AppState>,
auth: AuthSession<User, String, SessionSurrealPool<Any>, Surreal<Any>>,
Form(form): Form<UpdateTimezoneForm>,
) -> Result<impl IntoResponse, HtmlError> {
let user = match &auth.current_user {
Some(user) => user,
None => return Ok(Redirect::to("/").into_response()),
};
User::update_timezone(&user.id, &form.timezone, &state.surreal_db_client)
.await
.map_err(|e| HtmlError::new(e, state.templates.clone()))?;
auth.cache_clear_user(user.id.to_string());
// Update the user's API key
let updated_user = User {
timezone: form.timezone,
..user.clone()
};
let timezones = TZ_VARIANTS.iter().map(|tz| tz.to_string()).collect();
// Render the API key section block
let output = render_block(
AccountData::template_name(),
"timezone_section",
AccountData {
user: updated_user,
timezones,
},
state.templates.clone(),
)?;
Ok(output.into_response())
}
+9 -1
View File
@@ -18,6 +18,7 @@ use super::{render_block, render_template};
pub struct SignupParams { pub struct SignupParams {
pub email: String, pub email: String,
pub password: String, pub password: String,
pub timezone: String,
} }
#[derive(Serialize)] #[derive(Serialize)]
@@ -55,7 +56,14 @@ pub async fn process_signup_and_show_verification(
auth: AuthSession<User, String, SessionSurrealPool<Any>, Surreal<Any>>, auth: AuthSession<User, String, SessionSurrealPool<Any>, Surreal<Any>>,
Form(form): Form<SignupParams>, Form(form): Form<SignupParams>,
) -> Result<impl IntoResponse, HtmlError> { ) -> Result<impl IntoResponse, HtmlError> {
let user = match User::create_new(form.email, form.password, &state.surreal_db_client).await { let user = match User::create_new(
form.email,
form.password,
&state.surreal_db_client,
form.timezone,
)
.await
{
Ok(user) => user, Ok(user) => user,
Err(e) => { Err(e) => {
tracing::error!("{:?}", e); tracing::error!("{:?}", e);
+19 -2
View File
@@ -16,7 +16,9 @@ stored_object!(User, "user", {
password: String, password: String,
anonymous: bool, anonymous: bool,
api_key: Option<String>, api_key: Option<String>,
admin: bool admin: bool,
#[serde(default)]
timezone: String
}); });
#[async_trait] #[async_trait]
@@ -44,6 +46,7 @@ impl User {
email: String, email: String,
password: String, password: String,
db: &SurrealDbClient, db: &SurrealDbClient,
timezone: String,
) -> Result<Self, AppError> { ) -> Result<Self, AppError> {
// verify that the application allows new creations // verify that the application allows new creations
let systemsettings = SystemSettings::get_current(db).await?; let systemsettings = SystemSettings::get_current(db).await?;
@@ -64,7 +67,8 @@ impl User {
admin = $count < 1, // Changed from == 0 to < 1 admin = $count < 1, // Changed from == 0 to < 1
anonymous = false, anonymous = false,
created_at = $created_at, created_at = $created_at,
updated_at = $updated_at", updated_at = $updated_at,
timezone = $timezone",
) )
.bind(("table", "user")) .bind(("table", "user"))
.bind(("id", id)) .bind(("id", id))
@@ -72,6 +76,7 @@ impl User {
.bind(("password", password)) .bind(("password", password))
.bind(("created_at", now)) .bind(("created_at", now))
.bind(("updated_at", now)) .bind(("updated_at", now))
.bind(("timezone", timezone))
.await? .await?
.take(1)?; .take(1)?;
@@ -214,4 +219,16 @@ impl User {
Ok(items) Ok(items)
} }
pub async fn update_timezone(
user_id: &str,
timezone: &str,
db: &Surreal<Any>,
) -> Result<(), AppError> {
db.query("UPDATE type::thing('user', $user_id) SET timezone = $timezone")
.bind(("table_name", User::table_name()))
.bind(("user_id", user_id.to_string()))
.bind(("timezone", timezone.to_string()))
.await?;
Ok(())
}
} }
+15
View File
@@ -14,6 +14,7 @@
<input type="email" name="email" value="{{ user.email }}" class="input text-primary-content input-bordered w-full" <input type="email" name="email" value="{{ user.email }}" class="input text-primary-content input-bordered w-full"
disabled /> disabled />
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label">
<span class="label-text">API key</span> <span class="label-text">API key</span>
@@ -33,6 +34,20 @@
{% endif %} {% endif %}
{% endblock %} {% endblock %}
</div> </div>
<div class="form-control mt-4">
<label class="label">
<span class="label-text">Timezone</span>
</label>
{% block timezone_section %}
<select name="timezone" class="select w-full" hx-patch="/update-timezone" hx-swap="outerHTML">
{% for tz in timezones %}
<option value="{{ tz }}" {% if tz==user.timezone %}selected{% endif %}>{{ tz }}</option>
{% endfor %}
</select>
{% endblock %}
</div>
<div class="form-control mt-4"> <div class="form-control mt-4">
<button hx-post="/verify-email" class="btn btn-secondary w-full"> <button hx-post="/verify-email" class="btn btn-secondary w-full">
Verify Email Verify Email
+6
View File
@@ -43,6 +43,7 @@
Create Account Create Account
</button> </button>
</div> </div>
<input type="hidden" name="timezone" id="timezone" />
</form> </form>
<div class="divider">OR</div> <div class="divider">OR</div>
@@ -52,4 +53,9 @@
<a href="/signin" hx-boost="true" class="link link-primary">Sign in</a> <a href="/signin" hx-boost="true" class="link link-primary">Sign in</a>
</div> </div>
</div> </div>
<script>
// Detect timezone and set hidden input
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.getElementById("timezone").value = timezone;
</script>
{% endblock %} {% endblock %}