matrix_sdk/authentication/matrix/mod.rs
1// Copyright 2020 Damir Jelić
2// Copyright 2020 The Matrix.org Foundation C.I.C.
3// Copyright 2022 Famedly GmbH
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Types to interact with the native Matrix authentication API.
18
19#[cfg(feature = "sso-login")]
20use std::future::Future;
21use std::{borrow::Cow, fmt};
22
23use matrix_sdk_base::{SessionMeta, store::RoomLoadSettings};
24use ruma::{
25 api::{
26 OutgoingRequest,
27 auth_scheme::SendAccessToken,
28 client::{
29 account::register,
30 session::{
31 get_login_types, login, logout, refresh_token, sso_login, sso_login_with_provider,
32 },
33 uiaa::UserIdentifier,
34 },
35 },
36 serde::JsonObject,
37};
38use serde::{Deserialize, Serialize};
39use thiserror::Error;
40use tracing::{debug, error, info, instrument};
41use url::Url;
42
43use crate::{
44 Client, Error, RefreshTokenError, Result,
45 authentication::AuthData,
46 client::SessionChange,
47 error::{HttpError, HttpResult},
48};
49
50mod login_builder;
51
52pub use self::login_builder::LoginBuilder;
53#[cfg(feature = "sso-login")]
54pub use self::login_builder::SsoLoginBuilder;
55use super::SessionTokens;
56
57/// A high-level API to interact with the native Matrix authentication API.
58///
59/// To access this API, use [`Client::matrix_auth()`].
60#[derive(Debug, Clone)]
61pub struct MatrixAuth {
62 client: Client,
63}
64
65/// Errors that can occur when using the SSO API.
66#[derive(Debug, Error)]
67pub enum SsoError {
68 /// The supplied callback URL used to complete SSO is invalid.
69 #[error("callback URL invalid")]
70 CallbackUrlInvalid,
71}
72
73impl MatrixAuth {
74 pub(crate) fn new(client: Client) -> Self {
75 Self { client }
76 }
77
78 /// Gets the homeserver’s supported login types.
79 ///
80 /// This should be the first step when trying to log in so you can call the
81 /// appropriate method for the next step.
82 pub async fn get_login_types(&self) -> HttpResult<get_login_types::v3::Response> {
83 let request = get_login_types::v3::Request::new();
84 self.client.send(request).await
85 }
86
87 /// Get the URL to use to log in via Single Sign-On.
88 ///
89 /// Returns a URL that should be opened in a web browser to let the user
90 /// log in.
91 ///
92 /// After a successful login, the loginToken received at the redirect URL
93 /// should be used to log in with [`login_token`].
94 ///
95 /// # Arguments
96 ///
97 /// * `redirect_url` - The URL that will receive a `loginToken` after a
98 /// successful SSO login.
99 ///
100 /// * `idp_id` - The optional ID of the identity provider to log in with.
101 ///
102 /// [`login_token`]: #method.login_token
103 pub async fn get_sso_login_url(
104 &self,
105 redirect_url: &str,
106 idp_id: Option<&str>,
107 ) -> Result<String> {
108 let homeserver = self.client.homeserver();
109 let supported_versions = self.client.supported_versions().await?;
110
111 let request = if let Some(id) = idp_id {
112 sso_login_with_provider::v3::Request::new(id.to_owned(), redirect_url.to_owned())
113 .try_into_http_request::<Vec<u8>>(
114 homeserver.as_str(),
115 SendAccessToken::None,
116 Cow::Owned(supported_versions),
117 )
118 } else {
119 sso_login::v3::Request::new(redirect_url.to_owned()).try_into_http_request::<Vec<u8>>(
120 homeserver.as_str(),
121 SendAccessToken::None,
122 Cow::Owned(supported_versions),
123 )
124 };
125
126 match request {
127 Ok(req) => Ok(req.uri().to_string()),
128 Err(err) => Err(Error::from(HttpError::IntoHttp(err))),
129 }
130 }
131
132 /// Log into the server with a username and password.
133 ///
134 /// This can be used for the first login as well as for subsequent logins,
135 /// note that if the device ID isn't provided a new device will be created.
136 ///
137 /// If this isn't the first login, a device ID should be provided through
138 /// [`LoginBuilder::device_id`] to restore the correct stores.
139 ///
140 /// Alternatively the [`restore_session`] method can be used to restore a
141 /// logged-in client without the password.
142 ///
143 /// # Arguments
144 ///
145 /// * `user` - The user ID or user ID localpart of the user that should be
146 /// logged into the homeserver.
147 ///
148 /// * `password` - The password of the user.
149 ///
150 /// # Examples
151 ///
152 /// ```no_run
153 /// # use url::Url;
154 /// # let homeserver = Url::parse("http://example.com").unwrap();
155 /// # futures_executor::block_on(async {
156 /// use matrix_sdk::Client;
157 ///
158 /// let client = Client::new(homeserver).await?;
159 /// let user = "example";
160 ///
161 /// let response = client
162 /// .matrix_auth()
163 /// .login_username(user, "wordpass")
164 /// .initial_device_display_name("My bot")
165 /// .await?;
166 ///
167 /// println!(
168 /// "Logged in as {user}, got device_id {} and access_token {}",
169 /// response.device_id, response.access_token,
170 /// );
171 /// # anyhow::Ok(()) });
172 /// ```
173 ///
174 /// [`restore_session`]: #method.restore_session
175 pub fn login_username(&self, id: impl AsRef<str>, password: &str) -> LoginBuilder {
176 self.login_identifier(UserIdentifier::UserIdOrLocalpart(id.as_ref().to_owned()), password)
177 }
178
179 /// Log into the server with a user identifier and password.
180 ///
181 /// This is a more general form of [`login_username`][Self::login_username]
182 /// that also accepts third-party identifiers instead of just the user ID or
183 /// its localpart.
184 pub fn login_identifier(&self, id: UserIdentifier, password: &str) -> LoginBuilder {
185 LoginBuilder::new_password(self.clone(), id, password.to_owned())
186 }
187
188 /// Log into the server with a custom login type.
189 ///
190 /// # Arguments
191 ///
192 /// * `login_type` - Identifier of the custom login type, e.g.
193 /// `org.matrix.login.jwt`
194 ///
195 /// * `data` - The additional data which should be attached to the login
196 /// request.
197 ///
198 /// # Examples
199 ///
200 /// ```no_run
201 /// # use url::Url;
202 /// # let homeserver = Url::parse("http://example.com").unwrap();
203 /// # async {
204 /// use matrix_sdk::Client;
205 ///
206 /// let client = Client::new(homeserver).await?;
207 /// let user = "example";
208 ///
209 /// let response = client
210 /// .matrix_auth()
211 /// .login_custom(
212 /// "org.matrix.login.jwt",
213 /// [("token".to_owned(), "jwt_token_content".into())]
214 /// .into_iter()
215 /// .collect(),
216 /// )?
217 /// .initial_device_display_name("My bot")
218 /// .await?;
219 ///
220 /// println!(
221 /// "Logged in as {user}, got device_id {} and access_token {}",
222 /// response.device_id, response.access_token,
223 /// );
224 /// # anyhow::Ok(()) };
225 /// ```
226 pub fn login_custom(
227 &self,
228 login_type: &str,
229 data: JsonObject,
230 ) -> serde_json::Result<LoginBuilder> {
231 LoginBuilder::new_custom(self.clone(), login_type, data)
232 }
233
234 /// Log into the server with a token.
235 ///
236 /// This token is usually received in the SSO flow after following the URL
237 /// provided by [`get_sso_login_url`], note that this is not the access
238 /// token of a session.
239 ///
240 /// This should only be used for the first login.
241 ///
242 /// The [`restore_session`] method should be used to restore a logged-in
243 /// client after the first login.
244 ///
245 /// A device ID should be provided through [`LoginBuilder::device_id`] to
246 /// restore the correct stores, if the device ID isn't provided a new
247 /// device will be created.
248 ///
249 /// # Arguments
250 ///
251 /// * `token` - A login token.
252 ///
253 /// # Examples
254 ///
255 /// ```no_run
256 /// use matrix_sdk::Client;
257 /// # use url::Url;
258 /// # let homeserver = Url::parse("https://example.com").unwrap();
259 /// # let redirect_url = "http://localhost:1234";
260 /// # let login_token = "token";
261 /// # async {
262 /// let client = Client::new(homeserver).await.unwrap();
263 /// let auth = client.matrix_auth();
264 /// let sso_url = auth.get_sso_login_url(redirect_url, None);
265 ///
266 /// // Let the user authenticate at the SSO URL.
267 /// // Receive the loginToken param at the redirect_url.
268 ///
269 /// let response = auth
270 /// .login_token(login_token)
271 /// .initial_device_display_name("My app")
272 /// .await
273 /// .unwrap();
274 ///
275 /// println!(
276 /// "Logged in as {}, got device_id {} and access_token {}",
277 /// response.user_id, response.device_id, response.access_token,
278 /// );
279 /// # };
280 /// ```
281 ///
282 /// [`get_sso_login_url`]: #method.get_sso_login_url
283 /// [`restore_session`]: #method.restore_session
284 pub fn login_token(&self, token: &str) -> LoginBuilder {
285 LoginBuilder::new_token(self.clone(), token.to_owned())
286 }
287
288 /// A higher level wrapper around the methods to complete an SSO login after
289 /// the user has logged in through a webview. This method should be used
290 /// in tandem with [`MatrixAuth::get_sso_login_url`].
291 ///
292 /// # Arguments
293 ///
294 /// * `callback_url` - The received callback URL carrying the login token.
295 ///
296 /// # Examples
297 ///
298 /// ```no_run
299 /// use matrix_sdk::Client;
300 /// # use url::Url;
301 /// # let homeserver = Url::parse("https://example.com").unwrap();
302 /// # let redirect_url = "http://localhost:1234";
303 /// # let callback_url = Url::parse("http://localhost:1234?loginToken=token").unwrap();
304 /// # async {
305 /// let client = Client::new(homeserver).await.unwrap();
306 /// let auth = client.matrix_auth();
307 /// let sso_url = auth.get_sso_login_url(redirect_url, None);
308 ///
309 /// // Let the user authenticate at the SSO URL.
310 /// // Receive the callback_url.
311 ///
312 /// let response = auth
313 /// .login_with_sso_callback(callback_url)
314 /// .unwrap()
315 /// .initial_device_display_name("My app")
316 /// .await
317 /// .unwrap();
318 ///
319 /// println!(
320 /// "Logged in as {}, got device_id {} and access_token {}",
321 /// response.user_id, response.device_id, response.access_token,
322 /// );
323 /// # };
324 /// ```
325 pub fn login_with_sso_callback(&self, callback_url: Url) -> Result<LoginBuilder, SsoError> {
326 #[derive(Deserialize)]
327 struct QueryParameters {
328 #[serde(rename = "loginToken")]
329 login_token: Option<String>,
330 }
331
332 let query_string = callback_url.query().unwrap_or_default();
333 let query: QueryParameters =
334 serde_html_form::from_str(query_string).map_err(|_| SsoError::CallbackUrlInvalid)?;
335 let token = query.login_token.ok_or(SsoError::CallbackUrlInvalid)?;
336
337 Ok(self.login_token(token.as_str()))
338 }
339
340 /// Log into the server via Single Sign-On.
341 ///
342 /// This takes care of the whole SSO flow:
343 /// * Spawn a local http server
344 /// * Provide a callback to open the SSO login URL in a web browser
345 /// * Wait for the local http server to get the loginToken
346 /// * Call [`login_token`]
347 ///
348 /// If cancellation is needed the method should be wrapped in a cancellable
349 /// task. **Note** that users with root access to the system have the
350 /// ability to snoop in on the data/token that is passed to the local
351 /// HTTP server that will be spawned.
352 ///
353 /// If you need more control over the SSO login process, you should use
354 /// [`get_sso_login_url`] and [`login_token`] directly.
355 ///
356 /// This should only be used for the first login.
357 ///
358 /// The [`restore_session`] method should be used to restore a logged-in
359 /// client after the first login.
360 ///
361 /// # Arguments
362 ///
363 /// * `use_sso_login_url` - A callback that will receive the SSO Login URL.
364 /// It should usually be used to open the SSO URL in a browser and must
365 /// return `Ok(())` if the URL was successfully opened. If it returns
366 /// `Err`, the error will be forwarded.
367 ///
368 /// # Examples
369 ///
370 /// ```no_run
371 /// use matrix_sdk::Client;
372 /// # use url::Url;
373 /// # let homeserver = Url::parse("https://example.com").unwrap();
374 /// # async {
375 /// let client = Client::new(homeserver).await.unwrap();
376 ///
377 /// let response = client
378 /// .matrix_auth()
379 /// .login_sso(|sso_url| async move {
380 /// // Open sso_url
381 /// Ok(())
382 /// })
383 /// .initial_device_display_name("My app")
384 /// .await
385 /// .unwrap();
386 ///
387 /// println!(
388 /// "Logged in as {}, got device_id {} and access_token {}",
389 /// response.user_id, response.device_id, response.access_token
390 /// );
391 /// # };
392 /// ```
393 ///
394 /// [`get_sso_login_url`]: #method.get_sso_login_url
395 /// [`login_token`]: #method.login_token
396 /// [`restore_session`]: #method.restore_session
397 #[cfg(feature = "sso-login")]
398 pub fn login_sso<F, Fut>(&self, use_sso_login_url: F) -> SsoLoginBuilder<F>
399 where
400 F: FnOnce(String) -> Fut + Send,
401 Fut: Future<Output = Result<()>> + Send,
402 {
403 SsoLoginBuilder::new(self.clone(), use_sso_login_url)
404 }
405
406 /// Is the client logged in using the native Matrix authentication API.
407 pub fn logged_in(&self) -> bool {
408 self.client
409 .auth_ctx()
410 .auth_data
411 .get()
412 .is_some_and(|auth_data| matches!(auth_data, AuthData::Matrix))
413 }
414
415 /// Refresh the access token.
416 ///
417 /// When support for [refreshing access tokens] is activated on both the
418 /// homeserver and the client, access tokens have an expiration date and
419 /// need to be refreshed periodically. To activate support for refresh
420 /// tokens in the [`Client`], it needs to be done at login with the
421 /// [`LoginBuilder::request_refresh_token()`] method, or during account
422 /// registration.
423 ///
424 /// This method doesn't need to be called if
425 /// [`ClientBuilder::handle_refresh_tokens()`] is called during construction
426 /// of the `Client`. Otherwise, it should be called once when a refresh
427 /// token is available and an [`UnknownToken`] error is received.
428 /// If this call fails with another [`UnknownToken`] error, it means that
429 /// the session needs to be logged in again.
430 ///
431 /// It can also be called at any time when a refresh token is available, it
432 /// will invalidate the previous access token.
433 ///
434 /// The new tokens in the response will be used by the `Client` and should
435 /// be persisted to be able to [restore the session]. The response will
436 /// always contain an access token that replaces the previous one. It
437 /// can also contain a refresh token, in which case it will also replace
438 /// the previous one.
439 ///
440 /// This method is protected behind a lock, so calling this method several
441 /// times at once will only call the endpoint once and all subsequent calls
442 /// will wait for the result of the first call. The first call will
443 /// return `Ok(Some(response))` or the [`HttpError`] returned by the
444 /// endpoint, while the others will return `Ok(None)` if the token was
445 /// refreshed by the first call or a [`RefreshTokenError`] error, if it
446 /// failed.
447 ///
448 /// # Examples
449 ///
450 /// ```no_run
451 /// use matrix_sdk::{Client, Error};
452 /// use url::Url;
453 /// # async {
454 /// # fn get_credentials() -> (&'static str, &'static str) { ("", "") };
455 /// # fn persist_session(_: Option<matrix_sdk::AuthSession>) {};
456 ///
457 /// let homeserver = Url::parse("http://example.com")?;
458 /// let client = Client::new(homeserver).await?;
459 ///
460 /// let (user, password) = get_credentials();
461 /// let response = client
462 /// .matrix_auth()
463 /// .login_username(user, password)
464 /// .initial_device_display_name("My App")
465 /// .request_refresh_token()
466 /// .send()
467 /// .await?;
468 ///
469 /// persist_session(client.session());
470 ///
471 /// // Handle when an `M_UNKNOWN_TOKEN` error is encountered.
472 /// async fn on_unknown_token_err(client: &Client) -> Result<(), Error> {
473 /// let auth = client.matrix_auth();
474 ///
475 /// if client
476 /// .session_tokens()
477 /// .and_then(|tokens| tokens.refresh_token)
478 /// .is_some()
479 /// && auth.refresh_access_token().await.is_ok()
480 /// {
481 /// persist_session(client.session());
482 /// return Ok(());
483 /// }
484 ///
485 /// let (user, password) = get_credentials();
486 /// auth.login_username(user, password)
487 /// .request_refresh_token()
488 /// .send()
489 /// .await?;
490 ///
491 /// persist_session(client.session());
492 ///
493 /// Ok(())
494 /// }
495 /// # anyhow::Ok(()) };
496 /// ```
497 ///
498 /// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
499 /// [`UnknownToken`]: ruma::api::client::error::ErrorKind::UnknownToken
500 /// [restore the session]: Client::restore_session
501 /// [`ClientBuilder::handle_refresh_tokens()`]: crate::ClientBuilder::handle_refresh_tokens
502 pub async fn refresh_access_token(&self) -> Result<(), RefreshTokenError> {
503 macro_rules! fail {
504 ($lock:expr, $err:expr) => {
505 let error = $err;
506 *$lock = Err(error.clone());
507 return Err(error);
508 };
509 }
510
511 let refresh_token_lock = &self.client.auth_ctx().refresh_token_lock;
512 let Ok(mut guard) = refresh_token_lock.try_lock() else {
513 // Somebody else is also doing a token refresh; wait for it to finish first.
514 return refresh_token_lock.lock().await.clone();
515 };
516
517 let Some(mut session_tokens) = self.client.session_tokens() else {
518 fail!(guard, RefreshTokenError::RefreshTokenRequired);
519 };
520 let Some(refresh_token) = session_tokens.refresh_token.clone() else {
521 fail!(guard, RefreshTokenError::RefreshTokenRequired);
522 };
523
524 let request = refresh_token::v3::Request::new(refresh_token);
525 let res = self.client.send_inner(request, None, Default::default()).await;
526
527 match res {
528 Ok(res) => {
529 *guard = Ok(());
530
531 session_tokens.access_token = res.access_token;
532 if let Some(refresh_token) = res.refresh_token {
533 session_tokens.refresh_token = Some(refresh_token);
534 }
535
536 self.client.auth_ctx().set_session_tokens(session_tokens);
537
538 if let Some(save_session_callback) =
539 self.client.inner.auth_ctx.save_session_callback.get()
540 && let Err(err) = save_session_callback(self.client.clone())
541 {
542 error!("when saving session after refresh: {err}");
543 }
544
545 _ = self
546 .client
547 .inner
548 .auth_ctx
549 .session_change_sender
550 .send(SessionChange::TokensRefreshed);
551
552 Ok(())
553 }
554 Err(error) => {
555 let error = RefreshTokenError::MatrixAuth(error.into());
556 fail!(guard, error);
557 }
558 }
559 }
560
561 /// Register a user to the server.
562 ///
563 /// If registration was successful and a session token was returned by the
564 /// server, the client session is set (the client is logged in).
565 ///
566 /// # Arguments
567 ///
568 /// * `registration` - The easiest way to create this request is using the
569 /// [`register::v3::Request`] itself.
570 ///
571 /// # Examples
572 ///
573 /// ```no_run
574 /// use matrix_sdk::{
575 /// Client,
576 /// ruma::api::client::{
577 /// account::register::v3::Request as RegistrationRequest, uiaa,
578 /// },
579 /// };
580 /// # use url::Url;
581 /// # let homeserver = Url::parse("http://example.com").unwrap();
582 /// # async {
583 ///
584 /// let mut request = RegistrationRequest::new();
585 /// request.username = Some("user".to_owned());
586 /// request.password = Some("password".to_owned());
587 /// request.auth = Some(uiaa::AuthData::FallbackAcknowledgement(
588 /// uiaa::FallbackAcknowledgement::new("foobar".to_owned()),
589 /// ));
590 ///
591 /// let client = Client::new(homeserver).await.unwrap();
592 /// client.matrix_auth().register(request).await;
593 /// # };
594 /// ```
595 #[instrument(skip_all)]
596 pub async fn register(&self, request: register::v3::Request) -> Result<register::v3::Response> {
597 let homeserver = self.client.homeserver();
598 info!("Registering to {homeserver}");
599
600 #[cfg(feature = "e2e-encryption")]
601 let login_info = match (&request.username, &request.password) {
602 (Some(u), Some(p)) => Some(login::v3::LoginInfo::Password(login::v3::Password::new(
603 UserIdentifier::UserIdOrLocalpart(u.into()),
604 p.clone(),
605 ))),
606 _ => None,
607 };
608
609 let response = self.client.send(request).await?;
610 if let Some(session) = MatrixSession::from_register_response(&response) {
611 let _ = self
612 .set_session(
613 session,
614 RoomLoadSettings::default(),
615 #[cfg(feature = "e2e-encryption")]
616 login_info,
617 )
618 .await;
619 }
620 Ok(response)
621 }
622 /// Log out the current user.
623 pub async fn logout(&self) -> HttpResult<logout::v3::Response> {
624 let request = logout::v3::Request::new();
625 self.client.send(request).await
626 }
627
628 /// Get the whole native Matrix authentication session info of this client.
629 ///
630 /// Will be `None` if the client has not been logged in with the native
631 /// Matrix Authentication API.
632 ///
633 /// Can be used with [`MatrixAuth::restore_session`] to restore a previously
634 /// logged-in session.
635 pub fn session(&self) -> Option<MatrixSession> {
636 let meta = self.client.session_meta()?;
637 let tokens = self.client.session_tokens()?;
638 Some(MatrixSession { meta: meta.to_owned(), tokens })
639 }
640
641 /// Restore a previously logged in session.
642 ///
643 /// This can be used to restore the client to a logged in state, loading all
644 /// the stored state and encryption keys.
645 ///
646 /// Alternatively, if the whole session isn't stored the [`login`] method
647 /// can be used with a device ID.
648 ///
649 /// # Arguments
650 ///
651 /// * `session` - A session that the user already has from a previous login
652 /// call.
653 ///
654 /// * `room_load_settings` — Specify how many rooms must be restored; use
655 /// `::default()` if you don't know which value to pick.
656 ///
657 /// # Panics
658 ///
659 /// Panics if a session was already restored or logged in.
660 ///
661 /// # Examples
662 ///
663 /// ```no_run
664 /// use matrix_sdk::{
665 /// Client, SessionMeta, SessionTokens,
666 /// authentication::matrix::MatrixSession,
667 /// ruma::{device_id, user_id},
668 /// };
669 /// # use url::Url;
670 /// # async {
671 ///
672 /// let homeserver = Url::parse("http://example.com")?;
673 /// let client = Client::new(homeserver).await?;
674 ///
675 /// let session = MatrixSession {
676 /// meta: SessionMeta {
677 /// user_id: user_id!("@example:localhost").to_owned(),
678 /// device_id: device_id!("MYDEVICEID").to_owned(),
679 /// },
680 /// tokens: SessionTokens {
681 /// access_token: "My-Token".to_owned(),
682 /// refresh_token: None,
683 /// },
684 /// };
685 ///
686 /// client.restore_session(session).await?;
687 /// # anyhow::Ok(()) };
688 /// ```
689 ///
690 /// The `MatrixSession` object can also be created from the response the
691 /// [`LoginBuilder::send()`] method returns:
692 ///
693 /// ```no_run
694 /// use matrix_sdk::{Client, store::RoomLoadSettings};
695 /// use url::Url;
696 /// # async {
697 ///
698 /// let homeserver = Url::parse("http://example.com")?;
699 /// let client = Client::new(homeserver).await?;
700 /// let auth = client.matrix_auth();
701 ///
702 /// let response = auth.login_username("example", "my-password").send().await?;
703 ///
704 /// // Persist the `MatrixSession` so it can later be used to restore the login.
705 ///
706 /// auth.restore_session((&response).into(), RoomLoadSettings::default())
707 /// .await?;
708 /// # anyhow::Ok(()) };
709 /// ```
710 ///
711 /// [`login`]: #method.login
712 /// [`LoginBuilder::send()`]: crate::authentication::matrix::LoginBuilder::send
713 #[instrument(skip_all)]
714 pub async fn restore_session(
715 &self,
716 session: MatrixSession,
717 room_load_settings: RoomLoadSettings,
718 ) -> Result<()> {
719 debug!("Restoring Matrix auth session");
720 self.set_session(
721 session,
722 room_load_settings,
723 #[cfg(feature = "e2e-encryption")]
724 None,
725 )
726 .await?;
727 debug!("Done restoring Matrix auth session");
728 Ok(())
729 }
730
731 /// Receive a login response and update the homeserver and the base client
732 /// if needed.
733 ///
734 /// # Arguments
735 ///
736 /// * `response` - A successful login response.
737 pub(crate) async fn receive_login_response(
738 &self,
739 response: &login::v3::Response,
740 #[cfg(feature = "e2e-encryption")] login_info: Option<login::v3::LoginInfo>,
741 ) -> Result<()> {
742 self.client.maybe_update_login_well_known(response.well_known.as_ref());
743
744 self.set_session(
745 response.into(),
746 RoomLoadSettings::default(),
747 #[cfg(feature = "e2e-encryption")]
748 login_info,
749 )
750 .await?;
751
752 Ok(())
753 }
754
755 /// Set the Matrix authentication session.
756 ///
757 /// # Arguments
758 ///
759 /// * `session` — The session being opened.
760 ///
761 /// * `room_load_settings` — Specify how much rooms must be restored; use
762 /// `::default()` if you don't know which value to pick.
763 ///
764 /// # Panic
765 ///
766 /// Panics if authentication data was already set.
767 async fn set_session(
768 &self,
769 session: MatrixSession,
770 room_load_settings: RoomLoadSettings,
771 #[cfg(feature = "e2e-encryption")] login_info: Option<login::v3::LoginInfo>,
772 ) -> Result<()> {
773 // This API doesn't have any data but by setting this variant we protect the
774 // user from using both authentication APIs at once.
775 self.client
776 .auth_ctx()
777 .auth_data
778 .set(AuthData::Matrix)
779 .expect("Client authentication data was already set");
780 self.client.auth_ctx().set_session_tokens(session.tokens);
781 self.client
782 .base_client()
783 .activate(
784 session.meta,
785 room_load_settings,
786 #[cfg(feature = "e2e-encryption")]
787 None,
788 )
789 .await?;
790
791 #[cfg(feature = "e2e-encryption")]
792 {
793 use ruma::api::client::uiaa::{AuthData, Password};
794
795 let auth_data = match login_info {
796 Some(login::v3::LoginInfo::Password(login::v3::Password {
797 identifier: Some(identifier),
798 password,
799 ..
800 })) => Some(AuthData::Password(Password::new(identifier, password))),
801 // Other methods can't be immediately translated to an auth.
802 _ => None,
803 };
804
805 self.client.encryption().spawn_initialization_task(auth_data).await;
806 }
807
808 Ok(())
809 }
810}
811
812/// A user session using the native Matrix authentication API.
813///
814/// # Examples
815///
816/// ```
817/// use matrix_sdk::{
818/// SessionMeta, SessionTokens, authentication::matrix::MatrixSession,
819/// };
820/// use ruma::{device_id, user_id};
821///
822/// let session = MatrixSession {
823/// meta: SessionMeta {
824/// user_id: user_id!("@example:localhost").to_owned(),
825/// device_id: device_id!("MYDEVICEID").to_owned(),
826/// },
827/// tokens: SessionTokens {
828/// access_token: "My-Token".to_owned(),
829/// refresh_token: None,
830/// },
831/// };
832///
833/// assert_eq!(session.meta.device_id.as_str(), "MYDEVICEID");
834/// ```
835#[derive(Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
836pub struct MatrixSession {
837 /// The Matrix user session info.
838 #[serde(flatten)]
839 pub meta: SessionMeta,
840
841 /// The tokens used for authentication.
842 #[serde(flatten)]
843 pub tokens: SessionTokens,
844}
845
846#[cfg(not(tarpaulin_include))]
847impl fmt::Debug for MatrixSession {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 f.debug_struct("MatrixSession").field("meta", &self.meta).finish_non_exhaustive()
850 }
851}
852
853impl From<&login::v3::Response> for MatrixSession {
854 fn from(response: &login::v3::Response) -> Self {
855 let login::v3::Response { user_id, access_token, device_id, refresh_token, .. } = response;
856 Self {
857 meta: SessionMeta { user_id: user_id.clone(), device_id: device_id.clone() },
858 tokens: SessionTokens {
859 access_token: access_token.clone(),
860 refresh_token: refresh_token.clone(),
861 },
862 }
863 }
864}
865
866impl MatrixSession {
867 #[allow(clippy::question_mark)] // clippy falsely complains about the let-unpacking
868 fn from_register_response(response: ®ister::v3::Response) -> Option<Self> {
869 let register::v3::Response { user_id, access_token, device_id, refresh_token, .. } =
870 response;
871 Some(Self {
872 meta: SessionMeta { user_id: user_id.clone(), device_id: device_id.clone()? },
873 tokens: SessionTokens {
874 access_token: access_token.clone()?,
875 refresh_token: refresh_token.clone(),
876 },
877 })
878 }
879}