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 {
46 /// `/photo/{sub}` be cached hard and still arrive fresh.46 /// `/photo/{sub}` be cached hard and still arrive fresh.
47 #[serde(default)]47 #[serde(default)]
48 pub photo_version: u64,48 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()
49 }59 }
50 60
51 /// One event off the directory stream. The only thing `/directory/live`61 /// One event off the directory stream. The only thing `/directory/live`
@@ -366,6 +376,7 @@ mod tests {
366 assert_eq!(376 assert_eq!(
367 events,377 events,
368 vec![DirectoryEvent::Profile(DirectoryMember {378 vec![DirectoryEvent::Profile(DirectoryMember {
379+ timezone: default_timezone(),
369 sub: "one".into(),380 sub: "one".into(),
370 email: "one@example.com".into(),381 email: "one@example.com".into(),
371 name: "Ann".into(),382 name: "Ann".into(),
@@ -387,6 +398,7 @@ mod tests {
387 events.extend(parser.feed(&whole.as_bytes()[cut..]));398 events.extend(parser.feed(&whole.as_bytes()[cut..]));
388 assert_eq!(events.len(), 1, "cut at {cut}");399 assert_eq!(events.len(), 1, "cut at {cut}");
389 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {400 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {
401+ timezone: default_timezone(),
390 sub: "two".into(),402 sub: "two".into(),
391 email: "two@example.com".into(),403 email: "two@example.com".into(),
392 name: "Ann".into(),404 name: "Ann".into(),
@@ -403,6 +415,7 @@ mod tests {
403 let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes());415 let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes());
404 assert_eq!(events.len(), 1);416 assert_eq!(events.len(), 1);
405 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {417 assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember {
418+ timezone: default_timezone(),
406 sub: "three".into(),419 sub: "three".into(),
407 email: "three@example.com".into(),420 email: "three@example.com".into(),
408 name: "Ann".into(),421 name: "Ann".into(),
@@ -429,6 +442,7 @@ mod tests {
429 assert_eq!(442 assert_eq!(
430 events[0],443 events[0],
431 DirectoryEvent::Profile(DirectoryMember {444 DirectoryEvent::Profile(DirectoryMember {
445+ timezone: default_timezone(),
432 sub: "four".into(),446 sub: "four".into(),
433 email: "four@example.com".into(),447 email: "four@example.com".into(),
434 name: "Ann".into(),448 name: "Ann".into(),
crates/im-core/src/accounts.rsmodified+37 -6
@@ -20,7 +20,7 @@ use sha2::{Digest, Sha256};
20 use subtle::ConstantTimeEq;20 use subtle::ConstantTimeEq;
21 use time::OffsetDateTime;21 use time::OffsetDateTime;
22 22
23-use crate::model::{Invite, User, UserId};23+use crate::model::{DEFAULT_TIMEZONE, Invite, User, UserId};
24 use crate::store::{self, Result, Store, StoreError, backend};24 use crate::store::{self, Result, Store, StoreError, backend};
25 25
26 /// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second26 /// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second
@@ -392,6 +392,7 @@ pub async fn create_user_from_invite(
392 theme: "light".to_string(),392 theme: "light".to_string(),
393 language: "en".to_string(),393 language: "en".to_string(),
394 ui: "instrument".to_string(),394 ui: "instrument".to_string(),
395+ timezone: DEFAULT_TIMEZONE.to_string(),
395 };396 };
396 let password_hash = hash_password(password)?;397 let password_hash = hash_password(password)?;
397 // The lock is taken only now — the reads above (`invite_by_token`) lock398 // The lock is taken only now — the reads above (`invite_by_token`) lock
@@ -656,7 +657,8 @@ pub async fn verify_login(
656 let mut rows = conn657 let mut rows = conn
657 .query(658 .query(
658 "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \659 "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",
660 turso::params![email],662 turso::params![email],
661 )663 )
662 .await664 .await
@@ -678,6 +680,7 @@ pub async fn verify_login(
678 theme: store::text(&row, 10)?,680 theme: store::text(&row, 10)?,
679 language: store::text(&row, 11)?,681 language: store::text(&row, 11)?,
680 ui: store::text(&row, 12)?,682 ui: store::text(&row, 12)?,
683+ timezone: store::text(&row, 13)?,
681 };684 };
682 let phc = store::text(&row, 3)?;685 let phc = store::text(&row, 3)?;
683 if !verify_password(password, &phc) || user.disabled {686 if !verify_password(password, &phc) || user.disabled {
@@ -750,7 +753,8 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
750 let mut rows = conn753 let mut rows = conn
751 .query(754 .query(
752 "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \755 "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",
754 turso::params![id.to_string()],758 turso::params![id.to_string()],
755 )759 )
756 .await760 .await
@@ -771,6 +775,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
771 theme: store::text(&row, 9)?,775 theme: store::text(&row, 9)?,
772 language: store::text(&row, 10)?,776 language: store::text(&row, 10)?,
773 ui: store::text(&row, 11)?,777 ui: store::text(&row, 11)?,
778+ timezone: store::text(&row, 12)?,
774 }))779 }))
775 }780 }
776 781
@@ -801,7 +806,8 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
801 let mut rows = conn806 let mut rows = conn
802 .query(807 .query(
803 "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \808 "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",
805 (),811 (),
806 )812 )
807 .await813 .await
@@ -821,6 +827,7 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
821 theme: store::text(&row, 9)?,827 theme: store::text(&row, 9)?,
822 language: store::text(&row, 10)?,828 language: store::text(&row, 10)?,
823 ui: store::text(&row, 11)?,829 ui: store::text(&row, 11)?,
830+ timezone: store::text(&row, 12)?,
824 });831 });
825 }832 }
826 Ok(users)833 Ok(users)
@@ -863,11 +870,18 @@ pub async fn set_preferences(
863 theme: &str,870 theme: &str,
864 language: &str,871 language: &str,
865 ui: &str,872 ui: &str,
873+ timezone: &str,
866 ) -> Result<()> {874 ) -> Result<()> {
867 let conn = store.conn.lock().await;875 let conn = store.conn.lock().await;
868 conn.execute(876 conn.execute(
869- "UPDATE users SET theme = ?1, language = ?2, ui = ?3 WHERE id = ?4",877+ "UPDATE users SET theme = ?1, language = ?2, ui = ?3, timezone = ?4 WHERE id = ?5",
870- turso::params![theme.to_string(), language.to_string(), ui.to_string(), user.to_string()],878+ turso::params![
879+ theme.to_string(),
880+ language.to_string(),
881+ ui.to_string(),
882+ timezone.to_string(),
883+ user.to_string()
884+ ],
871 )885 )
872 .await886 .await
873 .map_err(backend)?;887 .map_err(backend)?;
@@ -1430,6 +1444,23 @@ mod tests {
1430 .unwrap();1444 .unwrap();
1431 assert!(!login_blocked(&store, "ann@example.com").await.unwrap());1445 assert!(!login_blocked(&store, "ann@example.com").await.unwrap());
1432 }1446 }
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+
1433 async fn seeded_user(store: &Store, email: &str, name: &str) -> User {1464 async fn seeded_user(store: &Store, email: &str, name: &str) -> User {
1434 let invite = create_invite(store, email, None, false).await.unwrap();1465 let invite = create_invite(store, email, None, false).await.unwrap();
1435 create_user_from_invite(store, invite.expose(), name, "tDLr9!mZQ2xv")1466 create_user_from_invite(store, invite.expose(), name, "tDLr9!mZQ2xv")
crates/im-core/src/model.rsmodified+8 -0
@@ -7,6 +7,11 @@
7 use serde::{Deserialize, Serialize};7 use serde::{Deserialize, Serialize};
8 use time::OffsetDateTime;8 use time::OffsetDateTime;
9 9
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+
10 macro_rules! id_wrapper {15 macro_rules! id_wrapper {
11 ($name:ident, $doc:literal) => {16 ($name:ident, $doc:literal) => {
12 #[doc = $doc]17 #[doc = $doc]
@@ -70,6 +75,9 @@ pub struct User {
70 pub theme: String,75 pub theme: String,
71 pub language: String,76 pub language: String,
72 pub ui: String,77 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,
73 }81 }
74 82
75 /// An outstanding (or spent) invite, as stored. The raw token exists only in83 /// 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(
608 "name": user.name,608 "name": user.name,
609 "admin": user.admin,609 "admin": user.admin,
610 "photo_version": user.photo_version,610 "photo_version": user.photo_version,
611+ "timezone": user.timezone,
611 "exp": expires.unix_timestamp(),612 "exp": expires.unix_timestamp(),
612 })))613 })))
613 }614 }
@@ -727,6 +728,11 @@ mod tests {
727 assert_eq!(active["active"], true);728 assert_eq!(active["active"], true);
728 assert_eq!(active["sub"], id.as_str());729 assert_eq!(active["sub"], id.as_str());
729 assert_eq!(active["admin"], want);730 assert_eq!(active["admin"], want);
731+ assert_eq!(
732+ active["timezone"],
733+ crate::model::DEFAULT_TIMEZONE,
734+ "introspection carries the display timezone"
735+ );
730 }736 }
731 }737 }
732 738
crates/im-core/src/store.rsmodified+12 -1
@@ -50,7 +50,8 @@ CREATE TABLE IF NOT EXISTS users (
50 photo_version INTEGER NOT NULL DEFAULT 0,50 photo_version INTEGER NOT NULL DEFAULT 0,
51 theme TEXT NOT NULL DEFAULT 'light',51 theme TEXT NOT NULL DEFAULT 'light',
52 language TEXT NOT NULL DEFAULT 'en',52 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'
54 );55 );
55 CREATE TABLE IF NOT EXISTS invites (56 CREATE TABLE IF NOT EXISTS invites (
56 token TEXT PRIMARY KEY,57 token TEXT PRIMARY KEY,
@@ -269,6 +270,16 @@ impl Store {
269 // ALTER over the owner precedent: databases born before the270 // ALTER over the owner precedent: databases born before the
270 // column get it here, and every existing row reads NULL until271 // column get it here, and every existing row reads NULL until
271 // its app re-registers.272 // 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+ }
272 if !has_column(&conn, "services", "client_id").await? {283 if !has_column(&conn, "services", "client_id").await? {
273 conn.execute("ALTER TABLE services ADD COLUMN client_id TEXT", ())284 conn.execute("ALTER TABLE services ADD COLUMN client_id TEXT", ())
274 .await285 .await
crates/im-web/src/auth.rsmodified+11 -1
@@ -545,6 +545,7 @@ struct PreferencesForm {
545 theme: Option<String>,545 theme: Option<String>,
546 ui: Option<String>,546 ui: Option<String>,
547 language: Option<String>,547 language: Option<String>,
548+ timezone: Option<String>,
548 }549 }
549 550
550 /// The landing's preferences: three selects, validated against the option551 /// The landing's preferences: three selects, validated against the option
@@ -573,8 +574,17 @@ async fn preferences(cx: &Cx, Form(input): Form<PreferencesForm>) -> Redirect {
573 if language != "en" && language != "tr" {574 if language != "en" && language != "tr" {
574 return see("/?section=preferences&error=bad_language".to_string());575 return see("/?section=preferences&error=bad_language".to_string());
575 }576 }
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+ }
576 let store = &server::app(cx).store;583 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;
578 server::log_event(cx, "preferences_saved", Some(&user.email), None).await;588 server::log_event(cx, "preferences_saved", Some(&user.email), None).await;
579 see("/?section=preferences&ok=preferences".to_string())589 see("/?section=preferences&ok=preferences".to_string())
580 }590 }
crates/im-web/src/directory.rsmodified+92 -1
@@ -30,6 +30,10 @@ pub struct DirectoryMember {
30 pub name: String,30 pub name: String,
31 pub admin: bool,31 pub admin: bool,
32 pub photo_version: u64,32 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,
33 }37 }
34 38
35 impl DirectoryMember {39 impl DirectoryMember {
@@ -41,6 +45,7 @@ impl DirectoryMember {
41 name: user.name.clone(),45 name: user.name.clone(),
42 admin: user.admin,46 admin: user.admin,
43 photo_version: user.photo_version,47 photo_version: user.photo_version,
48+ timezone: user.timezone.clone(),
44 }49 }
45 }50 }
46 }51 }
@@ -249,6 +254,8 @@ mod tests {
249 client_id: String,254 client_id: String,
250 secret: String,255 secret: String,
251 store: Arc<Store>,256 store: Arc<Store>,
257+ /// A handle on the live bus, for asserting what a change announces.
258+ live: tokio::sync::broadcast::Sender<server::LiveEvent>,
252 }259 }
253 260
254 async fn setup() -> Setup {261 async fn setup() -> Setup {
@@ -310,7 +317,7 @@ mod tests {
310 issuer: "http://127.0.0.1:7650".into(),317 issuer: "http://127.0.0.1:7650".into(),
311 services,318 services,
312 },319 },
313- live,320+ live: live.clone(),
314 };321 };
315 let router = Router::builder()322 let router = Router::builder()
316 .discover()323 .discover()
@@ -329,6 +336,7 @@ mod tests {
329 client_id: client_id.to_string(),336 client_id: client_id.to_string(),
330 secret: secret.expose().to_string(),337 secret: secret.expose().to_string(),
331 store,338 store,
339+ live,
332 }340 }
333 }341 }
334 342
@@ -558,6 +566,7 @@ mod tests {
558 client_id,566 client_id,
559 secret,567 secret,
560 store,568 store,
569+ ..
561 } = setup().await;570 } = setup().await;
562 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")571 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
563 .await572 .await
@@ -673,6 +682,7 @@ mod tests {
673 client_id,682 client_id,
674 secret,683 secret,
675 store,684 store,
685+ ..
676 } = setup().await;686 } = setup().await;
677 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")687 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
678 .await688 .await
@@ -854,6 +864,7 @@ mod tests {
854 client_id,864 client_id,
855 secret,865 secret,
856 store,866 store,
867+ ..
857 } = setup().await;868 } = setup().await;
858 // The setup already seeded; a re-boot's seed must be a no-op, even869 // The setup already seeded; a re-boot's seed must be a no-op, even
859 // though `in` is exactly the name the config carries.870 // though `in` is exactly the name the config carries.
@@ -884,6 +895,7 @@ mod tests {
884 client_id,895 client_id,
885 secret,896 secret,
886 store,897 store,
898+ ..
887 } = setup().await;899 } = setup().await;
888 900
889 // No pair, no write.901 // No pair, no write.
@@ -966,6 +978,7 @@ mod tests {
966 client_id,978 client_id,
967 secret,979 secret,
968 store,980 store,
981+ ..
969 } = setup().await;982 } = setup().await;
970 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")983 let ada = im_core::accounts::user_by_email(&store, "ada@example.com")
971 .await984 .await
@@ -1380,4 +1393,82 @@ mod tests {
1380 Some("/login?error=email_change_invalid")1393 Some("/login?error=email_change_invalid")
1381 );1394 );
1382 }1395 }
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+ }
1383 }1474 }
crates/im-web/src/i18n.rsmodified+6 -0
@@ -304,6 +304,8 @@ pub enum Key {
304 ThemeLabel,304 ThemeLabel,
305 UiLabel,305 UiLabel,
306 LanguageLabel,306 LanguageLabel,
307+ TimeZoneLabel,
308+ ErrBadZone,
307 LightOption,309 LightOption,
308 DarkOption,310 DarkOption,
309 InstrumentOption,311 InstrumentOption,
@@ -380,6 +382,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
380 (ErrBadUi, Tr) => "Bu bir arayüz değil.",382 (ErrBadUi, Tr) => "Bu bir arayüz değil.",
381 (ErrBadLanguage, En) => "That is not a language.",383 (ErrBadLanguage, En) => "That is not a language.",
382 (ErrBadLanguage, Tr) => "Bu bir dil değil.",384 (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.",
383 (ErrBadService, En) => {387 (ErrBadService, En) => {
384 "A service needs a key of lowercase letters, digits, or dashes, a name, and an http(s) address."388 "A service needs a key of lowercase letters, digits, or dashes, a name, and an http(s) address."
385 }389 }
@@ -854,6 +858,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
854 (UiLabel, Tr) => "ARAYÜZ",858 (UiLabel, Tr) => "ARAYÜZ",
855 (LanguageLabel, En) => "LANGUAGE",859 (LanguageLabel, En) => "LANGUAGE",
856 (LanguageLabel, Tr) => "DİL",860 (LanguageLabel, Tr) => "DİL",
861+ (TimeZoneLabel, En) => "TIME ZONE",
862+ (TimeZoneLabel, Tr) => "SAAT DİLİMİ",
857 (LightOption, En) => "Light",863 (LightOption, En) => "Light",
858 (LightOption, Tr) => "Açık",864 (LightOption, Tr) => "Açık",
859 (DarkOption, En) => "Dark",865 (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 {
44 "bad_theme" => t(lang, Key::ErrBadTheme),44 "bad_theme" => t(lang, Key::ErrBadTheme),
45 "bad_ui" => t(lang, Key::ErrBadUi),45 "bad_ui" => t(lang, Key::ErrBadUi),
46 "bad_language" => t(lang, Key::ErrBadLanguage),46 "bad_language" => t(lang, Key::ErrBadLanguage),
47+ "bad_zone" => t(lang, Key::ErrBadZone),
47 "bad_service" => t(lang, Key::ErrBadService),48 "bad_service" => t(lang, Key::ErrBadService),
48 "bad_client" => t(lang, Key::ErrBadClient),49 "bad_client" => t(lang, Key::ErrBadClient),
49 "no_such_client" => t(lang, Key::ErrNoSuchClient),50 "no_such_client" => t(lang, Key::ErrNoSuchClient),
@@ -73,6 +74,41 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str {
73 }74 }
74 }75 }
75 76
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+
76 /// The refusal this request carries back, if any. Values come percent-112 /// The refusal this request carries back, if any. Values come percent-
77 /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI.113 /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI.
78 pub fn query_value(query: &str, key: &str) -> Option<String> {114 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 {
715 <option value="tr" selected=(user.language == "tr")>"Türkçe"</option>751 <option value="tr" selected=(user.language == "tr")>"Türkçe"</option>
716 </select>752 </select>
717 </label>753 </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>
718 <button class="auth-submit" type="submit">760 <button class="auth-submit" type="submit">
719 <span class="auth-submit-text">(t(lang, Key::SaveButton))</span>761 <span class="auth-submit-text">(t(lang, Key::SaveButton))</span>
720 </button>762 </button>