forge
Explore
Log in

Don't you dare go Hollow

Timezone setting: im serves it, the directory carries it, iz will read it

Browse files at this commit

509d0e7b19104ad3ae2e1dc82c65e1f38dfe7d9bAhmet Kaan GümüşParent: b163bda
users gains timezone TEXT NOT NULL DEFAULT 'UTC+03:00' — migration-
guarded ALTER, the DEFAULT backfilling every existing row to +3. The
value format is iz's settings select ported verbatim: fixed offsets
'UTC-12:00' through 'UTC+14:00', zero-padded hours, 'UTC' for zero —
both sides must speak identical strings over the directory, so im does
not invent a spelling. User, its three queries (verify_login,
user_by_id, list_users — timezone appended, no index shifts) and
set_preferences expose it.

The introspection answer and DirectoryMember — the web type and the
im-client SDK type — carry timezone; the SDK field defaults to
'UTC+03:00' so rows mirrored before the field existed still read.

The landing's preferences pane gains the TIME ZONE select under the
three it had; the save validates against the option list (bad_zone
otherwise) and — because the timezone rides the directory — announces
the row as a profile frame, the way a name or photo change does.

Tests: default + set-and-read-back at the store, the introspect field,
and the route contract — /directory carries the stored zone, the live
bus announces it, a value outside the select's list is refused whole.
Browser-verified on the scratch server: 27 options (UTC-12:00 … UTC,
UTC+14:00), the select saves and re-renders the stored zone, and
/directory answers with it. Workspace check with zero warnings.
crates/im-client/src/directory.rsmodified+14 -0
@@ -46,6 +46,16 @@ pub struct DirectoryMember {
4646 /// `/photo/{sub}` be cached hard and still arrive fresh.
4747 #[serde(default)]
4848 pub photo_version: u64,
49+ /// The member's display timezone (a fixed offset like "UTC+03:00").
50+ /// Defaulted: rows mirrored before im carried the field still read.
51+ #[serde(default = "default_timezone")]
52+ pub timezone: String,
53+}
54+
55+/// The timezone im starts every account on, and the one this SDK assumes
56+/// when a mirrored row predates the field.
57+fn default_timezone() -> String {
58+ "UTC+03:00".to_string()
4959 }
5060
5161 /// One event off the directory stream. The only thing `/directory/live`
@@ -366,6 +376,7 @@ mod tests {
366376 assert_eq!(
367377 events,
368378 vec![DirectoryEvent::Profile(DirectoryMember {
379+ timezone: default_timezone(),
369380 sub: "one".into(),
370381 email: "one@example.com".into(),
371382 name: "Ann".into(),
@@ -387,6 +398,7 @@ mod tests {
387398 events.extend(parser.feed(&whole.as_bytes()[cut..]));
388399 assert_eq!(events.len(), 1, "cut at {cut}");
389400 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {
401+ timezone: default_timezone(),
390402 sub: "two".into(),
391403 email: "two@example.com".into(),
392404 name: "Ann".into(),
@@ -403,6 +415,7 @@ mod tests {
403415 let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes());
404416 assert_eq!(events.len(), 1);
405417 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {
418+ timezone: default_timezone(),
406419 sub: "three".into(),
407420 email: "three@example.com".into(),
408421 name: "Ann".into(),
@@ -429,6 +442,7 @@ mod tests {
429442 assert_eq!(
430443 events[0],
431444 DirectoryEvent::Profile(DirectoryMember {
445+ timezone: default_timezone(),
432446 sub: "four".into(),
433447 email: "four@example.com".into(),
434448 name: "Ann".into(),
crates/im-core/src/accounts.rsmodified+37 -6
@@ -20,7 +20,7 @@ use sha2::{Digest, Sha256};
2020 use subtle::ConstantTimeEq;
2121 use time::OffsetDateTime;
2222
23-use crate::model::{Invite, User, UserId};
23+use crate::model::{DEFAULT_TIMEZONE, Invite, User, UserId};
2424 use crate::store::{self, Result, Store, StoreError, backend};
2525
2626 /// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second
@@ -392,6 +392,7 @@ pub async fn create_user_from_invite(
392392 theme: "light".to_string(),
393393 language: "en".to_string(),
394394 ui: "instrument".to_string(),
395+ timezone: DEFAULT_TIMEZONE.to_string(),
395396 };
396397 let password_hash = hash_password(password)?;
397398 // The lock is taken only now — the reads above (`invite_by_token`) lock
@@ -656,7 +657,8 @@ pub async fn verify_login(
656657 let mut rows = conn
657658 .query(
658659 "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \
659- photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE email = ?1 COLLATE NOCASE",
660+ photo_mime IS NOT NULL, photo_version, theme, language, ui, timezone \
661+ FROM users WHERE email = ?1 COLLATE NOCASE",
660662 turso::params![email],
661663 )
662664 .await
@@ -678,6 +680,7 @@ pub async fn verify_login(
678680 theme: store::text(&row, 10)?,
679681 language: store::text(&row, 11)?,
680682 ui: store::text(&row, 12)?,
683+ timezone: store::text(&row, 13)?,
681684 };
682685 let phc = store::text(&row, 3)?;
683686 if !verify_password(password, &phc) || user.disabled {
@@ -750,7 +753,8 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
750753 let mut rows = conn
751754 .query(
752755 "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \
753- photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE id = ?1",
756+ photo_mime IS NOT NULL, photo_version, theme, language, ui, timezone \
757+ FROM users WHERE id = ?1",
754758 turso::params![id.to_string()],
755759 )
756760 .await
@@ -771,6 +775,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
771775 theme: store::text(&row, 9)?,
772776 language: store::text(&row, 10)?,
773777 ui: store::text(&row, 11)?,
778+ timezone: store::text(&row, 12)?,
774779 }))
775780 }
776781
@@ -801,7 +806,8 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
801806 let mut rows = conn
802807 .query(
803808 "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \
804- photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users ORDER BY created_at",
809+ photo_mime IS NOT NULL, photo_version, theme, language, ui, timezone \
810+ FROM users ORDER BY created_at",
805811 (),
806812 )
807813 .await
@@ -821,6 +827,7 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
821827 theme: store::text(&row, 9)?,
822828 language: store::text(&row, 10)?,
823829 ui: store::text(&row, 11)?,
830+ timezone: store::text(&row, 12)?,
824831 });
825832 }
826833 Ok(users)
@@ -863,11 +870,18 @@ pub async fn set_preferences(
863870 theme: &str,
864871 language: &str,
865872 ui: &str,
873+ timezone: &str,
866874 ) -> Result<()> {
867875 let conn = store.conn.lock().await;
868876 conn.execute(
869- "UPDATE users SET theme = ?1, language = ?2, ui = ?3 WHERE id = ?4",
870- turso::params![theme.to_string(), language.to_string(), ui.to_string(), user.to_string()],
877+ "UPDATE users SET theme = ?1, language = ?2, ui = ?3, timezone = ?4 WHERE id = ?5",
878+ turso::params![
879+ theme.to_string(),
880+ language.to_string(),
881+ ui.to_string(),
882+ timezone.to_string(),
883+ user.to_string()
884+ ],
871885 )
872886 .await
873887 .map_err(backend)?;
@@ -1430,6 +1444,23 @@ mod tests {
14301444 .unwrap();
14311445 assert!(!login_blocked(&store, "ann@example.com").await.unwrap());
14321446 }
1447+ #[tokio::test]
1448+ async fn timezone_defaults_to_the_family_offset_and_follows_preferences() {
1449+ let store = fixture().await;
1450+ let ann = seeded_user(&store, "ann@example.com", "Ann").await;
1451+ assert_eq!(
1452+ user_by_id(&store, &ann.id).await.unwrap().unwrap().timezone,
1453+ DEFAULT_TIMEZONE,
1454+ "a fresh account — and a migrated row via the DEFAULT — starts on +3"
1455+ );
1456+ set_preferences(&store, &ann.id, "dark", "tr", "ledger", "UTC-05:00")
1457+ .await
1458+ .unwrap();
1459+ let reloaded = user_by_id(&store, &ann.id).await.unwrap().unwrap();
1460+ assert_eq!(reloaded.timezone, "UTC-05:00");
1461+ assert_eq!(reloaded.theme, "dark");
1462+ }
1463+
14331464 async fn seeded_user(store: &Store, email: &str, name: &str) -> User {
14341465 let invite = create_invite(store, email, None, false).await.unwrap();
14351466 create_user_from_invite(store, invite.expose(), name, "tDLr9!mZQ2xv")
crates/im-core/src/model.rsmodified+8 -0
@@ -7,6 +7,11 @@
77 use serde::{Deserialize, Serialize};
88 use time::OffsetDateTime;
99
10+/// The timezone a fresh account — and every row the migration backfills —
11+/// starts on. The value is one of the fixed-offset strings the settings
12+/// select offers (iz's format, carried verbatim over the directory).
13+pub const DEFAULT_TIMEZONE: &str = "UTC+03:00";
14+
1015 macro_rules! id_wrapper {
1116 ($name:ident, $doc:literal) => {
1217 #[doc = $doc]
@@ -70,6 +75,9 @@ pub struct User {
7075 pub theme: String,
7176 pub language: String,
7277 pub ui: String,
78+ /// Display-only fixed offset in iz's spelling ("UTC+03:00", or "UTC"
79+ /// for zero). Apps read it over the directory to render times.
80+ pub timezone: String,
7381 }
7482
7583 /// An outstanding (or spent) invite, as stored. The raw token exists only in
crates/im-core/src/oidc.rsmodified+6 -0
@@ -608,6 +608,7 @@ pub async fn introspect_app_session(
608608 "name": user.name,
609609 "admin": user.admin,
610610 "photo_version": user.photo_version,
611+ "timezone": user.timezone,
611612 "exp": expires.unix_timestamp(),
612613 })))
613614 }
@@ -727,6 +728,11 @@ mod tests {
727728 assert_eq!(active["active"], true);
728729 assert_eq!(active["sub"], id.as_str());
729730 assert_eq!(active["admin"], want);
731+ assert_eq!(
732+ active["timezone"],
733+ crate::model::DEFAULT_TIMEZONE,
734+ "introspection carries the display timezone"
735+ );
730736 }
731737 }
732738
crates/im-core/src/store.rsmodified+12 -1
@@ -50,7 +50,8 @@ CREATE TABLE IF NOT EXISTS users (
5050 photo_version INTEGER NOT NULL DEFAULT 0,
5151 theme TEXT NOT NULL DEFAULT 'light',
5252 language TEXT NOT NULL DEFAULT 'en',
53- ui TEXT NOT NULL DEFAULT 'instrument'
53+ ui TEXT NOT NULL DEFAULT 'instrument',
54+ timezone TEXT NOT NULL DEFAULT 'UTC+03:00'
5455 );
5556 CREATE TABLE IF NOT EXISTS invites (
5657 token TEXT PRIMARY KEY,
@@ -269,6 +270,16 @@ impl Store {
269270 // ALTER over the owner precedent: databases born before the
270271 // column get it here, and every existing row reads NULL until
271272 // its app re-registers.
273+ // The display timezone (iz's fixed-offset spelling): the
274+ // DEFAULT backfills every existing row to UTC+03:00.
275+ if !has_column(&conn, "users", "timezone").await? {
276+ conn.execute(
277+ "ALTER TABLE users ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC+03:00'",
278+ (),
279+ )
280+ .await
281+ .map_err(backend)?;
282+ }
272283 if !has_column(&conn, "services", "client_id").await? {
273284 conn.execute("ALTER TABLE services ADD COLUMN client_id TEXT", ())
274285 .await
crates/im-web/src/auth.rsmodified+11 -1
@@ -545,6 +545,7 @@ struct PreferencesForm {
545545 theme: Option<String>,
546546 ui: Option<String>,
547547 language: Option<String>,
548+ timezone: Option<String>,
548549 }
549550
550551 /// The landing's preferences: three selects, validated against the option
@@ -573,8 +574,17 @@ async fn preferences(cx: &Cx, Form(input): Form<PreferencesForm>) -> Redirect {
573574 if language != "en" && language != "tr" {
574575 return see("/?section=preferences&error=bad_language".to_string());
575576 }
577+ let Some(timezone) = input.timezone.as_deref() else {
578+ return see("/?section=preferences&error=bad_zone".to_string());
579+ };
580+ if !crate::pages::zone_options().contains(&timezone.to_string()) {
581+ return see("/?section=preferences&error=bad_zone".to_string());
582+ }
576583 let store = &server::app(cx).store;
577- im_core::accounts::set_preferences(store, &user.id, theme, language, ui).await?;
584+ im_core::accounts::set_preferences(store, &user.id, theme, language, ui, timezone).await?;
585+ // The timezone rides the directory: registered siblings apply it live,
586+ // the way a name or photo change announces itself.
587+ server::notify_profile(cx, &user.id).await;
578588 server::log_event(cx, "preferences_saved", Some(&user.email), None).await;
579589 see("/?section=preferences&ok=preferences".to_string())
580590 }
crates/im-web/src/directory.rsmodified+92 -1
@@ -30,6 +30,10 @@ pub struct DirectoryMember {
3030 pub name: String,
3131 pub admin: bool,
3232 pub photo_version: u64,
33+ /// The member's display timezone, iz's fixed-offset spelling. This
34+ /// side only serializes — the field is always written — so the serde
35+ /// default lives on the SDK's reading half.
36+ pub timezone: String,
3337 }
3438
3539 impl DirectoryMember {
@@ -41,6 +45,7 @@ impl DirectoryMember {
4145 name: user.name.clone(),
4246 admin: user.admin,
4347 photo_version: user.photo_version,
48+ timezone: user.timezone.clone(),
4449 }
4550 }
4651 }
@@ -249,6 +254,8 @@ mod tests {
249254 client_id: String,
250255 secret: String,
251256 store: Arc<Store>,
257+ /// A handle on the live bus, for asserting what a change announces.
258+ live: tokio::sync::broadcast::Sender<server::LiveEvent>,
252259 }
253260
254261 async fn setup() -> Setup {
@@ -310,7 +317,7 @@ mod tests {
310317 issuer: "http://127.0.0.1:7650".into(),
311318 services,
312319 },
313- live,
320+ live: live.clone(),
314321 };
315322 let router = Router::builder()
316323 .discover()
@@ -329,6 +336,7 @@ mod tests {
329336 client_id: client_id.to_string(),
330337 secret: secret.expose().to_string(),
331338 store,
339+ live,
332340 }
333341 }
334342
@@ -558,6 +566,7 @@ mod tests {
558566 client_id,
559567 secret,
560568 store,
569+ ..
561570 } = setup().await;
562571 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
563572 .await
@@ -673,6 +682,7 @@ mod tests {
673682 client_id,
674683 secret,
675684 store,
685+ ..
676686 } = setup().await;
677687 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
678688 .await
@@ -854,6 +864,7 @@ mod tests {
854864 client_id,
855865 secret,
856866 store,
867+ ..
857868 } = setup().await;
858869 // The setup already seeded; a re-boot's seed must be a no-op, even
859870 // though `in` is exactly the name the config carries.
@@ -884,6 +895,7 @@ mod tests {
884895 client_id,
885896 secret,
886897 store,
898+ ..
887899 } = setup().await;
888900
889901 // No pair, no write.
@@ -966,6 +978,7 @@ mod tests {
966978 client_id,
967979 secret,
968980 store,
981+ ..
969982 } = setup().await;
970983 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
971984 .await
@@ -1380,4 +1393,82 @@ mod tests {
13801393 Some("/login?error=email_change_invalid")
13811394 );
13821395 }
1396+
1397+ #[tokio::test]
1398+ async fn timezone_rides_the_directory_and_the_live_frame() {
1399+ let Setup {
1400+ router,
1401+ client_id,
1402+ secret,
1403+ store,
1404+ live,
1405+ } = setup().await;
1406+ let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
1407+ .await
1408+ .unwrap()
1409+ .unwrap();
1410+ let session = im_core::sessions::create_session(&store, &ada.id, &Default::default())
1411+ .await
1412+ .unwrap();
1413+ let cookie = format!("{SESSION_COOKIE}={}", session.expose());
1414+
1415+ // The entry carries the family default before anyone touches it.
1416+ let (status, body) = get(&router, Some(basic(&client_id, &secret))).await;
1417+ assert_eq!(status, StatusCode::OK);
1418+ let roster = serde_json::from_str::<serde_json::Value>(&body).unwrap();
1419+ assert_eq!(roster[0]["timezone"], "UTC+03:00");
1420+
1421+ // Saving preferences with a new timezone refuses a value outside
1422+ // the select's list, and announces a real change as a profile
1423+ // frame — the same ride a name or photo change takes.
1424+ let mut rx = live.subscribe();
1425+ let (status, location, _) = post_form(
1426+ &router,
1427+ "/preferences",
1428+ "theme=light&ui=instrument&language=en&timezone=UTC-05:00",
1429+ Some(&cookie),
1430+ )
1431+ .await;
1432+ assert_eq!(status, StatusCode::SEE_OTHER);
1433+ assert_eq!(
1434+ location.as_deref(),
1435+ Some("/?section=preferences&ok=preferences")
1436+ );
1437+ match rx.try_recv().unwrap() {
1438+ server::LiveEvent::Profile(member) => {
1439+ assert_eq!(member.timezone, "UTC-05:00");
1440+ }
1441+ other => panic!("a profile change announces the row, got {other:?}"),
1442+ }
1443+
1444+ // And the roster reads the stored zone back.
1445+ let (_, body) = get(&router, Some(basic(&client_id, &secret))).await;
1446+ let roster = serde_json::from_str::<serde_json::Value>(&body).unwrap();
1447+ let ada_entry = roster
1448+ .as_array()
1449+ .unwrap()
1450+ .iter()
1451+ .find(|member| member["email"] == "ada@example.com")
1452+ .unwrap();
1453+ assert_eq!(ada_entry["timezone"], "UTC-05:00");
1454+
1455+ // A value the select never offers is refused whole.
1456+ let (status, location, _) = post_form(
1457+ &router,
1458+ "/preferences",
1459+ "theme=light&ui=instrument&language=en&timezone=Mars/Olympus",
1460+ Some(&cookie),
1461+ )
1462+ .await;
1463+ assert_eq!(status, StatusCode::SEE_OTHER);
1464+ assert_eq!(
1465+ location.as_deref(),
1466+ Some("/?section=preferences&error=bad_zone")
1467+ );
1468+ let reloaded = im_core::accounts::user_by_id(&store, &ada.id)
1469+ .await
1470+ .unwrap()
1471+ .unwrap();
1472+ assert_eq!(reloaded.timezone, "UTC-05:00", "nothing half-written");
1473+ }
13831474 }
crates/im-web/src/i18n.rsmodified+6 -0
@@ -304,6 +304,8 @@ pub enum Key {
304304 ThemeLabel,
305305 UiLabel,
306306 LanguageLabel,
307+ TimeZoneLabel,
308+ ErrBadZone,
307309 LightOption,
308310 DarkOption,
309311 InstrumentOption,
@@ -380,6 +382,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
380382 (ErrBadUi, Tr) => "Bu bir arayüz değil.",
381383 (ErrBadLanguage, En) => "That is not a language.",
382384 (ErrBadLanguage, Tr) => "Bu bir dil değil.",
385+ (ErrBadZone, En) => "That is not a time zone.",
386+ (ErrBadZone, Tr) => "Bu bir saat dilimi değil.",
383387 (ErrBadService, En) => {
384388 "A service needs a key of lowercase letters, digits, or dashes, a name, and an http(s) address."
385389 }
@@ -854,6 +858,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
854858 (UiLabel, Tr) => "ARAYÜZ",
855859 (LanguageLabel, En) => "LANGUAGE",
856860 (LanguageLabel, Tr) => "DİL",
861+ (TimeZoneLabel, En) => "TIME ZONE",
862+ (TimeZoneLabel, Tr) => "SAAT DİLİMİ",
857863 (LightOption, En) => "Light",
858864 (LightOption, Tr) => "Açık",
859865 (DarkOption, En) => "Dark",
crates/im-web/src/pages.rsmodified+42 -0
@@ -44,6 +44,7 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str {
4444 "bad_theme" => t(lang, Key::ErrBadTheme),
4545 "bad_ui" => t(lang, Key::ErrBadUi),
4646 "bad_language" => t(lang, Key::ErrBadLanguage),
47+ "bad_zone" => t(lang, Key::ErrBadZone),
4748 "bad_service" => t(lang, Key::ErrBadService),
4849 "bad_client" => t(lang, Key::ErrBadClient),
4950 "no_such_client" => t(lang, Key::ErrNoSuchClient),
@@ -73,6 +74,41 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str {
7374 }
7475 }
7576
77+/// The offsets the timezone field offers, `"UTC-12:00"` through
78+/// `"UTC+14:00"` — iz's settings select, ported verbatim so both sides
79+/// speak the same values over the directory. Fixed offsets: no tz database
80+/// rides along for what a display label needs, and `"UTC"` stands for
81+/// +00:00.
82+pub(crate) fn zone_options() -> Vec<String> {
83+ (-12..=14)
84+ .map(|hour: i32| {
85+ if hour == 0 {
86+ "UTC".to_string()
87+ } else {
88+ format!(
89+ "UTC{}{:02}:00",
90+ if hour > 0 { "+" } else { "-" },
91+ hour.abs()
92+ )
93+ }
94+ })
95+ .collect()
96+}
97+
98+/// The timezone `<option>` list, pre-selected to the account's stored one.
99+pub(crate) fn timezone_select(current: &str) -> String {
100+ zone_options()
101+ .into_iter()
102+ .map(|zone| {
103+ format!(
104+ r#"<option value="{z}"{sel}>{z}</option>"#,
105+ z = zone,
106+ sel = if zone == current { r#" selected="selected""# } else { "" },
107+ )
108+ })
109+ .collect::<String>()
110+}
111+
76112 /// The refusal this request carries back, if any. Values come percent-
77113 /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI.
78114 pub fn query_value(query: &str, key: &str) -> Option<String> {
@@ -715,6 +751,12 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
715751 <option value="tr" selected=(user.language == "tr")>"Türkçe"</option>
716752 </select>
717753 </label>
754+ <label class="auth-field">
755+ <span class="auth-label">(t(lang, Key::TimeZoneLabel))</span>
756+ <select class="auth-input" name="timezone">
757+ (topcoat::view::Unescaped::new_unchecked(timezone_select(&user.timezone)))
758+ </select>
759+ </label>
718760 <button class="auth-submit" type="submit">
719761 <span class="auth-submit-text">(t(lang, Key::SaveButton))</span>
720762 </button>