From 5339cead1025a8d79b6e4b4267ab7d99c593df14 Mon Sep 17 00:00:00 2001 From: Ginger Date: Thu, 3 Dec 2026 12:50:11 -0500 Subject: [PATCH] feat(web): Handle MSC4198 login hints --- src/api/client/oauth/server_metadata.rs | 4 + src/service/oauth/grant.rs | 33 ++++- src/service/oauth/mod.rs | 13 +- src/service/users/account.rs | 36 +++++- src/web/pages/account/login.rs | 117 ++++++++++++------ src/web/pages/account/mod.rs | 46 ++++++- src/web/pages/mod.rs | 1 + src/web/pages/oauth/grant.rs | 61 ++++++++- src/web/pages/resources/common.css | 11 ++ src/web/pages/resources/components.css | 25 ++++ src/web/pages/resources/grant.css | 20 --- src/web/pages/resources/switch-account.css | 35 ++++++ src/web/pages/switch_account.rs | 92 ++++++++++++++ src/web/pages/templates/_icons.html.j2 | 7 ++ src/web/pages/templates/grant.html.j2 | 4 +- .../pages/templates/switch_account.html.j2 | 33 +++++ src/web/session/mod.rs | 17 ++- 17 files changed, 472 insertions(+), 83 deletions(-) create mode 100644 src/web/pages/resources/switch-account.css create mode 100644 src/web/pages/switch_account.rs create mode 100644 src/web/pages/templates/switch_account.html.j2 diff --git a/src/api/client/oauth/server_metadata.rs b/src/api/client/oauth/server_metadata.rs index 331289af2..05d023d8c 100644 --- a/src/api/client/oauth/server_metadata.rs +++ b/src/api/client/oauth/server_metadata.rs @@ -70,5 +70,9 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value "response_types_supported": ["code"], "revocation_endpoint": endpoint_base.join(TOKEN_REVOKE_PATH).unwrap(), "token_endpoint": endpoint_base.join(TOKEN_PATH).unwrap(), + // NOTE: This isn't gated behind an experiment because MSC4198 is extremely simple, only specifying + // a couple query parameters and a syntax for login hints. + // The actual account-switching behavior it enables is implementation-defined and thus at no risk of drifting away from the MSC. + "org.matrix.msc4198.login_hint_types_supported": ["mxid"], }) } diff --git a/src/service/oauth/grant.rs b/src/service/oauth/grant.rs index b42506f1b..54d53db3f 100644 --- a/src/service/oauth/grant.rs +++ b/src/service/oauth/grant.rs @@ -3,10 +3,11 @@ use std::{ collections::BTreeSet, error::Error, fmt::{Debug, Display}, + str::FromStr, }; use regex::regex; -use ruma::{OwnedDeviceId, api::OAuthClientScope}; +use ruma::{OwnedDeviceId, OwnedUserId, api::OAuthClientScope}; use serde::{Deserialize, Serialize}; use url::Url; @@ -26,6 +27,8 @@ pub struct AuthorizationCodeQuery { pub code_challenge_method: CodeChallengeMethod, #[serde(default)] pub prompt: Option, + #[serde(default)] + pub login_hint: Option, } #[derive(Deserialize, Serialize)] @@ -38,6 +41,8 @@ pub struct AuthorizationCodeResponse { pub struct DeviceCodeRequest { pub client_id: String, pub scope: RawScopes, + #[serde(default, rename = "org.matrix.msc4198.login_hint")] + pub login_hint: Option, } #[derive(Deserialize, Serialize)] @@ -53,6 +58,8 @@ pub struct DeviceCodeResponse { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct DeviceCodeVerifyQuery { pub user_code: Option, + #[serde(default, skip_serializing_if = "core::ops::Not::not")] + pub ignore_login_hint: bool, } #[derive(Debug, Clone, Default, Deserialize, Serialize)] @@ -174,6 +181,30 @@ impl RawScopes { } } +pub enum LoginHint { + Mxid(OwnedUserId), +} + +impl FromStr for LoginHint { + type Err = (); + + fn from_str(s: &str) -> Result { + match s.split_once(':') { + | Some(("mxid", user_id)) if let Ok(user_id) = user_id.parse::() => + Ok(Self::Mxid(user_id)), + | _ => Err(()), + } + } +} + +impl Display for LoginHint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + | Self::Mxid(user_id) => write!(f, "mxid:{user_id}"), + } + } +} + #[derive(Serialize, Debug, Clone)] pub struct OAuthError { pub error: ErrorCode, diff --git a/src/service/oauth/mod.rs b/src/service/oauth/mod.rs index bea18ca66..fa50006c9 100644 --- a/src/service/oauth/mod.rs +++ b/src/service/oauth/mod.rs @@ -135,6 +135,7 @@ struct PendingDeviceCodeGrant { requested_scopes: RequestedScopes, client_name: Option, client_id: String, + login_hint: Option, requested_at: SystemTime, } @@ -165,6 +166,7 @@ pub struct DeviceCodeGrantInfo { pub device_code: String, pub client_metadata: ClientMetadata, pub requested_scopes: RequestedScopes, + pub login_hint: Option, } /// A time-limited grant for a client to perform some sensitive action. @@ -422,6 +424,7 @@ impl Service { requested_scopes, client_name: client_metadata.client_name, client_id: query.client_id, + login_hint: query.login_hint, requested_at: SystemTime::now(), }; @@ -442,7 +445,7 @@ impl Service { &self, supplied_user_code: &str, ) -> Option { - let (device_code, client_id, requested_scopes) = { + let (device_code, client_id, requested_scopes, login_hint) = { let pending_grants = self.pending_device_code_grants.lock(); let (device_code, grant) = pending_grants @@ -451,7 +454,12 @@ impl Service { matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code) })?; - (device_code.clone(), grant.client_id.clone(), grant.requested_scopes.clone()) + ( + device_code.clone(), + grant.client_id.clone(), + grant.requested_scopes.clone(), + grant.login_hint.clone(), + ) }; let client_metadata = self @@ -463,6 +471,7 @@ impl Service { device_code, client_metadata, requested_scopes, + login_hint, }) } diff --git a/src/service/users/account.rs b/src/service/users/account.rs index 53fb3746f..05ccdacd4 100644 --- a/src/service/users/account.rs +++ b/src/service/users/account.rs @@ -15,7 +15,10 @@ use futures::{FutureExt, Stream, StreamExt}; use lettre::Address; use ruma::{ MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId, - api::client::profile::PropagateTo, + api::client::{ + profile::PropagateTo, + uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier}, + }, events::{ GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent, invite_permission_config::InvitePermissionAction, push_rules::PushRulesEvent, @@ -721,6 +724,37 @@ impl super::Service { Ok(user_id) } + /// Look up a user identifier. If a user ID is returned, it will be local to + /// this server, but may refer to a nonexistent account. + pub async fn lookup_by_identifier(&self, identifier: UserIdentifier) -> Option { + match identifier { + | UserIdentifier::Email(EmailUserIdentifier { address, .. }) => { + let address = address.parse().ok()?; + + let localpart = self + .services + .threepid + .get_localpart_for_email(&address) + .await?; + + Some( + UserId::parse(format!( + "@{localpart}:{}", + self.services.globals.server_name() + )) + .unwrap(), + ) + }, + | UserIdentifier::Matrix(MatrixUserIdentifier { user, .. }) => UserId::parse(&user) + .ok() + .filter(|user_id| self.services.globals.user_is_local(user_id)) + .or_else(|| { + UserId::parse(format!("@{user}:{}", self.services.globals.server_name())).ok() + }), + | _ => None, + } + } + /// Creates an OpenID token, which can be used to prove that a user has /// access to an account (primarily for integrations) pub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result { diff --git a/src/web/pages/account/login.rs b/src/web/pages/account/login.rs index 6cbc3d42c..cde147087 100644 --- a/src/web/pages/account/login.rs +++ b/src/web/pages/account/login.rs @@ -6,8 +6,8 @@ use axum::{ response::{IntoResponse, Redirect}, routing::{get, on}, }; -use conduwuit_api::client::handle_login; -use conduwuit_service::users::ProfileQuerier; +use conduwuit_core::{error, result::FlatOk}; +use conduwuit_service::{oauth::grant::LoginHint, users::ProfileQuerier}; use openidconnect::core::CoreAuthPrompt; use ruma::{ OwnedUserId, @@ -76,12 +76,21 @@ struct LoginForm { async fn route_login( State(services): State, Extension(context): Extension, - Expect(Query(LoginQuery { next, reauthenticate, intent })): Expect>, + Expect(Query(LoginQuery { next, reauthenticate, intent, login_hint })): Expect< + Query, + >, session_store: Session, user: User, PostForm(form): PostForm, ) -> Result { - let user_id = user.into_session().map(|session| session.user_id); + let current_user = user.into_session().map(|session| session.user_id); + let login_hint = login_hint.as_deref().map(str::parse::).flat_ok(); + + if let Some(LoginHint::Mxid(hint_user)) = &login_hint + && !services.globals.user_is_local(hint_user) + { + return Err(WebError::BadRequest("Login hint is not a local user.".to_owned())); + } let login_type = if services.oidc.enabled() { let (session, redirect_url) = services @@ -96,7 +105,10 @@ async fn route_login( session_store .insert(OIDC_SESSION_ID_KEY, OidcSession { next: next.clone().unwrap_or_default(), - state: OidcSessionState::CodeExchange { expected_user: user_id.clone(), session }, + state: OidcSessionState::CodeExchange { + expected_user: current_user.clone(), + session, + }, }) .await .expect("should be able to serialize OIDC session"); @@ -116,12 +128,22 @@ async fn route_login( } }; - let body = match &user_id { - | None => LoginBody::Unauthenticated { + let body = match (¤t_user, &login_hint) { + | (None, None) => LoginBody::Unauthenticated { server_name: services.globals.server_name().to_string(), next: next.clone(), }, - | Some(user_id) => { + | (None, Some(LoginHint::Mxid(new_user))) => { + let user_card = UserCard::for_local_user( + &services, + new_user.to_owned(), + ProfileQuerier::Anonymous, + ) + .await; + + LoginBody::Authenticated { user_card } + }, + | (Some(user_id), _) => { if !reauthenticate { return response!(Redirect::to(&next.unwrap_or_default().target_path())); } @@ -136,41 +158,10 @@ async fn route_login( let mut template = Login::new(context, body, login_type, None); if let Some(form) = form { - let login_result = match (user_id, form.identifier) { - | (Some(user_id), _) => { - // The user is already authenticated, we need to check their - // password - services - .users - .check_password(&user_id, &form.password) - .await - }, - | (None, Some(identifier)) => { - // The user isn't authenticated, we need to log them in - let identifier = if identifier.parse::().is_ok() { - UserIdentifier::Email(EmailUserIdentifier::new(identifier)) - } else { - UserIdentifier::Matrix(MatrixUserIdentifier::new(identifier)) - }; - - handle_login(&services, Some(&identifier), &form.password, None).await - }, - | (None, None) => { - // The user isn't authenticated and didn't supply an identity - return response!(WebError::BadRequest("No identity provided".to_owned())); - }, - }; - - let user_id = match login_result { + let user_id = match perform_login(&services, current_user, login_hint, form).await { | Ok(user_id) => user_id, | Err(err) => { - let error_message = if let conduwuit_core::Error::Request(_, message, _) = err { - message.into_owned() - } else { - "Internal login error".to_owned() - }; - - template.login_error = Some(error_message); + template.login_error = Some(err); return response!(template); }, }; @@ -188,6 +179,50 @@ async fn route_login( response!(template) } +async fn perform_login( + services: &crate::State, + current_user: Option, + login_hint: Option, + form: LoginForm, +) -> Result { + let logging_in_user = if let Some(current_user) = current_user { + current_user + } else if let Some(LoginHint::Mxid(hint_user)) = login_hint { + hint_user + } else if let Some(identifier) = form.identifier { + let identifier = if identifier.parse::().is_ok() { + UserIdentifier::Email(EmailUserIdentifier::new(identifier)) + } else { + UserIdentifier::Matrix(MatrixUserIdentifier::new(identifier)) + }; + + if let Some(identified_user) = services.users.lookup_by_identifier(identifier).await { + identified_user + } else { + return Err("Failed to parse username or email address.".to_owned()); + } + } else { + return Err("No identity provided.".to_owned()); + }; + + if services.users.is_login_disabled(&logging_in_user).await { + return Err("This account is blocked from logging in.".to_owned()); + } + + match services + .users + .check_password(&logging_in_user, &form.password) + .await + { + | Ok(user_id) => Ok(user_id), + | Err(conduwuit_core::Error::Request(_, message, _)) => Err(message.into_owned()), + | Err(err) => { + error!(?logging_in_user, "Internal error logging in: {err}"); + Err("Internal error.".to_owned()) + }, + } +} + async fn get_logout(session: Session, RawQuery(query): RawQuery) -> impl IntoResponse { let _ = session.remove::(User::KEY).await; diff --git a/src/web/pages/account/mod.rs b/src/web/pages/account/mod.rs index 7e55cb063..3ffcb2a9a 100644 --- a/src/web/pages/account/mod.rs +++ b/src/web/pages/account/mod.rs @@ -10,6 +10,7 @@ use futures::StreamExt; use ruma::{ OwnedClientSecret, OwnedDeviceId, OwnedSessionId, api::client::discovery::get_authorization_server_metadata::v1::AccountManagementAction, + assign, }; use serde::{Deserialize, Serialize}; @@ -19,9 +20,10 @@ use crate::{ pages::{ Result, TemplateContext, components::{DeviceCard, DeviceCardStyle, UserCard}, + switch_account::{LoginHintQuery, prompt_to_switch_account}, }, response, - session::{LoginTarget, User}, + session::{LoginQuery, LoginTarget, User}, template, }; @@ -139,15 +141,49 @@ async fn get_account( })) } -#[derive(Deserialize)] -struct AccountDeeplinkQuery { - action: Option, - device_id: Option, +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(crate) struct AccountDeeplinkQuery { + pub action: Option, + pub device_id: Option, + #[serde(default)] + pub login_hint: Option, +} + +impl LoginHintQuery for AccountDeeplinkQuery { + fn into_login_target(self) -> LoginTarget { LoginTarget::AccountDeeplink(self) } + + fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { login_hint: None }) } } async fn get_account_deeplink( + State(services): State, + Extension(context): Extension, Expect(Query(query)): Expect>, + user: User, ) -> Result { + if let Some(current_user) = user.into_session() { + if let Some(switcher) = prompt_to_switch_account( + &services, + context, + ¤t_user.user_id, + query.login_hint.as_deref(), + &query, + ) + .await + { + return Ok(switcher); + } + } else { + // We redirect to the login page ourselves instead of letting the + // handler for the deeplink's target do it so that we can pass the login + // hint to the login page. + return Err(WebError::LoginRequired(LoginQuery { + next: Some(LoginTarget::AccountDeeplink(query.suppress_login_hint())), + login_hint: query.login_hint, + ..Default::default() + })); + } + let redirect_target = match query.action.unwrap_or(AccountManagementAction::Profile) { | AccountManagementAction::AccountDeactivate => "deactivate".to_owned(), | AccountManagementAction::CrossSigningReset => "cross_signing_reset".to_owned(), diff --git a/src/web/pages/mod.rs b/src/web/pages/mod.rs index 28a442785..404fa2a69 100644 --- a/src/web/pages/mod.rs +++ b/src/web/pages/mod.rs @@ -20,6 +20,7 @@ pub(super) mod media; pub(super) mod oauth; pub(super) mod oidc; pub(super) mod resources; +mod switch_account; pub(super) mod threepid; type Result = std::result::Result; diff --git a/src/web/pages/oauth/grant.rs b/src/web/pages/oauth/grant.rs index 4aead9e9b..b277c4168 100644 --- a/src/web/pages/oauth/grant.rs +++ b/src/web/pages/oauth/grant.rs @@ -12,7 +12,7 @@ use conduwuit_service::{ }, users::ProfileQuerier, }; -use ruma::{OwnedUserId, api::OAuthClientScope}; +use ruma::{OwnedUserId, api::OAuthClientScope, assign}; use serde::{Deserialize, de::IgnoredAny}; use crate::{ @@ -22,6 +22,7 @@ use crate::{ GET_POST, Result, TemplateContext, account::register::{RegisterQuery, RequestedRegistrationFlow}, components::{Avatar, ClientScopes, UserCard}, + switch_account::{LoginHintQuery, prompt_to_switch_account}, }, response, session::{LoginIntent, LoginQuery, LoginTarget, User}, @@ -46,6 +47,12 @@ template! { } } +impl LoginHintQuery for AuthorizationCodeQuery { + fn into_login_target(self) -> LoginTarget { LoginTarget::AuthorizationCode(self) } + + fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { login_hint: None }) } +} + async fn route_authorization_code( State(services): State, Extension(context): Extension, @@ -57,7 +64,7 @@ async fn route_authorization_code( user.user_id } else { let is_first_run = services.firstrun.is_first_run(); - let next = LoginTarget::AuthorizationCode(query.clone()); + let next = LoginTarget::AuthorizationCode(query.suppress_login_hint()); let uri = if query .prompt @@ -84,6 +91,7 @@ async fn route_authorization_code( ROUTE_PREFIX, serde_urlencoded::to_string(LoginQuery { next: Some(next), + login_hint: query.login_hint, ..Default::default() }) .unwrap() @@ -93,6 +101,18 @@ async fn route_authorization_code( return response!(Redirect::to(&uri)); }; + if let Some(switcher) = prompt_to_switch_account( + &services, + context.clone(), + &user_id, + query.login_hint.as_deref(), + &query, + ) + .await + { + return Ok(switcher); + } + if form.is_some() { let redirect_uri = services .oauth @@ -170,6 +190,12 @@ enum DeviceCodeGrantBody { Success, } +impl LoginHintQuery for DeviceCodeVerifyQuery { + fn into_login_target(self) -> LoginTarget { LoginTarget::DeviceCode(self) } + + fn suppress_login_hint(&self) -> Self { assign!(self.clone(), { ignore_login_hint: true }) } +} + async fn route_device_code( State(services): State, Extension(context): Extension, @@ -180,13 +206,25 @@ async fn route_device_code( let user_id = if let Some(user) = user.into_session() { user.user_id } else { - let next = LoginTarget::DeviceCode(query.clone()); + let next = LoginTarget::DeviceCode(query.suppress_login_hint()); + + let login_hint = if let Some(user_code) = &query.user_code + && let Some(grant_info) = services.oauth.grant_info_for_user_code(user_code).await + { + grant_info.login_hint + } else { + None + }; let uri = format!( "{}/account/login?{}", ROUTE_PREFIX, - serde_urlencoded::to_string(LoginQuery { next: Some(next), ..Default::default() }) - .unwrap() + serde_urlencoded::to_string(LoginQuery { + next: Some(next), + login_hint, + ..Default::default() + }) + .unwrap() ); return response!(Redirect::to(&uri)); @@ -206,6 +244,19 @@ async fn route_device_code( )); }; + if !query.ignore_login_hint + && let Some(switcher) = prompt_to_switch_account( + &services, + context.clone(), + &user_id, + grant_info.login_hint.as_deref(), + &query, + ) + .await + { + return Ok(switcher); + } + let RequestedScopes { device_id, mut scopes } = grant_info.requested_scopes; let existing_session_info = if let Some(device_id) = &device_id { diff --git a/src/web/pages/resources/common.css b/src/web/pages/resources/common.css index 0ead096d1..40cfc9d7f 100644 --- a/src/web/pages/resources/common.css +++ b/src/web/pages/resources/common.css @@ -392,6 +392,17 @@ ul.list-group { } } +.button-group { + display: flex; + gap: 0.5rem; + align-items: center; + + > a, button { + text-align: center; + flex: 1 fit-content; + } +} + .bi { display: inline-block; vertical-align: -.125em; diff --git a/src/web/pages/resources/components.css b/src/web/pages/resources/components.css index 4993d1140..712401fa3 100644 --- a/src/web/pages/resources/components.css +++ b/src/web/pages/resources/components.css @@ -43,6 +43,11 @@ font-weight: normal; font-size: small; font-family: monospace; + + &:only-child { + color: var(--text-color); + font-size: inherit; + } } } @@ -92,3 +97,23 @@ gap: 10px; margin-top: 10px; } + +.avatar-pair { + justify-content: center; + display: flex; + flex-direction: row; + + .separator { + align-self: center; + margin-inline: 1em; + color: var(--secondary); + font-size: x-large; + user-select: none; + + svg { + vertical-align: middle; + width: 24px; + height: 24px; + } + } +} diff --git a/src/web/pages/resources/grant.css b/src/web/pages/resources/grant.css index 34214795a..60b142dfc 100644 --- a/src/web/pages/resources/grant.css +++ b/src/web/pages/resources/grant.css @@ -1,23 +1,3 @@ -.avatars { - justify-content: center; - display: flex; - flex-direction: row; - - .separator { - align-self: center; - margin-inline: 1em; - color: var(--secondary); - font-size: x-large; - user-select: none; - - svg { - vertical-align: middle; - width: 24px; - height: 24px; - } - } -} - .identity { margin-block: 1em; color: var(--secondary); diff --git a/src/web/pages/resources/switch-account.css b/src/web/pages/resources/switch-account.css new file mode 100644 index 000000000..60ab072ad --- /dev/null +++ b/src/web/pages/resources/switch-account.css @@ -0,0 +1,35 @@ +.account-chooser { + display: flex; + gap: 1rem; + + @media (max-width: 425px) { + flex-direction: column; + } + + a { + display: flex; + flex: 1; + flex-direction: column; + align-items: center; + text-decoration: none; + text-align: center; + color: var(--text-color); + + border: 1px solid var(--c1); + border-radius: var(--border-radius-sm); + + padding: 1rem 0; + + .avatar { + margin-bottom: 0.5rem; + } + + code { + font-size: small; + } + + &:hover { + background-color: var(--card-bg); + } + } +} diff --git a/src/web/pages/switch_account.rs b/src/web/pages/switch_account.rs new file mode 100644 index 000000000..9f7690573 --- /dev/null +++ b/src/web/pages/switch_account.rs @@ -0,0 +1,92 @@ +use axum::response::{IntoResponse, Response}; +use conduwuit_core::result::FlatOk; +use conduwuit_service::{oauth::grant::LoginHint, users::ProfileQuerier}; +use ruma::UserId; +use serde::Serialize; + +use crate::{ + pages::{TemplateContext, components::Avatar}, + session::{LoginQuery, LoginTarget}, + template, +}; + +template! { + struct SwitchAccount<'a> use "switch_account.html.j2" { + current_user_avatar: Avatar, + new_user_avatar: Avatar, + current_user_name: String, + new_user_name: String, + current_user_id: &'a UserId, + new_user_id: &'a UserId, + switch_account_query: String, + continue_query: String + } +} + +pub(super) async fn prompt_to_switch_account( + services: &crate::State, + context: TemplateContext, + current_user: &UserId, + login_hint: Option<&str>, + query: &Query, +) -> Option { + let Some(LoginHint::Mxid(new_user)) = login_hint.map(str::parse).flat_ok() else { + return None; + }; + + if current_user == new_user { + return None; + } + + let switch_account_query = serde_urlencoded::to_string(LoginQuery { + next: Some(query.suppress_login_hint().into_login_target()), + login_hint: Some(LoginHint::Mxid(new_user.clone()).to_string()), + ..Default::default() + }) + .unwrap(); + + let continue_query = serde_urlencoded::to_string(query.suppress_login_hint()).unwrap(); + + let current_user_name = services + .users + .displayname(current_user) + .await + .unwrap_or_else(|_| current_user.localpart().to_owned()); + let current_user_avatar = + Avatar::for_local_user(services, current_user, ProfileQuerier::Owner).await; + + let new_user_name = services + .users + .displayname(&new_user) + .await + .unwrap_or_else(|_| new_user.localpart().to_owned()); + let new_user_avatar = + Avatar::for_local_user(services, &new_user, ProfileQuerier::Other(current_user)).await; + + Some( + SwitchAccount::new( + context, + current_user_avatar, + new_user_avatar, + current_user_name, + new_user_name, + current_user, + &new_user, + switch_account_query, + continue_query, + ) + .into_response(), + ) +} + +/// A trait for query parameter structs that have a login hint. +pub(super) trait LoginHintQuery: Serialize + Sync { + /// Modify this query parameter struct to suppress + /// the login hint. The resulting query should keep the + /// page it belongs to from prompting the user to switch accounts. + fn suppress_login_hint(&self) -> Self; + + /// Wrap this query parameter struct in its particular variant of + /// [`LoginTarget`]. + fn into_login_target(self) -> LoginTarget; +} diff --git a/src/web/pages/templates/_icons.html.j2 b/src/web/pages/templates/_icons.html.j2 index 1fa139cc2..ecbea47d1 100644 --- a/src/web/pages/templates/_icons.html.j2 +++ b/src/web/pages/templates/_icons.html.j2 @@ -23,3 +23,10 @@ {% endmacro %} + +{% macro box_arrow_right() %} + + + + +{% endmacro %} diff --git a/src/web/pages/templates/grant.html.j2 b/src/web/pages/templates/grant.html.j2 index d8904d98b..988a666d9 100644 --- a/src/web/pages/templates/grant.html.j2 +++ b/src/web/pages/templates/grant.html.j2 @@ -13,7 +13,7 @@ Authorize client {% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %}

Authorize {{ client_name }}

-
+
{{ user_avatar }}
@@ -24,7 +24,7 @@ Authorize client
- Signed in as {{ user_id }}. Switch accounts + Logged in as {{ user_id }}. Switch accounts

diff --git a/src/web/pages/templates/switch_account.html.j2 b/src/web/pages/templates/switch_account.html.j2 new file mode 100644 index 000000000..0f737a59e --- /dev/null +++ b/src/web/pages/templates/switch_account.html.j2 @@ -0,0 +1,33 @@ +{% extends "_layout.html.j2" %} +{% import "_icons.html.j2" as icons %} + +{%- block head -%} + +{%- endblock -%} + +{%- block title -%} +Select an account +{%- endblock -%} + +{%- block content -%} +

+{%- endblock -%} diff --git a/src/web/session/mod.rs b/src/web/session/mod.rs index 54f1d5830..a53acf601 100644 --- a/src/web/session/mod.rs +++ b/src/web/session/mod.rs @@ -15,7 +15,10 @@ use ruma::{OwnedUserId, UserId}; use serde::{Deserialize, Serialize}; use tower_sessions::Session; -use crate::{ROUTE_PREFIX, WebError, pages::account::device::DevicePath}; +use crate::{ + ROUTE_PREFIX, WebError, + pages::account::{AccountDeeplinkQuery, device::DevicePath}, +}; pub(crate) mod store; @@ -27,6 +30,8 @@ pub(crate) struct LoginQuery { pub reauthenticate: bool, #[serde(default)] pub intent: Option, + #[serde(default)] + pub login_hint: Option, } #[derive(Clone, Debug, Default, Deserialize, Serialize)] @@ -35,6 +40,7 @@ pub(crate) enum LoginTarget { AuthorizationCode(AuthorizationCodeQuery), #[default] Account, + AccountDeeplink(AccountDeeplinkQuery), ChangePassword, ChangeEmail, CrossSigningReset, @@ -57,6 +63,8 @@ impl LoginTarget { ) .into(), | Self::Account => "account/".into(), + | Self::AccountDeeplink(query) => + format!("account/deeplink?{}", serde_urlencoded::to_string(query).unwrap()).into(), | Self::ChangePassword => "account/password/change".into(), | Self::ChangeEmail => "account/email/change/".into(), | Self::CrossSigningReset => "account/cross_signing_reset".into(), @@ -117,14 +125,11 @@ impl User { /// Extract the user ID, redirecting to the login page if the user isn't /// logged in. - pub(crate) fn expect(self, or_else: LoginTarget) -> Result { + pub(crate) fn expect(self, or: LoginTarget) -> Result { if let Some(session) = self.0 { Ok(session.user_id) } else { - Err(WebError::LoginRequired(LoginQuery { - next: Some(or_else), - ..Default::default() - })) + Err(WebError::LoginRequired(LoginQuery { next: Some(or), ..Default::default() })) } }