mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-03 22:01:50 +00:00
feat(web): Handle MSC4198 login hints
This commit is contained in:
17 files changed
+472
-83
No files matched your search
@@ -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"],
|
||||
})
|
||||
}
|
||||
@@ -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<Prompt>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
@@ -53,6 +58,8 @@ pub struct DeviceCodeResponse {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct DeviceCodeVerifyQuery {
|
||||
pub user_code: Option<String>,
|
||||
#[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<Self, Self::Err> {
|
||||
match s.split_once(':') {
|
||||
| Some(("mxid", user_id)) if let Ok(user_id) = user_id.parse::<OwnedUserId>() =>
|
||||
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,
|
||||
|
||||
@@ -135,6 +135,7 @@ struct PendingDeviceCodeGrant {
|
||||
requested_scopes: RequestedScopes,
|
||||
client_name: Option<String>,
|
||||
client_id: String,
|
||||
login_hint: Option<String>,
|
||||
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<String>,
|
||||
}
|
||||
|
||||
/// 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<DeviceCodeGrantInfo> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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<OwnedUserId> {
|
||||
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<u64> {
|
||||
|
||||
@@ -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<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
Expect(Query(LoginQuery { next, reauthenticate, intent })): Expect<Query<LoginQuery>>,
|
||||
Expect(Query(LoginQuery { next, reauthenticate, intent, login_hint })): Expect<
|
||||
Query<LoginQuery>,
|
||||
>,
|
||||
session_store: Session,
|
||||
user: User<true>,
|
||||
PostForm(form): PostForm<LoginForm>,
|
||||
) -> 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::<LoginHint>).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::<lettre::Address>().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<OwnedUserId>,
|
||||
login_hint: Option<LoginHint>,
|
||||
form: LoginForm,
|
||||
) -> Result<OwnedUserId, String> {
|
||||
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::<lettre::Address>().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::<OwnedUserId>(User::KEY).await;
|
||||
|
||||
|
||||
@@ -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<AccountManagementAction>,
|
||||
device_id: Option<OwnedDeviceId>,
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub(crate) struct AccountDeeplinkQuery {
|
||||
pub action: Option<AccountManagementAction>,
|
||||
pub device_id: Option<OwnedDeviceId>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
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<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
Expect(Query(query)): Expect<Query<AccountDeeplinkQuery>>,
|
||||
user: User<true>,
|
||||
) -> 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(),
|
||||
|
||||
@@ -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<T = Response, E = WebError> = std::result::Result<T, E>;
|
||||
|
||||
@@ -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<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
@@ -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<crate::State>,
|
||||
Extension(context): Extension<TemplateContext>,
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Query: LoginHintQuery>(
|
||||
services: &crate::State,
|
||||
context: TemplateContext,
|
||||
current_user: &UserId,
|
||||
login_hint: Option<&str>,
|
||||
query: &Query,
|
||||
) -> Option<Response> {
|
||||
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;
|
||||
}
|
||||
@@ -23,3 +23,10 @@
|
||||
<path fill-rule="evenodd" d="M1 11.5a.5.5 0 0 0 .5.5h11.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 11H1.5a.5.5 0 0 0-.5.5m14-7a.5.5 0 0 1-.5.5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H14.5a.5.5 0 0 1 .5.5"/>
|
||||
</svg>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro box_arrow_right() %}
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-right" viewBox="0 0 16 16">
|
||||
<path fill-rule="evenodd" d="M10 12.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v2a.5.5 0 0 0 1 0v-2A1.5 1.5 0 0 0 9.5 2h-8A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h8a1.5 1.5 0 0 0 1.5-1.5v-2a.5.5 0 0 0-1 0z"/>
|
||||
<path fill-rule="evenodd" d="M15.854 8.354a.5.5 0 0 0 0-.708l-3-3a.5.5 0 0 0-.708.708L14.293 7.5H5.5a.5.5 0 0 0 0 1h8.793l-2.147 2.146a.5.5 0 0 0 .708.708z"/>
|
||||
</svg>
|
||||
{% endmacro %}
|
||||
@@ -13,7 +13,7 @@ Authorize client
|
||||
{% let client_name = client_metadata.client_name.as_deref().unwrap_or("Unknown application") %}
|
||||
<div class="panel narrow">
|
||||
<h1>Authorize {{ client_name }}</h1>
|
||||
<div class="avatars">
|
||||
<div class="avatar-pair">
|
||||
<div class="red-avatar">
|
||||
{{ user_avatar }}
|
||||
</div>
|
||||
@@ -24,7 +24,7 @@ Authorize client
|
||||
</div>
|
||||
|
||||
<div class="identity">
|
||||
Signed in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
Logged in as <code>{{ user_id }}</code>. <a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ logout_query }}">Switch accounts</a>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
{% extends "_layout.html.j2" %}
|
||||
{% import "_icons.html.j2" as icons %}
|
||||
|
||||
{%- block head -%}
|
||||
<link rel="stylesheet" href="{{ crate::ROUTE_PREFIX }}/resources/switch-account.css">
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block title -%}
|
||||
Select an account
|
||||
{%- endblock -%}
|
||||
|
||||
{%- block content -%}
|
||||
<div class="panel narrow">
|
||||
<h1>Select an account</h1>
|
||||
|
||||
<p>
|
||||
Welcome back! Which account would you like to continue with?
|
||||
</p>
|
||||
|
||||
<div class="account-chooser red-avatar">
|
||||
<a href="?{{ continue_query }}">
|
||||
{{ current_user_avatar }}
|
||||
<span>Continue as <b>{{ current_user_name }}</b></span>
|
||||
<code>{{ current_user_id }}</code>
|
||||
</a>
|
||||
<a href="{{ crate::ROUTE_PREFIX }}/account/logout?{{ switch_account_query }}">
|
||||
{{ new_user_avatar }}
|
||||
<span>Continue as <b>{{ new_user_name }}</b></span>
|
||||
<code>{{ new_user_id }}</code>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{%- endblock -%}
|
||||
+11
-6
@@ -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<LoginIntent>,
|
||||
#[serde(default)]
|
||||
pub login_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[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<const ALLOW_LOCKED: bool> User<ALLOW_LOCKED> {
|
||||
|
||||
/// 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<OwnedUserId, WebError> {
|
||||
pub(crate) fn expect(self, or: LoginTarget) -> Result<OwnedUserId, WebError> {
|
||||
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() }))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user