an address is fixable at last, from either side of the door: the admin panel's users section grows a direct email edit on every row — applied outright, because an unreachable mailbox is exactly what the rescue is for, and email is contact metadata, not a key, so the id stays and sessions, app tokens and OIDC claims read the new address on their next read — while a person asking on their own account, from the landing's profile card, must be vouched for at both ends: one confirmation mail to the address being left and one to the address being gained, the change applying only when both mailboxes click, either order, each link single-use on a reset-length clock, the gained address re-checked for another owner at the moment it applies; the pair lives in a new email_changes table mirrored into im-migrate, a fresh ask retires the pair before it, and the confirm card is a POST — never a link a mail scanner could pre-fetch — that any mailbox holder can press, signed in or not
Browse files at this commitc5b40ed38d4beb843e69b96f977fdad73264b4ddParent: 58623169 changed files +1048 -5
- crates/im-core/src/accounts.rs +458 -0
- crates/im-core/src/store.rs +13 -0
- crates/im-migrate/src/main.rs +12 -0
- crates/im-web/src/admin.rs +50 -5
- crates/im-web/src/auth.rs +111 -0
- crates/im-web/src/directory.rs +218 -0
- crates/im-web/src/i18n.rs +92 -0
- crates/im-web/src/mailer.rs +19 -0
- crates/im-web/src/pages.rs +75 -0
crates/im-core/src/accounts.rsmodified+458 -0
| @@ -77,6 +77,12 @@ pub enum AccountError { | |||
| 77 | InviteExpired, | 77 | InviteExpired, |
| 78 | #[error("an account with this address already exists")] | 78 | #[error("an account with this address already exists")] |
| 79 | EmailTaken, | 79 | EmailTaken, |
| 80 | + #[error("that address doesn't look valid")] | ||
| 81 | + InvalidEmail, | ||
| 82 | + #[error("that's already your address")] | ||
| 83 | + SameEmail, | ||
| 84 | + #[error("this email-change link is not valid")] | ||
| 85 | + EmailChangeInvalid, | ||
| 80 | #[error("password: {0}")] | 86 | #[error("password: {0}")] |
| 81 | Password(#[from] PasswordProblem), | 87 | Password(#[from] PasswordProblem), |
| 82 | #[error("password hashing failed: {0}")] | 88 | #[error("password hashing failed: {0}")] |
| @@ -864,6 +870,251 @@ pub async fn set_preferences( | |||
| 864 | Ok(()) | 870 | Ok(()) |
| 865 | } | 871 | } |
| 866 | 872 | ||
| 873 | +/// Normalizes an address the way the login path reads it — trimmed and | ||
| 874 | +/// lowercased — and refuses what no mail could ever reach. | ||
| 875 | +fn normalize_email(email: &str) -> std::result::Result<String, AccountError> { | ||
| 876 | + let email = email.trim().to_lowercase(); | ||
| 877 | + let Some((local, domain)) = email.split_once('@') else { | ||
| 878 | + return Err(AccountError::InvalidEmail); | ||
| 879 | + }; | ||
| 880 | + if local.is_empty() || domain.is_empty() || !domain.contains('.') { | ||
| 881 | + return Err(AccountError::InvalidEmail); | ||
| 882 | + } | ||
| 883 | + Ok(email) | ||
| 884 | +} | ||
| 885 | + | ||
| 886 | +/// Rewrites a user's address in place — the admin panel's direct rescue | ||
| 887 | +/// for a typo'd or unreachable mailbox. Email is contact metadata, not a | ||
| 888 | +/// key: the id stays, and sessions, app tokens and OIDC claims read the | ||
| 889 | +/// new address live. The address is normalized the way the login path | ||
| 890 | +/// reads it, an address another account owns is refused, and setting the | ||
| 891 | +/// address the account already carries quietly succeeds. | ||
| 892 | +pub async fn set_email(store: &Store, user: &UserId, email: &str) -> std::result::Result<(), AccountError> { | ||
| 893 | + let email = normalize_email(email)?; | ||
| 894 | + if let Some(other) = user_by_email(store, &email).await? { | ||
| 895 | + if other.id != *user { | ||
| 896 | + return Err(AccountError::EmailTaken); | ||
| 897 | + } | ||
| 898 | + } | ||
| 899 | + let conn = store.conn.lock().await; | ||
| 900 | + conn.execute( | ||
| 901 | + "UPDATE users SET email = ?1 WHERE id = ?2", | ||
| 902 | + turso::params![email, user.to_string()], | ||
| 903 | + ) | ||
| 904 | + .await | ||
| 905 | + .map_err(backend)?; | ||
| 906 | + Ok(()) | ||
| 907 | +} | ||
| 908 | + | ||
| 909 | +/// What a confirmed pair of mailboxes means: one side agreed and the | ||
| 910 | +/// change waits, or both agreed and the address is rewritten. | ||
| 911 | +#[derive(Debug)] | ||
| 912 | +pub enum EmailChangeConfirmed { | ||
| 913 | + /// One mailbox confirmed; the other address still owes its click. | ||
| 914 | + AwaitOther, | ||
| 915 | + /// Both confirmed; the carried `User` reads the new address. | ||
| 916 | + Applied(User), | ||
| 917 | +} | ||
| 918 | + | ||
| 919 | +/// Asks for an address change on one's own account: one pending row | ||
| 920 | +/// carrying two independent tokens, one mailed to the address being left | ||
| 921 | +/// and one to the address being gained. The change applies only when both | ||
| 922 | +/// mailboxes confirm, in either order. Asking again retires the previous | ||
| 923 | +/// pair — the newest mails are the only doors — and an address another | ||
| 924 | +/// account owns is refused at the ask. | ||
| 925 | +pub async fn request_email_change( | ||
| 926 | + store: &Store, | ||
| 927 | + user: &UserId, | ||
| 928 | + new_email: &str, | ||
| 929 | +) -> std::result::Result<(Token, Token), AccountError> { | ||
| 930 | + let me = user_by_id(store, user) | ||
| 931 | + .await? | ||
| 932 | + .ok_or_else(|| AccountError::Backend("email change: user vanished".into()))?; | ||
| 933 | + let old_email = normalize_email(&me.email)?; | ||
| 934 | + let new_email = normalize_email(new_email)?; | ||
| 935 | + if new_email == old_email { | ||
| 936 | + return Err(AccountError::SameEmail); | ||
| 937 | + } | ||
| 938 | + if let Some(other) = user_by_email(store, &new_email).await? { | ||
| 939 | + if other.id != *user { | ||
| 940 | + return Err(AccountError::EmailTaken); | ||
| 941 | + } | ||
| 942 | + } | ||
| 943 | + let old_token = Token::mint(); | ||
| 944 | + let new_token = Token::mint(); | ||
| 945 | + let now = store::now(); | ||
| 946 | + // The reset link's clock: the same policy knob, the same urgency. | ||
| 947 | + let expires = now + time::Duration::minutes(crate::settings::reset_minutes(store).await?); | ||
| 948 | + let conn = store.conn.lock().await; | ||
| 949 | + conn.execute( | ||
| 950 | + "DELETE FROM email_changes WHERE user_id = ?1 AND used_at IS NULL", | ||
| 951 | + turso::params![user.to_string()], | ||
| 952 | + ) | ||
| 953 | + .await | ||
| 954 | + .map_err(backend)?; | ||
| 955 | + conn.execute( | ||
| 956 | + "INSERT INTO email_changes (old_token_hash, new_token_hash, user_id, old_email, \ | ||
| 957 | + new_email, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | ||
| 958 | + turso::params![ | ||
| 959 | + old_token.hash(), | ||
| 960 | + new_token.hash(), | ||
| 961 | + user.to_string(), | ||
| 962 | + old_email, | ||
| 963 | + new_email, | ||
| 964 | + store::stamp(now)?, | ||
| 965 | + store::stamp(expires)?, | ||
| 966 | + ], | ||
| 967 | + ) | ||
| 968 | + .await | ||
| 969 | + .map_err(backend)?; | ||
| 970 | + Ok((old_token, new_token)) | ||
| 971 | +} | ||
| 972 | + | ||
| 973 | +/// Confirms one end of a pending address change. The first mailbox to | ||
| 974 | +/// agree only marks its side; the second completes the pair, and the | ||
| 975 | +/// gained address is re-checked at that moment — someone may have | ||
| 976 | +/// registered it while the mails travelled. That refusal leaves the old | ||
| 977 | +/// address in place and tears the dead pair down. Every link is | ||
| 978 | +/// single-use and dies at expiry. | ||
| 979 | +pub async fn confirm_email_change( | ||
| 980 | + store: &Store, | ||
| 981 | + token: &str, | ||
| 982 | +) -> std::result::Result<EmailChangeConfirmed, AccountError> { | ||
| 983 | + let hash = hash_token(token); | ||
| 984 | + // Short-held read first: the row says which side clicked and whether | ||
| 985 | + // the pair may still complete. | ||
| 986 | + let row = { | ||
| 987 | + let conn = store.conn.lock().await; | ||
| 988 | + let mut rows = conn | ||
| 989 | + .query( | ||
| 990 | + "SELECT old_token_hash, new_token_hash, user_id, old_email, new_email, \ | ||
| 991 | + expires_at, used_at, confirmed_old_at, confirmed_new_at \ | ||
| 992 | + FROM email_changes WHERE old_token_hash = ?1 OR new_token_hash = ?1", | ||
| 993 | + turso::params![hash.clone()], | ||
| 994 | + ) | ||
| 995 | + .await | ||
| 996 | + .map_err(backend)?; | ||
| 997 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 998 | + return Err(AccountError::EmailChangeInvalid); | ||
| 999 | + }; | ||
| 1000 | + ( | ||
| 1001 | + store::text(&row, 0)?, | ||
| 1002 | + store::text(&row, 1)?, | ||
| 1003 | + UserId::from(store::text(&row, 2)?), | ||
| 1004 | + store::text(&row, 3)?, | ||
| 1005 | + store::text(&row, 4)?, | ||
| 1006 | + store::parse_stamp(&store::text(&row, 5)?)?, | ||
| 1007 | + store::opt_text(&row, 6)?.is_some(), | ||
| 1008 | + store::opt_text(&row, 7)?.is_some(), | ||
| 1009 | + store::opt_text(&row, 8)?.is_some(), | ||
| 1010 | + ) | ||
| 1011 | + }; | ||
| 1012 | + let (old_hash, _new_hash, user_id, _old_email, new_email, expires_at, used, old_done, new_done) = | ||
| 1013 | + row; | ||
| 1014 | + if used || expires_at < store::now() { | ||
| 1015 | + return Err(AccountError::EmailChangeInvalid); | ||
| 1016 | + } | ||
| 1017 | + let clicked_old = old_hash == hash; | ||
| 1018 | + if (clicked_old && old_done) || (!clicked_old && new_done) { | ||
| 1019 | + // This mailbox already agreed; a second click adds nothing but | ||
| 1020 | + // still says what the pair waits on. | ||
| 1021 | + return Ok(EmailChangeConfirmed::AwaitOther); | ||
| 1022 | + } | ||
| 1023 | + let completes = (clicked_old && new_done) || (!clicked_old && old_done); | ||
| 1024 | + if completes { | ||
| 1025 | + if let Some(other) = user_by_email(store, &new_email).await? { | ||
| 1026 | + if other.id != user_id { | ||
| 1027 | + let conn = store.conn.lock().await; | ||
| 1028 | + conn.execute( | ||
| 1029 | + "DELETE FROM email_changes WHERE old_token_hash = ?1 OR new_token_hash = ?1", | ||
| 1030 | + turso::params![hash], | ||
| 1031 | + ) | ||
| 1032 | + .await | ||
| 1033 | + .map_err(backend)?; | ||
| 1034 | + return Err(AccountError::EmailTaken); | ||
| 1035 | + } | ||
| 1036 | + } | ||
| 1037 | + set_email(store, &user_id, &new_email).await?; | ||
| 1038 | + let stamp = store::stamp(store::now())?; | ||
| 1039 | + let conn = store.conn.lock().await; | ||
| 1040 | + conn.execute( | ||
| 1041 | + "UPDATE email_changes SET confirmed_old_at = COALESCE(confirmed_old_at, ?1), \ | ||
| 1042 | + confirmed_new_at = COALESCE(confirmed_new_at, ?1), used_at = ?1 \ | ||
| 1043 | + WHERE old_token_hash = ?2 OR new_token_hash = ?2", | ||
| 1044 | + turso::params![stamp, hash], | ||
| 1045 | + ) | ||
| 1046 | + .await | ||
| 1047 | + .map_err(backend)?; | ||
| 1048 | + drop(conn); | ||
| 1049 | + let user = user_by_id(store, &user_id) | ||
| 1050 | + .await? | ||
| 1051 | + .ok_or_else(|| AccountError::Backend("email change: user vanished".into()))?; | ||
| 1052 | + return Ok(EmailChangeConfirmed::Applied(user)); | ||
| 1053 | + } | ||
| 1054 | + let sql = if clicked_old { | ||
| 1055 | + "UPDATE email_changes SET confirmed_old_at = ?1 \ | ||
| 1056 | + WHERE old_token_hash = ?2 OR new_token_hash = ?2" | ||
| 1057 | + } else { | ||
| 1058 | + "UPDATE email_changes SET confirmed_new_at = ?1 \ | ||
| 1059 | + WHERE old_token_hash = ?2 OR new_token_hash = ?2" | ||
| 1060 | + }; | ||
| 1061 | + let stamp = store::stamp(store::now())?; | ||
| 1062 | + let conn = store.conn.lock().await; | ||
| 1063 | + conn.execute(sql, turso::params![stamp, hash]) | ||
| 1064 | + .await | ||
| 1065 | + .map_err(backend)?; | ||
| 1066 | + Ok(EmailChangeConfirmed::AwaitOther) | ||
| 1067 | +} | ||
| 1068 | + | ||
| 1069 | +/// The change a confirmation link still offers — the address being gained | ||
| 1070 | +/// when the pair is live and unspent, `None` for a dead one. The confirm | ||
| 1071 | +/// card reads this to name what approval means. | ||
| 1072 | +pub async fn email_change_link( | ||
| 1073 | + store: &Store, | ||
| 1074 | + token: &str, | ||
| 1075 | +) -> std::result::Result<Option<String>, AccountError> { | ||
| 1076 | + let hash = hash_token(token); | ||
| 1077 | + let conn = store.conn.lock().await; | ||
| 1078 | + let mut rows = conn | ||
| 1079 | + .query( | ||
| 1080 | + "SELECT new_email, expires_at, used_at FROM email_changes \ | ||
| 1081 | + WHERE old_token_hash = ?1 OR new_token_hash = ?1", | ||
| 1082 | + turso::params![hash], | ||
| 1083 | + ) | ||
| 1084 | + .await | ||
| 1085 | + .map_err(backend)?; | ||
| 1086 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 1087 | + return Ok(None); | ||
| 1088 | + }; | ||
| 1089 | + let new_email = store::text(&row, 0)?; | ||
| 1090 | + let expires_at = store::parse_stamp(&store::text(&row, 1)?)?; | ||
| 1091 | + let spent = store::opt_text(&row, 2)?.is_some(); | ||
| 1092 | + Ok((!spent && expires_at >= store::now()).then_some(new_email)) | ||
| 1093 | +} | ||
| 1094 | + | ||
| 1095 | +/// The address a user's pending change is waiting on, for the landing's | ||
| 1096 | +/// one-line state. `None` when nothing is asked for or the ask expired. | ||
| 1097 | +pub async fn pending_email_change( | ||
| 1098 | + store: &Store, | ||
| 1099 | + user: &UserId, | ||
| 1100 | +) -> std::result::Result<Option<String>, AccountError> { | ||
| 1101 | + let conn = store.conn.lock().await; | ||
| 1102 | + let mut rows = conn | ||
| 1103 | + .query( | ||
| 1104 | + "SELECT new_email, expires_at FROM email_changes \ | ||
| 1105 | + WHERE user_id = ?1 AND used_at IS NULL", | ||
| 1106 | + turso::params![user.to_string()], | ||
| 1107 | + ) | ||
| 1108 | + .await | ||
| 1109 | + .map_err(backend)?; | ||
| 1110 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 1111 | + return Ok(None); | ||
| 1112 | + }; | ||
| 1113 | + let new_email = store::text(&row, 0)?; | ||
| 1114 | + let expires_at = store::parse_stamp(&store::text(&row, 1)?)?; | ||
| 1115 | + Ok((expires_at >= store::now()).then_some(new_email)) | ||
| 1116 | +} | ||
| 1117 | + | ||
| 867 | #[cfg(test)] | 1118 | #[cfg(test)] |
| 868 | mod tests { | 1119 | mod tests { |
| 869 | use super::*; | 1120 | use super::*; |
| @@ -1175,4 +1426,211 @@ mod tests { | |||
| 1175 | .unwrap(); | 1426 | .unwrap(); |
| 1176 | assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); | 1427 | assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); |
| 1177 | } | 1428 | } |
| 1429 | + async fn seeded_user(store: &Store, email: &str, name: &str) -> User { | ||
| 1430 | + let invite = create_invite(store, email, None, false).await.unwrap(); | ||
| 1431 | + create_user_from_invite(store, invite.expose(), name, "tDLr9!mZQ2xv") | ||
| 1432 | + .await | ||
| 1433 | + .unwrap() | ||
| 1434 | + } | ||
| 1435 | + | ||
| 1436 | + #[tokio::test] | ||
| 1437 | + async fn set_email_rewrites_the_address_and_refuses_another_accounts() { | ||
| 1438 | + let store = fixture().await; | ||
| 1439 | + let ann = seeded_user(&store, "ann@example.com", "Ann").await; | ||
| 1440 | + let bob = seeded_user(&store, "bob@example.com", "Bob").await; | ||
| 1441 | + | ||
| 1442 | + // The rewrite is normalized the way the login path reads it, and | ||
| 1443 | + // every reader of the address follows. | ||
| 1444 | + set_email(&store, &ann.id, " Ann.New@Example.COM ") | ||
| 1445 | + .await | ||
| 1446 | + .unwrap(); | ||
| 1447 | + let found = user_by_email(&store, "ann.new@example.com") | ||
| 1448 | + .await | ||
| 1449 | + .unwrap() | ||
| 1450 | + .expect("the new address must resolve"); | ||
| 1451 | + assert_eq!(found.id, ann.id); | ||
| 1452 | + assert_eq!(found.email, "ann.new@example.com"); | ||
| 1453 | + assert!( | ||
| 1454 | + user_by_email(&store, "ann@example.com") | ||
| 1455 | + .await | ||
| 1456 | + .unwrap() | ||
| 1457 | + .is_none() | ||
| 1458 | + ); | ||
| 1459 | + | ||
| 1460 | + // An address another account owns is refused, the account untouched. | ||
| 1461 | + assert!(matches!( | ||
| 1462 | + set_email(&store, &ann.id, "bob@example.com").await, | ||
| 1463 | + Err(AccountError::EmailTaken) | ||
| 1464 | + )); | ||
| 1465 | + assert_eq!( | ||
| 1466 | + user_by_id(&store, &ann.id).await.unwrap().unwrap().email, | ||
| 1467 | + "ann.new@example.com" | ||
| 1468 | + ); | ||
| 1469 | + | ||
| 1470 | + // The address the account already carries: quiet success. | ||
| 1471 | + set_email(&store, &bob.id, "BOB@example.com").await.unwrap(); | ||
| 1472 | + | ||
| 1473 | + // And what no mail could reach is named at the door. | ||
| 1474 | + assert!(matches!( | ||
| 1475 | + set_email(&store, &ann.id, "not-an-address").await, | ||
| 1476 | + Err(AccountError::InvalidEmail) | ||
| 1477 | + )); | ||
| 1478 | + } | ||
| 1479 | + | ||
| 1480 | + #[tokio::test] | ||
| 1481 | + async fn email_change_applies_only_after_both_addresses_confirm() { | ||
| 1482 | + let store = fixture().await; | ||
| 1483 | + let ann = seeded_user(&store, "ann@example.com", "Ann").await; | ||
| 1484 | + | ||
| 1485 | + let (old_token, new_token) = | ||
| 1486 | + request_email_change(&store, &ann.id, "ann2@example.com") | ||
| 1487 | + .await | ||
| 1488 | + .unwrap(); | ||
| 1489 | + assert_eq!( | ||
| 1490 | + pending_email_change(&store, &ann.id).await.unwrap().as_deref(), | ||
| 1491 | + Some("ann2@example.com") | ||
| 1492 | + ); | ||
| 1493 | + | ||
| 1494 | + // The new mailbox agrees first: a mark, not the change. | ||
| 1495 | + assert!(matches!( | ||
| 1496 | + confirm_email_change(&store, new_token.expose()).await, | ||
| 1497 | + Ok(EmailChangeConfirmed::AwaitOther) | ||
| 1498 | + )); | ||
| 1499 | + assert_eq!( | ||
| 1500 | + user_by_email(&store, "ann@example.com") | ||
| 1501 | + .await | ||
| 1502 | + .unwrap() | ||
| 1503 | + .unwrap() | ||
| 1504 | + .id, | ||
| 1505 | + ann.id, | ||
| 1506 | + "one click must not move the address" | ||
| 1507 | + ); | ||
| 1508 | + | ||
| 1509 | + // Clicking the same link again adds nothing and spends nothing. | ||
| 1510 | + assert!(matches!( | ||
| 1511 | + confirm_email_change(&store, new_token.expose()).await, | ||
| 1512 | + Ok(EmailChangeConfirmed::AwaitOther) | ||
| 1513 | + )); | ||
| 1514 | + | ||
| 1515 | + // The old mailbox's agreement completes the pair: the address moves. | ||
| 1516 | + let user = match confirm_email_change(&store, old_token.expose()).await { | ||
| 1517 | + Ok(EmailChangeConfirmed::Applied(user)) => user, | ||
| 1518 | + outcome => panic!("expected Applied, got {outcome:?}"), | ||
| 1519 | + }; | ||
| 1520 | + assert_eq!(user.id, ann.id); | ||
| 1521 | + assert_eq!(user.email, "ann2@example.com"); | ||
| 1522 | + assert!( | ||
| 1523 | + user_by_email(&store, "ann2@example.com") | ||
| 1524 | + .await | ||
| 1525 | + .unwrap() | ||
| 1526 | + .is_some() | ||
| 1527 | + ); | ||
| 1528 | + assert!( | ||
| 1529 | + user_by_email(&store, "ann@example.com") | ||
| 1530 | + .await | ||
| 1531 | + .unwrap() | ||
| 1532 | + .is_none() | ||
| 1533 | + ); | ||
| 1534 | + assert_eq!(pending_email_change(&store, &ann.id).await.unwrap(), None); | ||
| 1535 | + | ||
| 1536 | + // The pair is spent whole: either link answers dead from now on. | ||
| 1537 | + assert!(matches!( | ||
| 1538 | + confirm_email_change(&store, old_token.expose()).await, | ||
| 1539 | + Err(AccountError::EmailChangeInvalid) | ||
| 1540 | + )); | ||
| 1541 | + assert!(matches!( | ||
| 1542 | + confirm_email_change(&store, new_token.expose()).await, | ||
| 1543 | + Err(AccountError::EmailChangeInvalid) | ||
| 1544 | + )); | ||
| 1545 | + } | ||
| 1546 | + | ||
| 1547 | + #[tokio::test] | ||
| 1548 | + async fn email_change_refuses_a_taken_address_at_ask_and_at_apply() { | ||
| 1549 | + let store = fixture().await; | ||
| 1550 | + let ann = seeded_user(&store, "ann@example.com", "Ann").await; | ||
| 1551 | + let _bob = seeded_user(&store, "bob@example.com", "Bob").await; | ||
| 1552 | + | ||
| 1553 | + // An owned address is refused at the ask. | ||
| 1554 | + assert!(matches!( | ||
| 1555 | + request_email_change(&store, &ann.id, "bob@example.com").await, | ||
| 1556 | + Err(AccountError::EmailTaken) | ||
| 1557 | + )); | ||
| 1558 | + // And so is the address the account already carries. | ||
| 1559 | + assert!(matches!( | ||
| 1560 | + request_email_change(&store, &ann.id, "ann@example.com").await, | ||
| 1561 | + Err(AccountError::SameEmail) | ||
| 1562 | + )); | ||
| 1563 | + | ||
| 1564 | + // The race: the gained address is asked for, then taken by someone | ||
| 1565 | + // else before both clicks land. The apply-time refusal keeps the | ||
| 1566 | + // old address and tears the dead pair down. | ||
| 1567 | + let (old_token, new_token) = | ||
| 1568 | + request_email_change(&store, &ann.id, "free@example.com") | ||
| 1569 | + .await | ||
| 1570 | + .unwrap(); | ||
| 1571 | + let carol = seeded_user(&store, "free@example.com", "Carol").await; | ||
| 1572 | + assert!(matches!( | ||
| 1573 | + confirm_email_change(&store, new_token.expose()).await, | ||
| 1574 | + Ok(EmailChangeConfirmed::AwaitOther) | ||
| 1575 | + )); | ||
| 1576 | + assert!(matches!( | ||
| 1577 | + confirm_email_change(&store, old_token.expose()).await, | ||
| 1578 | + Err(AccountError::EmailTaken) | ||
| 1579 | + )); | ||
| 1580 | + assert_eq!( | ||
| 1581 | + user_by_email(&store, "ann@example.com") | ||
| 1582 | + .await | ||
| 1583 | + .unwrap() | ||
| 1584 | + .unwrap() | ||
| 1585 | + .id, | ||
| 1586 | + ann.id, | ||
| 1587 | + "the refusal must leave the old address in place" | ||
| 1588 | + ); | ||
| 1589 | + assert_eq!(carol.email, "free@example.com"); | ||
| 1590 | + assert_eq!(pending_email_change(&store, &ann.id).await.unwrap(), None); | ||
| 1591 | + } | ||
| 1592 | + | ||
| 1593 | + #[tokio::test] | ||
| 1594 | + async fn email_change_links_die_at_expiry_and_a_new_ask_supersedes() { | ||
| 1595 | + let store = fixture().await; | ||
| 1596 | + let ann = seeded_user(&store, "ann@example.com", "Ann").await; | ||
| 1597 | + | ||
| 1598 | + let (first_old, first_new) = | ||
| 1599 | + request_email_change(&store, &ann.id, "ann2@example.com") | ||
| 1600 | + .await | ||
| 1601 | + .unwrap(); | ||
| 1602 | + | ||
| 1603 | + // Asking again is the reset idiom: the newest pair is the only door. | ||
| 1604 | + request_email_change(&store, &ann.id, "ann3@example.com") | ||
| 1605 | + .await | ||
| 1606 | + .unwrap(); | ||
| 1607 | + assert!(matches!( | ||
| 1608 | + confirm_email_change(&store, first_old.expose()).await, | ||
| 1609 | + Err(AccountError::EmailChangeInvalid) | ||
| 1610 | + )); | ||
| 1611 | + assert!(matches!( | ||
| 1612 | + confirm_email_change(&store, first_new.expose()).await, | ||
| 1613 | + Err(AccountError::EmailChangeInvalid) | ||
| 1614 | + )); | ||
| 1615 | + | ||
| 1616 | + // And the clock kills a pair on its own: past expiry, dead. | ||
| 1617 | + let (expired_old, _expired_new) = | ||
| 1618 | + request_email_change(&store, &ann.id, "ann4@example.com") | ||
| 1619 | + .await | ||
| 1620 | + .unwrap(); | ||
| 1621 | + { | ||
| 1622 | + let conn = store.conn.lock().await; | ||
| 1623 | + conn.execute( | ||
| 1624 | + "UPDATE email_changes SET expires_at = ?1", | ||
| 1625 | + turso::params![store::stamp(store::now() - time::Duration::seconds(1)).unwrap()], | ||
| 1626 | + ) | ||
| 1627 | + .await | ||
| 1628 | + .unwrap(); | ||
| 1629 | + } | ||
| 1630 | + assert!(matches!( | ||
| 1631 | + confirm_email_change(&store, expired_old.expose()).await, | ||
| 1632 | + Err(AccountError::EmailChangeInvalid) | ||
| 1633 | + )); | ||
| 1634 | + assert_eq!(pending_email_change(&store, &ann.id).await.unwrap(), None); | ||
| 1635 | + } | ||
| 1178 | } | 1636 | } |
crates/im-core/src/store.rsmodified+13 -0
| @@ -126,6 +126,18 @@ CREATE TABLE IF NOT EXISTS reset_links ( | |||
| 126 | expires_at TEXT NOT NULL, | 126 | expires_at TEXT NOT NULL, |
| 127 | used_at TEXT | 127 | used_at TEXT |
| 128 | ); | 128 | ); |
| 129 | +CREATE TABLE IF NOT EXISTS email_changes ( | ||
| 130 | + old_token_hash TEXT PRIMARY KEY, | ||
| 131 | + new_token_hash TEXT NOT NULL UNIQUE, | ||
| 132 | + user_id TEXT NOT NULL REFERENCES users(id), | ||
| 133 | + old_email TEXT NOT NULL, | ||
| 134 | + new_email TEXT NOT NULL, | ||
| 135 | + created_at TEXT NOT NULL, | ||
| 136 | + expires_at TEXT NOT NULL, | ||
| 137 | + confirmed_old_at TEXT, | ||
| 138 | + confirmed_new_at TEXT, | ||
| 139 | + used_at TEXT | ||
| 140 | +); | ||
| 129 | CREATE TABLE IF NOT EXISTS login_attempts ( | 141 | CREATE TABLE IF NOT EXISTS login_attempts ( |
| 130 | key TEXT NOT NULL, | 142 | key TEXT NOT NULL, |
| 131 | at TEXT NOT NULL | 143 | at TEXT NOT NULL |
| @@ -393,6 +405,7 @@ mod tests { | |||
| 393 | "refresh_tokens", | 405 | "refresh_tokens", |
| 394 | "signing_keys", | 406 | "signing_keys", |
| 395 | "reset_links", | 407 | "reset_links", |
| 408 | + "email_changes", | ||
| 396 | "login_attempts", | 409 | "login_attempts", |
| 397 | ] { | 410 | ] { |
| 398 | assert!(tables.contains(&expected.to_string()), "missing {expected}"); | 411 | assert!(tables.contains(&expected.to_string()), "missing {expected}"); |
crates/im-migrate/src/main.rsmodified+12 -0
| @@ -115,6 +115,18 @@ CREATE TABLE IF NOT EXISTS reset_links ( | |||
| 115 | expires_at TEXT NOT NULL, | 115 | expires_at TEXT NOT NULL, |
| 116 | used_at TEXT | 116 | used_at TEXT |
| 117 | ); | 117 | ); |
| 118 | +CREATE TABLE IF NOT EXISTS email_changes ( | ||
| 119 | + old_token_hash TEXT PRIMARY KEY, | ||
| 120 | + new_token_hash TEXT NOT NULL UNIQUE, | ||
| 121 | + user_id TEXT NOT NULL REFERENCES users(id), | ||
| 122 | + old_email TEXT NOT NULL, | ||
| 123 | + new_email TEXT NOT NULL, | ||
| 124 | + created_at TEXT NOT NULL, | ||
| 125 | + expires_at TEXT NOT NULL, | ||
| 126 | + confirmed_old_at TEXT, | ||
| 127 | + confirmed_new_at TEXT, | ||
| 128 | + used_at TEXT | ||
| 129 | +); | ||
| 118 | CREATE TABLE IF NOT EXISTS login_attempts ( | 130 | CREATE TABLE IF NOT EXISTS login_attempts ( |
| 119 | key TEXT NOT NULL, | 131 | key TEXT NOT NULL, |
| 120 | at TEXT NOT NULL | 132 | at TEXT NOT NULL |
crates/im-web/src/admin.rsmodified+50 -5
| @@ -157,6 +157,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | |||
| 157 | "deleted" => t(lang, Key::OkDeleted), | 157 | "deleted" => t(lang, Key::OkDeleted), |
| 158 | "settings" => t(lang, Key::OkSettingsSaved), | 158 | "settings" => t(lang, Key::OkSettingsSaved), |
| 159 | "services" => t(lang, Key::OkServicesSaved), | 159 | "services" => t(lang, Key::OkServicesSaved), |
| 160 | + "email_changed" => t(lang, Key::OkEmailChanged), | ||
| 160 | _ => t(lang, Key::OkDone), | 161 | _ => t(lang, Key::OkDone), |
| 161 | } | 162 | } |
| 162 | )), | 163 | )), |
| @@ -289,12 +290,28 @@ async fn users_section( | |||
| 289 | .flatten() | 290 | .flatten() |
| 290 | .collect::<Vec<_>>() | 291 | .collect::<Vec<_>>() |
| 291 | .join(" · "); | 292 | .join(" · "); |
| 293 | + let id = escape(&user.id.to_string()); | ||
| 294 | + let email = escape(&user.email); | ||
| 295 | + // The address edit sits on every row — the admin's own included: | ||
| 296 | + // the rescue exists precisely for a mailbox the mail cannot reach. | ||
| 297 | + // Same two-step disclosure as the row's other actions. | ||
| 298 | + let email_edit = format!( | ||
| 299 | + r#"<details class="admin-confirm"><summary class="admin-action">{edit_word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{edit_title}</div><form method="post" action="/admin/user_email" class="admin-form"><input type="hidden" name="user" value="{id}"><label class="auth-field"><span class="auth-label">{email_label}</span><input class="auth-input auth-input-mono" type="email" name="email" value="{email}" required></label><button class="admin-action" type="submit">{save}</button></form></div></details>"#, | ||
| 300 | + edit_word = t(lang, Key::EditWord), | ||
| 301 | + edit_title = i18n::email_edit_title(lang, &email), | ||
| 302 | + id = id, | ||
| 303 | + email_label = t(lang, Key::EmailCol), | ||
| 304 | + email = email, | ||
| 305 | + save = t(lang, Key::SaveButton), | ||
| 306 | + ); | ||
| 292 | let actions = if user.id == me.id { | 307 | let actions = if user.id == me.id { |
| 293 | - // Never let the only admin lock themselves out by reflex. | 308 | + // Never let the only admin lock themselves out by reflex. The |
| 294 | - format!(r#"<span class="muted">{}</span>"#, t(lang, Key::YouWord)) | 309 | + // address edit stays: fixing one's own address is the point. |
| 310 | + format!( | ||
| 311 | + r#"<span class="muted">{}</span>{email_edit}"#, | ||
| 312 | + t(lang, Key::YouWord) | ||
| 313 | + ) | ||
| 295 | } else { | 314 | } else { |
| 296 | - let id = escape(&user.id.to_string()); | ||
| 297 | - let email = escape(&user.email); | ||
| 298 | // Every row action is a two-step disclosure — iz's | 315 | // Every row action is a two-step disclosure — iz's |
| 299 | // confirm-details idiom: the summary is the word, the panel holds | 316 | // confirm-details idiom: the summary is the word, the panel holds |
| 300 | // the button that actually does it. No script required; the live | 317 | // the button that actually does it. No script required; the live |
| @@ -333,7 +350,7 @@ async fn users_section( | |||
| 333 | t(lang, Key::ConfirmDelete), | 350 | t(lang, Key::ConfirmDelete), |
| 334 | ); | 351 | ); |
| 335 | format!( | 352 | format!( |
| 336 | - r#"{toggle}<form method="post" action="/admin/revoke"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">{sign_out}</button></form>{remove}"#, | 353 | + r#"{email_edit}{toggle}<form method="post" action="/admin/revoke"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">{sign_out}</button></form>{remove}"#, |
| 337 | sign_out = t(lang, Key::SignOutEverywhere), | 354 | sign_out = t(lang, Key::SignOutEverywhere), |
| 338 | ) | 355 | ) |
| 339 | }; | 356 | }; |
| @@ -1206,6 +1223,34 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> { | |||
| 1206 | } | 1223 | } |
| 1207 | } | 1224 | } |
| 1208 | 1225 | ||
| 1226 | +#[derive(Deserialize)] | ||
| 1227 | +struct UserEmailForm { | ||
| 1228 | + user: String, | ||
| 1229 | + email: String, | ||
| 1230 | +} | ||
| 1231 | + | ||
| 1232 | +/// The users section's direct address edit — the admin's rescue for a | ||
| 1233 | +/// typo'd or unreachable mailbox, applied outright: email is contact | ||
| 1234 | +/// metadata, not a key, so the id stays and every reader of the address | ||
| 1235 | +/// follows on its next read. | ||
| 1236 | +#[route(POST "/admin/user_email")] | ||
| 1237 | +async fn user_email(cx: &Cx, Form(input): Form<UserEmailForm>) -> Result<Response> { | ||
| 1238 | + let me = match require_admin(cx).await { | ||
| 1239 | + Ok(me) => me, | ||
| 1240 | + Err(redirect) => return Ok(redirect), | ||
| 1241 | + }; | ||
| 1242 | + let store = &app(cx).store; | ||
| 1243 | + match accounts::set_email(store, &UserId::from(input.user), &input.email).await { | ||
| 1244 | + Ok(()) => {} | ||
| 1245 | + Err(accounts::AccountError::EmailTaken) => return back(cx, "users", "&error=email_taken"), | ||
| 1246 | + Err(accounts::AccountError::InvalidEmail) => return back(cx, "users", "&error=bad_email"), | ||
| 1247 | + Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), | ||
| 1248 | + } | ||
| 1249 | + let email = input.email.trim().to_lowercase(); | ||
| 1250 | + server::log_event(cx, "email_changed", Some(&me.email), Some(&email)).await; | ||
| 1251 | + back(cx, "users", "&ok=email_changed") | ||
| 1252 | +} | ||
| 1253 | + | ||
| 1209 | #[derive(Deserialize)] | 1254 | #[derive(Deserialize)] |
| 1210 | struct InviteAction { | 1255 | struct InviteAction { |
| 1211 | invite: String, | 1256 | invite: String, |
crates/im-web/src/auth.rsmodified+111 -0
| @@ -388,6 +388,117 @@ async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect { | |||
| 388 | } | 388 | } |
| 389 | } | 389 | } |
| 390 | 390 | ||
| 391 | +#[derive(Deserialize)] | ||
| 392 | +struct EmailChangeForm { | ||
| 393 | + email: String, | ||
| 394 | +} | ||
| 395 | + | ||
| 396 | +/// The landing's address change: one ask, two mails — the old address must | ||
| 397 | +/// agree to let the account go and the new one to take it on. Without a | ||
| 398 | +/// sender configured the two links come back on the redirect once — the | ||
| 399 | +/// crate's unmailed idiom, and the requester is the only person who needs | ||
| 400 | +/// them. | ||
| 401 | +#[route(POST "/email_change")] | ||
| 402 | +async fn email_change(cx: &Cx, Form(input): Form<EmailChangeForm>) -> Redirect { | ||
| 403 | + let Some(me) = server::current_user(cx).await else { | ||
| 404 | + return see("/".to_string()); | ||
| 405 | + }; | ||
| 406 | + let store = &server::app(cx).store; | ||
| 407 | + let (old_token, new_token) = | ||
| 408 | + match accounts::request_email_change(store, &me.id, &input.email).await { | ||
| 409 | + Ok(pair) => pair, | ||
| 410 | + Err(AccountError::InvalidEmail) => { | ||
| 411 | + return see("/?section=profile&error=bad_email".to_string()); | ||
| 412 | + } | ||
| 413 | + Err(AccountError::SameEmail) => { | ||
| 414 | + return see("/?section=profile&error=same_email".to_string()); | ||
| 415 | + } | ||
| 416 | + Err(AccountError::EmailTaken) => { | ||
| 417 | + return see("/?section=profile&error=email_taken".to_string()); | ||
| 418 | + } | ||
| 419 | + Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), | ||
| 420 | + }; | ||
| 421 | + let issuer = server::app(cx).config.issuer.clone(); | ||
| 422 | + // Both mails follow the account's own language. | ||
| 423 | + let lang = crate::i18n::Lang::from_code(&me.language); | ||
| 424 | + let old_mailed = crate::mailer::send_email_change( | ||
| 425 | + store, | ||
| 426 | + &issuer, | ||
| 427 | + &me.email, | ||
| 428 | + old_token.expose(), | ||
| 429 | + lang, | ||
| 430 | + false, | ||
| 431 | + ) | ||
| 432 | + .await | ||
| 433 | + .is_ok(); | ||
| 434 | + let new_mailed = crate::mailer::send_email_change( | ||
| 435 | + store, | ||
| 436 | + &issuer, | ||
| 437 | + input.email.trim(), | ||
| 438 | + new_token.expose(), | ||
| 439 | + lang, | ||
| 440 | + true, | ||
| 441 | + ) | ||
| 442 | + .await | ||
| 443 | + .is_ok(); | ||
| 444 | + server::log_event( | ||
| 445 | + cx, | ||
| 446 | + "email_change_asked", | ||
| 447 | + Some(&me.email), | ||
| 448 | + Some(input.email.trim().to_lowercase()).as_deref(), | ||
| 449 | + ) | ||
| 450 | + .await; | ||
| 451 | + if old_mailed && new_mailed { | ||
| 452 | + see("/?section=profile&ok=email_change_asked".to_string()) | ||
| 453 | + } else { | ||
| 454 | + let links = format!( | ||
| 455 | + "{issuer}/email/{} {issuer}/email/{}", | ||
| 456 | + old_token.expose(), | ||
| 457 | + new_token.expose() | ||
| 458 | + ); | ||
| 459 | + see(format!( | ||
| 460 | + "/?section=profile&ok=email_change_asked&links={}", | ||
| 461 | + crate::oidc::urlencode(&links) | ||
| 462 | + )) | ||
| 463 | + } | ||
| 464 | +} | ||
| 465 | + | ||
| 466 | +#[derive(Deserialize)] | ||
| 467 | +struct EmailConfirmForm { | ||
| 468 | + token: String, | ||
| 469 | +} | ||
| 470 | + | ||
| 471 | +/// A confirmation link's POST — the click that counts. The first mailbox | ||
| 472 | +/// to agree only marks its side; the second applies the change. Signed-out | ||
| 473 | +/// viewers may confirm, because holding the mailbox is the proof; each | ||
| 474 | +/// lands where their state says, a session on the landing and everyone | ||
| 475 | +/// else at the front door. | ||
| 476 | +#[route(POST "/email")] | ||
| 477 | +async fn email_confirm(cx: &Cx, Form(input): Form<EmailConfirmForm>) -> Redirect { | ||
| 478 | + let store = &server::app(cx).store; | ||
| 479 | + match accounts::confirm_email_change(store, &input.token).await { | ||
| 480 | + Ok(accounts::EmailChangeConfirmed::Applied(user)) => { | ||
| 481 | + server::log_event(cx, "email_changed", Some(&user.email), None).await; | ||
| 482 | + if server::current_user(cx).await.is_some() { | ||
| 483 | + see("/?section=profile&ok=email_changed".to_string()) | ||
| 484 | + } else { | ||
| 485 | + see("/login?ok=email_changed".to_string()) | ||
| 486 | + } | ||
| 487 | + } | ||
| 488 | + Ok(accounts::EmailChangeConfirmed::AwaitOther) => { | ||
| 489 | + if server::current_user(cx).await.is_some() { | ||
| 490 | + see("/?section=profile&ok=email_half_confirmed".to_string()) | ||
| 491 | + } else { | ||
| 492 | + see("/login?ok=email_half_confirmed".to_string()) | ||
| 493 | + } | ||
| 494 | + } | ||
| 495 | + Err(AccountError::EmailTaken) => see("/login?error=email_taken".to_string()), | ||
| 496 | + Err(AccountError::EmailChangeInvalid) => { | ||
| 497 | + see("/login?error=email_change_invalid".to_string()) | ||
| 498 | + } | ||
| 499 | + Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), | ||
| 500 | + } | ||
| 501 | +} | ||
| 391 | #[derive(Deserialize)] | 502 | #[derive(Deserialize)] |
| 392 | struct SessionRevokeForm { | 503 | struct SessionRevokeForm { |
| 393 | session: String, | 504 | session: String, |
crates/im-web/src/directory.rsmodified+218 -0
| @@ -993,4 +993,222 @@ mod tests { | |||
| 993 | ); | 993 | ); |
| 994 | } | 994 | } |
| 995 | 995 | ||
| 996 | + /// Percent-decodes a query value back into text — the tests read the | ||
| 997 | + /// once-shown confirmation links out of the redirect's Location. | ||
| 998 | + fn pct_decode(raw: &str) -> String { | ||
| 999 | + let bytes = raw.as_bytes(); | ||
| 1000 | + let mut out = Vec::new(); | ||
| 1001 | + let mut i = 0; | ||
| 1002 | + while i < bytes.len() { | ||
| 1003 | + if bytes[i] == b'%' { | ||
| 1004 | + out.push( | ||
| 1005 | + u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap(), 16) | ||
| 1006 | + .unwrap(), | ||
| 1007 | + ); | ||
| 1008 | + i += 3; | ||
| 1009 | + } else { | ||
| 1010 | + out.push(bytes[i]); | ||
| 1011 | + i += 1; | ||
| 1012 | + } | ||
| 1013 | + } | ||
| 1014 | + String::from_utf8(out).unwrap() | ||
| 1015 | + } | ||
| 1016 | + | ||
| 1017 | + #[tokio::test] | ||
| 1018 | + async fn admin_email_edit_applies_directly_and_refuses_taken_address() { | ||
| 1019 | + let Setup { | ||
| 1020 | + router, store, .. | ||
| 1021 | + } = setup().await; | ||
| 1022 | + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") | ||
| 1023 | + .await | ||
| 1024 | + .unwrap() | ||
| 1025 | + .unwrap(); | ||
| 1026 | + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") | ||
| 1027 | + .await | ||
| 1028 | + .unwrap() | ||
| 1029 | + .unwrap(); | ||
| 1030 | + let session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) | ||
| 1031 | + .await | ||
| 1032 | + .unwrap(); | ||
| 1033 | + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); | ||
| 1034 | + | ||
| 1035 | + // A non-admin's edit is sent to the front door and writes nothing. | ||
| 1036 | + let ben_session = im_core::sessions::create_session(&store, &ben.id, &Default::default()) | ||
| 1037 | + .await | ||
| 1038 | + .unwrap(); | ||
| 1039 | + let (status, location, _) = post_form( | ||
| 1040 | + &router, | ||
| 1041 | + "/admin/user_email", | ||
| 1042 | + &format!("user={}&email=changed%40example.com", ben.id), | ||
| 1043 | + Some(&format!("{SESSION_COOKIE}={}", ben_session.expose())), | ||
| 1044 | + ) | ||
| 1045 | + .await; | ||
| 1046 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1047 | + assert_eq!(location.as_deref(), Some("/")); | ||
| 1048 | + assert!( | ||
| 1049 | + im_core::accounts::user_by_email(&store, "changed@example.com") | ||
| 1050 | + .await | ||
| 1051 | + .unwrap() | ||
| 1052 | + .is_none() | ||
| 1053 | + ); | ||
| 1054 | + | ||
| 1055 | + // The admin's edit lands back on the section with its ok code, the | ||
| 1056 | + // address normalized the way the login path reads it. | ||
| 1057 | + let (status, location, _) = post_form( | ||
| 1058 | + &router, | ||
| 1059 | + "/admin/user_email", | ||
| 1060 | + &format!("user={}&email=%20Ben.New%40Example.COM%20", ben.id), | ||
| 1061 | + Some(&cookie), | ||
| 1062 | + ) | ||
| 1063 | + .await; | ||
| 1064 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1065 | + assert_eq!( | ||
| 1066 | + location.as_deref(), | ||
| 1067 | + Some("/admin?section=users&ok=email_changed") | ||
| 1068 | + ); | ||
| 1069 | + let moved = im_core::accounts::user_by_email(&store, "ben.new@example.com") | ||
| 1070 | + .await | ||
| 1071 | + .unwrap() | ||
| 1072 | + .unwrap(); | ||
| 1073 | + assert_eq!(moved.id, ben.id); | ||
| 1074 | + assert_eq!(moved.email, "ben.new@example.com"); | ||
| 1075 | + assert!( | ||
| 1076 | + im_core::accounts::user_by_email(&store, "ben@example.com") | ||
| 1077 | + .await | ||
| 1078 | + .unwrap() | ||
| 1079 | + .is_none() | ||
| 1080 | + ); | ||
| 1081 | + let panel = get_page(&router, "/admin?section=users", &cookie).await; | ||
| 1082 | + assert!(panel.contains("ben.new@example.com"), "{panel}"); | ||
| 1083 | + | ||
| 1084 | + // Another account's address is refused by name; the account's | ||
| 1085 | + // address stays. | ||
| 1086 | + let (status, location, _) = post_form( | ||
| 1087 | + &router, | ||
| 1088 | + "/admin/user_email", | ||
| 1089 | + &format!("user={}&email=ada%40example.com", ben.id), | ||
| 1090 | + Some(&cookie), | ||
| 1091 | + ) | ||
| 1092 | + .await; | ||
| 1093 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1094 | + assert_eq!( | ||
| 1095 | + location.as_deref(), | ||
| 1096 | + Some("/admin?section=users&error=email_taken") | ||
| 1097 | + ); | ||
| 1098 | + assert_eq!( | ||
| 1099 | + im_core::accounts::user_by_email(&store, "ben.new@example.com") | ||
| 1100 | + .await | ||
| 1101 | + .unwrap() | ||
| 1102 | + .unwrap() | ||
| 1103 | + .id, | ||
| 1104 | + ben.id | ||
| 1105 | + ); | ||
| 1106 | + } | ||
| 1107 | + | ||
| 1108 | + #[tokio::test] | ||
| 1109 | + async fn self_served_email_change_applies_after_both_addresses_confirm() { | ||
| 1110 | + let Setup { | ||
| 1111 | + router, store, .. | ||
| 1112 | + } = setup().await; | ||
| 1113 | + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") | ||
| 1114 | + .await | ||
| 1115 | + .unwrap() | ||
| 1116 | + .unwrap(); | ||
| 1117 | + let session = im_core::sessions::create_session(&store, &ben.id, &Default::default()) | ||
| 1118 | + .await | ||
| 1119 | + .unwrap(); | ||
| 1120 | + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); | ||
| 1121 | + | ||
| 1122 | + // The ask: with no sender configured, the two confirmation links | ||
| 1123 | + // come back on the redirect once — the crate's unmailed idiom. | ||
| 1124 | + let (status, location, _) = post_form( | ||
| 1125 | + &router, | ||
| 1126 | + "/email_change", | ||
| 1127 | + "email=ben2%40example.com", | ||
| 1128 | + Some(&cookie), | ||
| 1129 | + ) | ||
| 1130 | + .await; | ||
| 1131 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1132 | + let location = location.expect("a redirect carrying the once-shown links"); | ||
| 1133 | + assert!(location.contains("ok=email_change_asked"), "{location}"); | ||
| 1134 | + let encoded = location | ||
| 1135 | + .split("links=") | ||
| 1136 | + .nth(1) | ||
| 1137 | + .expect("the unmailed pair shows once"); | ||
| 1138 | + let tokens: Vec<String> = pct_decode(encoded) | ||
| 1139 | + .split(' ') | ||
| 1140 | + .map(|link| { | ||
| 1141 | + link.rsplit('/') | ||
| 1142 | + .next() | ||
| 1143 | + .expect("each link ends in its token") | ||
| 1144 | + .to_string() | ||
| 1145 | + }) | ||
| 1146 | + .collect(); | ||
| 1147 | + assert_eq!(tokens.len(), 2); | ||
| 1148 | + | ||
| 1149 | + // The card names the address being gained, and the POST under it is | ||
| 1150 | + // the only door. | ||
| 1151 | + let card = get_page(&router, &format!("/email/{}", tokens[1]), "").await; | ||
| 1152 | + assert!(card.contains("ben2@example.com"), "{card}"); | ||
| 1153 | + assert!(card.contains(r#"action="/email""#), "{card}"); | ||
| 1154 | + | ||
| 1155 | + // The first click marks its side; the address does not move. | ||
| 1156 | + let (status, location, _) = post_form( | ||
| 1157 | + &router, | ||
| 1158 | + "/email", | ||
| 1159 | + &format!("token={}", tokens[1]), | ||
| 1160 | + Some(&cookie), | ||
| 1161 | + ) | ||
| 1162 | + .await; | ||
| 1163 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1164 | + assert_eq!( | ||
| 1165 | + location.as_deref(), | ||
| 1166 | + Some("/?section=profile&ok=email_half_confirmed") | ||
| 1167 | + ); | ||
| 1168 | + assert!( | ||
| 1169 | + im_core::accounts::user_by_email(&store, "ben@example.com") | ||
| 1170 | + .await | ||
| 1171 | + .unwrap() | ||
| 1172 | + .is_some() | ||
| 1173 | + ); | ||
| 1174 | + | ||
| 1175 | + // The second mailbox's agreement applies the change. | ||
| 1176 | + let (status, location, _) = post_form( | ||
| 1177 | + &router, | ||
| 1178 | + "/email", | ||
| 1179 | + &format!("token={}", tokens[0]), | ||
| 1180 | + Some(&cookie), | ||
| 1181 | + ) | ||
| 1182 | + .await; | ||
| 1183 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1184 | + assert_eq!( | ||
| 1185 | + location.as_deref(), | ||
| 1186 | + Some("/?section=profile&ok=email_changed") | ||
| 1187 | + ); | ||
| 1188 | + let moved = im_core::accounts::user_by_email(&store, "ben2@example.com") | ||
| 1189 | + .await | ||
| 1190 | + .unwrap() | ||
| 1191 | + .unwrap(); | ||
| 1192 | + assert_eq!(moved.id, ben.id); | ||
| 1193 | + assert!( | ||
| 1194 | + im_core::accounts::user_by_email(&store, "ben@example.com") | ||
| 1195 | + .await | ||
| 1196 | + .unwrap() | ||
| 1197 | + .is_none() | ||
| 1198 | + ); | ||
| 1199 | + | ||
| 1200 | + // Spent whole: either link answers dead now. | ||
| 1201 | + let (status, location, _) = post_form( | ||
| 1202 | + &router, | ||
| 1203 | + "/email", | ||
| 1204 | + &format!("token={}", tokens[0]), | ||
| 1205 | + Some(&cookie), | ||
| 1206 | + ) | ||
| 1207 | + .await; | ||
| 1208 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 1209 | + assert_eq!( | ||
| 1210 | + location.as_deref(), | ||
| 1211 | + Some("/login?error=email_change_invalid") | ||
| 1212 | + ); | ||
| 1213 | + } | ||
| 996 | } | 1214 | } |
crates/im-web/src/i18n.rsmodified+92 -0
| @@ -50,6 +50,9 @@ pub enum Key { | |||
| 50 | ErrInviteExpired, | 50 | ErrInviteExpired, |
| 51 | ErrInviteSpent, | 51 | ErrInviteSpent, |
| 52 | ErrEmailTaken, | 52 | ErrEmailTaken, |
| 53 | + ErrInvalidEmail, | ||
| 54 | + ErrSameEmail, | ||
| 55 | + ErrEmailChangeInvalid, | ||
| 53 | ErrPasswordTooShort, | 56 | ErrPasswordTooShort, |
| 54 | ErrPasswordPersonal, | 57 | ErrPasswordPersonal, |
| 55 | ErrPasswordsDiffer, | 58 | ErrPasswordsDiffer, |
| @@ -75,6 +78,15 @@ pub enum Key { | |||
| 75 | OkPhotoRemoved, | 78 | OkPhotoRemoved, |
| 76 | OkSessionRevoked, | 79 | OkSessionRevoked, |
| 77 | OkDone, | 80 | OkDone, |
| 81 | + OkEmailChanged, | ||
| 82 | + OkEmailChangeAsked, | ||
| 83 | + OkEmailHalfConfirmed, | ||
| 84 | + EmailCardTitle, | ||
| 85 | + NewEmailLabel, | ||
| 86 | + EmailChangeButton, | ||
| 87 | + EmailChangeNote, | ||
| 88 | + EmailConfirmTitle, | ||
| 89 | + ConfirmEmailButton, | ||
| 78 | 90 | ||
| 79 | // Sign-in card and auth pages. | 91 | // Sign-in card and auth pages. |
| 80 | SignInTitle, | 92 | SignInTitle, |
| @@ -315,6 +327,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 315 | (ErrInviteSpent, Tr) => "Bu davet zaten kullanıldı.", | 327 | (ErrInviteSpent, Tr) => "Bu davet zaten kullanıldı.", |
| 316 | (ErrEmailTaken, En) => "An account with this address already exists.", | 328 | (ErrEmailTaken, En) => "An account with this address already exists.", |
| 317 | (ErrEmailTaken, Tr) => "Bu adresle zaten bir hesap var.", | 329 | (ErrEmailTaken, Tr) => "Bu adresle zaten bir hesap var.", |
| 330 | + (ErrInvalidEmail, En) => "That doesn't look like an email address.", | ||
| 331 | + (ErrInvalidEmail, Tr) => "Bu bir e-posta adresine benzemiyor.", | ||
| 332 | + (ErrSameEmail, En) => "That's already your address.", | ||
| 333 | + (ErrSameEmail, Tr) => "Bu adres zaten senin adresin.", | ||
| 334 | + (ErrEmailChangeInvalid, En) => "This email-change link is not valid.", | ||
| 335 | + (ErrEmailChangeInvalid, Tr) => "Bu e-posta değişikliği bağlantısı geçerli değil.", | ||
| 318 | (ErrPasswordTooShort, En) => "The password needs at least 10 characters.", | 336 | (ErrPasswordTooShort, En) => "The password needs at least 10 characters.", |
| 319 | (ErrPasswordTooShort, Tr) => "Parola en az 10 karakter olmalı.", | 337 | (ErrPasswordTooShort, Tr) => "Parola en az 10 karakter olmalı.", |
| 320 | (ErrPasswordPersonal, En) => "The password can't contain your address or your name.", | 338 | (ErrPasswordPersonal, En) => "The password can't contain your address or your name.", |
| @@ -529,6 +547,24 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 529 | (NavServices, Tr) => "Hizmetler", | 547 | (NavServices, Tr) => "Hizmetler", |
| 530 | (OkInvited, En) => "Invite created.", | 548 | (OkInvited, En) => "Invite created.", |
| 531 | (OkInvited, Tr) => "Davet oluşturuldu.", | 549 | (OkInvited, Tr) => "Davet oluşturuldu.", |
| 550 | + (OkEmailChanged, En) => "Email changed.", | ||
| 551 | + (OkEmailChanged, Tr) => "E-posta değişti.", | ||
| 552 | + (OkEmailChangeAsked, En) => "Confirmation mails sent — check both inboxes.", | ||
| 553 | + (OkEmailChangeAsked, Tr) => "Onay postaları gönderildi — iki kutuyu da kontrol et.", | ||
| 554 | + (OkEmailHalfConfirmed, En) => "One address confirmed — the change waits on the other.", | ||
| 555 | + (OkEmailHalfConfirmed, Tr) => "Bir adres onaylandı — değişiklik diğer adresi bekliyor.", | ||
| 556 | + (EmailCardTitle, En) => "Email address", | ||
| 557 | + (EmailCardTitle, Tr) => "E-posta adresi", | ||
| 558 | + (NewEmailLabel, En) => "New address", | ||
| 559 | + (NewEmailLabel, Tr) => "Yeni adres", | ||
| 560 | + (EmailChangeButton, En) => "Change address", | ||
| 561 | + (EmailChangeButton, Tr) => "Adresi değiştir", | ||
| 562 | + (EmailChangeNote, En) => "Both addresses confirm: one mail to the old one, one to the new.", | ||
| 563 | + (EmailChangeNote, Tr) => "İki adres de onaylar: eskiye bir, yeniye bir posta.", | ||
| 564 | + (EmailConfirmTitle, En) => "Confirm email change", | ||
| 565 | + (EmailConfirmTitle, Tr) => "E-posta değişikliğini onayla", | ||
| 566 | + (ConfirmEmailButton, En) => "Confirm", | ||
| 567 | + (ConfirmEmailButton, Tr) => "Onayla", | ||
| 532 | (OkRevoked, En) => "Sessions revoked — every device is signed out.", | 568 | (OkRevoked, En) => "Sessions revoked — every device is signed out.", |
| 533 | (OkRevoked, Tr) => "Oturumlar kapatıldı — her cihazın oturumu kapatıldı.", | 569 | (OkRevoked, Tr) => "Oturumlar kapatıldı — her cihazın oturumu kapatıldı.", |
| 534 | (OkDisabled, En) => "Account disabled.", | 570 | (OkDisabled, En) => "Account disabled.", |
| @@ -945,3 +981,59 @@ pub fn reset_mail(lang: Lang, link: &str, minutes: i64) -> (String, String) { | |||
| 945 | ), | 981 | ), |
| 946 | } | 982 | } |
| 947 | } | 983 | } |
| 984 | + | ||
| 985 | +/// The email-change card's sentence: what approval does to the address. | ||
| 986 | +pub fn email_confirm_sub(lang: Lang, new_email_html: &str) -> String { | ||
| 987 | + match lang { | ||
| 988 | + Lang::En => format!("Confirm to make {new_email_html} this account's address."), | ||
| 989 | + Lang::Tr => format!("Onaylayınca hesabın adresi {new_email_html} olacak."), | ||
| 990 | + } | ||
| 991 | +} | ||
| 992 | + | ||
| 993 | +/// The landing's pending line: the change asked for but not yet doubly | ||
| 994 | +/// confirmed. | ||
| 995 | +pub fn email_pending_line(lang: Lang, new_email_html: &str) -> String { | ||
| 996 | + match lang { | ||
| 997 | + Lang::En => format!("A change to {new_email_html} awaits confirmation."), | ||
| 998 | + Lang::Tr => format!("{new_email_html} değişikliği onay bekliyor."), | ||
| 999 | + } | ||
| 1000 | +} | ||
| 1001 | + | ||
| 1002 | +/// The admin row's edit-disclosure title. | ||
| 1003 | +pub fn email_edit_title(lang: Lang, email_html: &str) -> String { | ||
| 1004 | + match lang { | ||
| 1005 | + Lang::En => format!("Change {email_html}'s address."), | ||
| 1006 | + Lang::Tr => format!("{email_html} adresini değiştir."), | ||
| 1007 | + } | ||
| 1008 | +} | ||
| 1009 | +/// The address-change confirmation mail. Two travel per request — to the | ||
| 1010 | +/// address being left and the one being gained — and each says which kind | ||
| 1011 | +/// it is, so the holder knows which door they're opening. | ||
| 1012 | +pub fn email_change_mail(lang: Lang, link: &str, minutes: i64, gaining: bool) -> (String, String) { | ||
| 1013 | + match (lang, gaining) { | ||
| 1014 | + (Lang::En, true) => ( | ||
| 1015 | + "Confirm your new im address".to_string(), | ||
| 1016 | + format!( | ||
| 1017 | + "A change of this im account's address was asked for. Confirm to make it this account's address. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n" | ||
| 1018 | + ), | ||
| 1019 | + ), | ||
| 1020 | + (Lang::En, false) => ( | ||
| 1021 | + "Your im address is being changed".to_string(), | ||
| 1022 | + format!( | ||
| 1023 | + "A change of this im account's address was asked for. Confirm to let the account go. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n" | ||
| 1024 | + ), | ||
| 1025 | + ), | ||
| 1026 | + (Lang::Tr, true) => ( | ||
| 1027 | + "Yeni im adresini onayla".to_string(), | ||
| 1028 | + format!( | ||
| 1029 | + "Bu im hesabı için bir adres değişikliği istendi. Onaylayınca adres hesabın olacak. Bağlantı {minutes} dakika boyunca senin:\n\n{link}\n\nBu sen değilsen, bu posta hiçbir şeyi değiştirmez.\n" | ||
| 1030 | + ), | ||
| 1031 | + ), | ||
| 1032 | + (Lang::Tr, false) => ( | ||
| 1033 | + "im adresin değiştiriliyor".to_string(), | ||
| 1034 | + format!( | ||
| 1035 | + "Bu im hesabının adres değişikliği istendi. Onaylayınca hesabı bırakmış olacaksın. Bağlantı {minutes} dakika boyunca senin:\n\n{link}\n\nBu sen değilsen, bu posta hiçbir şeyi değiştirmez.\n" | ||
| 1036 | + ), | ||
| 1037 | + ), | ||
| 1038 | + } | ||
| 1039 | +} | ||
crates/im-web/src/mailer.rsmodified+19 -0
| @@ -99,6 +99,25 @@ pub async fn send_reset( | |||
| 99 | Ok(link) | 99 | Ok(link) |
| 100 | } | 100 | } |
| 101 | 101 | ||
| 102 | +/// The address-change confirmation mail: the link is the whole payload, in | ||
| 103 | +/// the account's language. Two travel per request — `gaining` marks the | ||
| 104 | +/// one bound for the address being gained; its twin goes to the address | ||
| 105 | +/// being left, and each says which door it opens. | ||
| 106 | +pub async fn send_email_change( | ||
| 107 | + store: &Store, | ||
| 108 | + issuer: &str, | ||
| 109 | + email: &str, | ||
| 110 | + token: &str, | ||
| 111 | + lang: Lang, | ||
| 112 | + gaining: bool, | ||
| 113 | +) -> Result<String> { | ||
| 114 | + let link = format!("{issuer}/email/{token}"); | ||
| 115 | + let minutes = settings::reset_minutes(store).await?; | ||
| 116 | + let (subject, body) = i18n::email_change_mail(lang, &link, minutes, gaining); | ||
| 117 | + send(store, email, &subject, body).await?; | ||
| 118 | + Ok(link) | ||
| 119 | +} | ||
| 120 | + | ||
| 102 | /// Dials the mail server without sending anything: connect, TLS, hello, | 121 | /// Dials the mail server without sending anything: connect, TLS, hello, |
| 103 | /// authenticate, NOOP, hang up. A pass proves the host, the port, the | 122 | /// authenticate, NOOP, hang up. A pass proves the host, the port, the |
| 104 | /// encryption and the password; it says nothing about whether the | 123 | /// encryption and the password; it says nothing about whether the |
crates/im-web/src/pages.rsmodified+75 -0
| @@ -27,6 +27,9 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { | |||
| 27 | "invite_expired" => t(lang, Key::ErrInviteExpired), | 27 | "invite_expired" => t(lang, Key::ErrInviteExpired), |
| 28 | "invite_spent" => t(lang, Key::ErrInviteSpent), | 28 | "invite_spent" => t(lang, Key::ErrInviteSpent), |
| 29 | "email_taken" => t(lang, Key::ErrEmailTaken), | 29 | "email_taken" => t(lang, Key::ErrEmailTaken), |
| 30 | + "bad_email" => t(lang, Key::ErrInvalidEmail), | ||
| 31 | + "same_email" => t(lang, Key::ErrSameEmail), | ||
| 32 | + "email_change_invalid" => t(lang, Key::ErrEmailChangeInvalid), | ||
| 30 | "password_too_short" => t(lang, Key::ErrPasswordTooShort), | 33 | "password_too_short" => t(lang, Key::ErrPasswordTooShort), |
| 31 | "password_personal" => t(lang, Key::ErrPasswordPersonal), | 34 | "password_personal" => t(lang, Key::ErrPasswordPersonal), |
| 32 | "passwords_differ" => t(lang, Key::ErrPasswordsDiffer), | 35 | "passwords_differ" => t(lang, Key::ErrPasswordsDiffer), |
| @@ -59,6 +62,9 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str { | |||
| 59 | "photo_saved" => t(lang, Key::OkPhotoSaved), | 62 | "photo_saved" => t(lang, Key::OkPhotoSaved), |
| 60 | "photo_removed" => t(lang, Key::OkPhotoRemoved), | 63 | "photo_removed" => t(lang, Key::OkPhotoRemoved), |
| 61 | "session_revoked" => t(lang, Key::OkSessionRevoked), | 64 | "session_revoked" => t(lang, Key::OkSessionRevoked), |
| 65 | + "email_changed" => t(lang, Key::OkEmailChanged), | ||
| 66 | + "email_change_asked" => t(lang, Key::OkEmailChangeAsked), | ||
| 67 | + "email_half_confirmed" => t(lang, Key::OkEmailHalfConfirmed), | ||
| 62 | "preferences" => t(lang, Key::Saved), | 68 | "preferences" => t(lang, Key::Saved), |
| 63 | "password" => t(lang, Key::PasswordSaved), | 69 | "password" => t(lang, Key::PasswordSaved), |
| 64 | _ => t(lang, Key::OkDone), | 70 | _ => t(lang, Key::OkDone), |
| @@ -621,6 +627,8 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | |||
| 621 | let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; | 627 | let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; |
| 622 | let joined = user.created_at.date().to_string(); | 628 | let joined = user.created_at.date().to_string(); |
| 623 | let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?; | 629 | let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?; |
| 630 | + let pending_email = | ||
| 631 | + im_core::accounts::pending_email_change(&server::app(cx).store, &user.id).await?; | ||
| 624 | let current = server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token)); | 632 | let current = server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token)); |
| 625 | let sessions_html = sessions_html(&sessions, current.as_deref(), lang); | 633 | let sessions_html = sessions_html(&sessions, current.as_deref(), lang); |
| 626 | let apps = im_core::oidc::list_connected_apps(&server::app(cx).store, &user.id).await?; | 634 | let apps = im_core::oidc::list_connected_apps(&server::app(cx).store, &user.id).await?; |
| @@ -861,6 +869,34 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | |||
| 861 | </div> | 869 | </div> |
| 862 | </dl> | 870 | </dl> |
| 863 | </div> | 871 | </div> |
| 872 | + <div class="auth-card"> | ||
| 873 | + <div class="auth-title">(t(lang, Key::EmailCardTitle))</div> | ||
| 874 | + if let Some(pending) = pending_email.as_deref() { | ||
| 875 | + <div class="auth-sub"> | ||
| 876 | + (crate::i18n::email_pending_line(lang, &escape(pending))) | ||
| 877 | + </div> | ||
| 878 | + } | ||
| 879 | + if let Some(links) = query_value(&query, "links") { | ||
| 880 | + <div class="auth-note">(links)</div> | ||
| 881 | + } | ||
| 882 | + <form method="post" action="/email_change"> | ||
| 883 | + <label class="auth-field"> | ||
| 884 | + <span class="auth-label">(t(lang, Key::NewEmailLabel))</span> | ||
| 885 | + <input | ||
| 886 | + class="auth-input auth-input-mono" | ||
| 887 | + type="email" | ||
| 888 | + name="email" | ||
| 889 | + autocomplete="email" | ||
| 890 | + value=(user.email.clone()) | ||
| 891 | + required="" | ||
| 892 | + > | ||
| 893 | + </label> | ||
| 894 | + <button class="auth-submit" type="submit"> | ||
| 895 | + <span class="auth-submit-text">(t(lang, Key::EmailChangeButton))</span> | ||
| 896 | + </button> | ||
| 897 | + </form> | ||
| 898 | + <div class="auth-sub">(t(lang, Key::EmailChangeNote))</div> | ||
| 899 | + </div> | ||
| 864 | } | 900 | } |
| 865 | <div class="auth-footer">(t(lang, Key::BrandFooter))</div> | 901 | <div class="auth-footer">(t(lang, Key::BrandFooter))</div> |
| 866 | </div> | 902 | </div> |
| @@ -979,3 +1015,42 @@ async fn reset_page(cx: &Cx) -> Result<Response> { | |||
| 979 | .await? | 1015 | .await? |
| 980 | .into_response(cx) | 1016 | .into_response(cx) |
| 981 | } | 1017 | } |
| 1018 | + | ||
| 1019 | +/// The address-change link's destination: a card naming the address being | ||
| 1020 | +/// gained, and the one button that agrees to it. A GET never mutates — | ||
| 1021 | +/// mail scanners prefetch links — so agreeing is this card's one POST. | ||
| 1022 | +#[route(GET "/email/{token}")] | ||
| 1023 | +async fn email_change_page(cx: &Cx) -> Result<Response> { | ||
| 1024 | + let lang = Lang::En; | ||
| 1025 | + let token: &str = path_param::<Token>(cx); | ||
| 1026 | + let Some(new_email) = im_core::accounts::email_change_link(&server::app(cx).store, token).await? | ||
| 1027 | + else { | ||
| 1028 | + return see_other("/login?error=email_change_invalid").into_response(cx); | ||
| 1029 | + }; | ||
| 1030 | + let stage = view! { | ||
| 1031 | + cx => | ||
| 1032 | + <main class="auth-stage"> | ||
| 1033 | + <div class="auth-column"> | ||
| 1034 | + (wordmark(cx).await?) | ||
| 1035 | + <div class="auth-card"> | ||
| 1036 | + <div class="auth-head"> | ||
| 1037 | + <div class="auth-title">(t(lang, Key::EmailConfirmTitle))</div> | ||
| 1038 | + <div class="auth-sub"> | ||
| 1039 | + (crate::i18n::email_confirm_sub(lang, &escape(&new_email))) | ||
| 1040 | + </div> | ||
| 1041 | + </div> | ||
| 1042 | + <form method="post" action="/email" data-hard=""> | ||
| 1043 | + <input type="hidden" name="token" value=(token.to_string())> | ||
| 1044 | + <button class="auth-submit" type="submit"> | ||
| 1045 | + <span class="auth-submit-text">(t(lang, Key::ConfirmEmailButton))</span> | ||
| 1046 | + </button> | ||
| 1047 | + </form> | ||
| 1048 | + </div> | ||
| 1049 | + <div class="auth-footer">(t(lang, Key::BrandFooter))</div> | ||
| 1050 | + </div> | ||
| 1051 | + </main> | ||
| 1052 | + }; | ||
| 1053 | + shell(cx, t(lang, Key::EmailConfirmTitle), None, stage) | ||
| 1054 | + .await? | ||
| 1055 | + .into_response(cx) | ||
| 1056 | +} | ||