client: Remove session data other than the access token
This commit is contained in:
parent
e2be614552
commit
15c9e470c8
@ -3,34 +3,32 @@ use std::time::Duration;
|
|||||||
use assign::assign;
|
use assign::assign;
|
||||||
use async_stream::try_stream;
|
use async_stream::try_stream;
|
||||||
use futures_core::stream::Stream;
|
use futures_core::stream::Stream;
|
||||||
use ruma_client_api::r0::sync::sync_events::{
|
use ruma_client_api::r0::{
|
||||||
Filter as SyncFilter, Request as SyncRequest, Response as SyncResponse,
|
account::register::{self, RegistrationKind},
|
||||||
|
session::login::{self, LoginInfo, UserIdentifier},
|
||||||
|
sync::sync_events,
|
||||||
};
|
};
|
||||||
use ruma_common::presence::PresenceState;
|
use ruma_common::presence::PresenceState;
|
||||||
use ruma_identifiers::DeviceId;
|
use ruma_identifiers::DeviceId;
|
||||||
|
|
||||||
use super::{Client, Error, Identification, Session};
|
use super::{Client, Error};
|
||||||
|
|
||||||
|
/// Client-API specific functionality of `Client`.
|
||||||
impl Client {
|
impl Client {
|
||||||
/// Log in with a username and password.
|
/// Log in with a username and password.
|
||||||
///
|
///
|
||||||
/// In contrast to `api::r0::session::login::call()`, this method stores the
|
/// In contrast to [`request`], this method stores the access token returned by the endpoint in
|
||||||
/// session data returned by the endpoint in this client, instead of
|
/// this client, in addition to returning it.
|
||||||
/// returning it.
|
|
||||||
pub async fn log_in(
|
pub async fn log_in(
|
||||||
&self,
|
&self,
|
||||||
user: &str,
|
user: &str,
|
||||||
password: &str,
|
password: &str,
|
||||||
device_id: Option<&DeviceId>,
|
device_id: Option<&DeviceId>,
|
||||||
initial_device_display_name: Option<&str>,
|
initial_device_display_name: Option<&str>,
|
||||||
) -> Result<Session, Error<ruma_client_api::Error>> {
|
) -> Result<login::Response, Error<ruma_client_api::Error>> {
|
||||||
use ruma_client_api::r0::session::login::{
|
|
||||||
LoginInfo, Request as LoginRequest, UserIdentifier,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
let response = self
|
||||||
.request(assign!(
|
.request(assign!(
|
||||||
LoginRequest::new(
|
login::Request::new(
|
||||||
LoginInfo::Password { identifier: UserIdentifier::MatrixId(user), password }
|
LoginInfo::Password { identifier: UserIdentifier::MatrixId(user), password }
|
||||||
), {
|
), {
|
||||||
device_id,
|
device_id,
|
||||||
@ -39,92 +37,61 @@ impl Client {
|
|||||||
))
|
))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let session = Session {
|
*self.0.access_token.lock().unwrap() = Some(response.access_token.clone());
|
||||||
access_token: response.access_token,
|
|
||||||
identification: Some(Identification {
|
|
||||||
device_id: response.device_id,
|
|
||||||
user_id: response.user_id,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
*self.0.session.lock().unwrap() = Some(session.clone());
|
|
||||||
|
|
||||||
Ok(session)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register as a guest. In contrast to `api::r0::account::register::call()`,
|
/// Register as a guest.
|
||||||
/// this method stores the session data returned by the endpoint in this
|
///
|
||||||
/// client, instead of returning it.
|
/// In contrast to [`request`], this method stores the access token returned by the endpoint in
|
||||||
|
/// this client, in addition to returning it.
|
||||||
pub async fn register_guest(
|
pub async fn register_guest(
|
||||||
&self,
|
&self,
|
||||||
) -> Result<Session, Error<ruma_client_api::r0::uiaa::UiaaResponse>> {
|
) -> Result<register::Response, Error<ruma_client_api::r0::uiaa::UiaaResponse>> {
|
||||||
use ruma_client_api::r0::account::register::{self, RegistrationKind};
|
|
||||||
|
|
||||||
let response = self
|
let response = self
|
||||||
.request(assign!(register::Request::new(), { kind: RegistrationKind::Guest }))
|
.request(assign!(register::Request::new(), { kind: RegistrationKind::Guest }))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let session = Session {
|
*self.0.access_token.lock().unwrap() = response.access_token.clone();
|
||||||
// since we supply inhibit_login: false above, the access token needs to be there
|
|
||||||
// TODO: maybe unwrap is not the best solution though
|
|
||||||
access_token: response.access_token.unwrap(),
|
|
||||||
identification: Some(Identification {
|
|
||||||
// same as access_token
|
|
||||||
device_id: response.device_id.unwrap(),
|
|
||||||
user_id: response.user_id,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
*self.0.session.lock().unwrap() = Some(session.clone());
|
|
||||||
|
|
||||||
Ok(session)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register as a new user on this server.
|
/// Register as a new user on this server.
|
||||||
///
|
///
|
||||||
/// In contrast to `api::r0::account::register::call()`, this method stores
|
/// In contrast to [`request`], this method stores the access token returned by the endpoint in
|
||||||
/// the session data returned by the endpoint in this client, instead of
|
/// this client, in addition to returning it.
|
||||||
/// returning it.
|
|
||||||
///
|
///
|
||||||
/// The username is the local part of the returned user_id. If it is
|
/// The username is the local part of the returned user_id. If it is omitted from this request,
|
||||||
/// omitted from this request, the server will generate one.
|
/// the server will generate one.
|
||||||
pub async fn register_user(
|
pub async fn register_user(
|
||||||
&self,
|
&self,
|
||||||
username: Option<&str>,
|
username: Option<&str>,
|
||||||
password: &str,
|
password: &str,
|
||||||
) -> Result<Session, Error<ruma_client_api::r0::uiaa::UiaaResponse>> {
|
) -> Result<register::Response, Error<ruma_client_api::r0::uiaa::UiaaResponse>> {
|
||||||
use ruma_client_api::r0::account::register;
|
|
||||||
|
|
||||||
let response = self
|
let response = self
|
||||||
.request(assign!(register::Request::new(), { username, password: Some(password) }))
|
.request(assign!(register::Request::new(), { username, password: Some(password) }))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let session = Session {
|
*self.0.access_token.lock().unwrap() = response.access_token.clone();
|
||||||
// since we supply inhibit_login: false above, the access token needs to be there
|
|
||||||
// TODO: maybe unwrap is not the best solution though
|
|
||||||
access_token: response.access_token.unwrap(),
|
|
||||||
identification: Some(Identification {
|
|
||||||
// same as access_token
|
|
||||||
device_id: response.device_id.unwrap(),
|
|
||||||
user_id: response.user_id,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
*self.0.session.lock().unwrap() = Some(session.clone());
|
|
||||||
|
|
||||||
Ok(session)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convenience method that represents repeated calls to the sync_events endpoint as a stream.
|
/// Convenience method that represents repeated calls to the sync_events endpoint as a stream.
|
||||||
pub fn sync<'a>(
|
pub fn sync<'a>(
|
||||||
&self,
|
&self,
|
||||||
filter: Option<&'a SyncFilter<'a>>,
|
filter: Option<&'a sync_events::Filter<'a>>,
|
||||||
mut since: String,
|
mut since: String,
|
||||||
set_presence: &'a PresenceState,
|
set_presence: &'a PresenceState,
|
||||||
timeout: Option<Duration>,
|
timeout: Option<Duration>,
|
||||||
) -> impl Stream<Item = Result<SyncResponse, Error<ruma_client_api::Error>>> + 'a {
|
) -> impl Stream<Item = Result<sync_events::Response, Error<ruma_client_api::Error>>> + 'a {
|
||||||
let client = self.clone();
|
let client = self.clone();
|
||||||
try_stream! {
|
try_stream! {
|
||||||
loop {
|
loop {
|
||||||
let response = client
|
let response = client
|
||||||
.request(assign!(SyncRequest::new(), {
|
.request(assign!(sync_events::Request::new(), {
|
||||||
filter,
|
filter,
|
||||||
since: Some(&since),
|
since: Some(&since),
|
||||||
set_presence,
|
set_presence,
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
|
#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
|
||||||
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
|
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
|
||||||
//! A [Matrix](https://matrix.org/) client library.
|
//! A minimal [Matrix](https://matrix.org/) client library.
|
||||||
//!
|
//!
|
||||||
//! # Usage
|
//! # Usage
|
||||||
//!
|
//!
|
||||||
@ -24,17 +24,16 @@
|
|||||||
//! };
|
//! };
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! You can also pass an existing session to the `Client` constructor to restore a previous session
|
//! You can also pass an existing access token to the `Client` constructor to restore a previous
|
||||||
//! rather than calling `log_in`. This can also be used to create a session for an application
|
//! session rather than calling `log_in`. This can also be used to create a session for an
|
||||||
//! service that does not need to log in, but uses the access_token directly:
|
//! application service that does not need to log in, but uses the access_token directly:
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use ruma_client::{Client, Session};
|
//! use ruma_client::Client;
|
||||||
//!
|
//!
|
||||||
//! let work = async {
|
//! let work = async {
|
||||||
//! let homeserver_url = "https://example.com".parse().unwrap();
|
//! let homeserver_url = "https://example.com".parse().unwrap();
|
||||||
//! let session = Session{access_token: "as_access_token".to_string(), identification: None};
|
//! let client = Client::new(homeserver_url, Some("as_access_token".into()));
|
||||||
//! let client = Client::new(homeserver_url, Some(session));
|
|
||||||
//!
|
//!
|
||||||
//! // make calls to the API
|
//! // make calls to the API
|
||||||
//! };
|
//! };
|
||||||
@ -116,12 +115,8 @@ use ruma_serde::urlencoded;
|
|||||||
#[cfg(feature = "client-api")]
|
#[cfg(feature = "client-api")]
|
||||||
mod client_api;
|
mod client_api;
|
||||||
mod error;
|
mod error;
|
||||||
mod session;
|
|
||||||
|
|
||||||
pub use self::{
|
pub use self::error::Error;
|
||||||
error::Error,
|
|
||||||
session::{Identification, Session},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(not(feature = "_tls"))]
|
#[cfg(not(feature = "_tls"))]
|
||||||
type Connector = HttpConnector;
|
type Connector = HttpConnector;
|
||||||
@ -162,16 +157,16 @@ struct ClientData {
|
|||||||
hyper: HyperClient<Connector>,
|
hyper: HyperClient<Connector>,
|
||||||
|
|
||||||
/// User session data.
|
/// User session data.
|
||||||
session: Mutex<Option<Session>>,
|
access_token: Mutex<Option<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Client {
|
impl Client {
|
||||||
/// Creates a new client.
|
/// Creates a new client.
|
||||||
pub fn new(homeserver_url: Uri, session: Option<Session>) -> Self {
|
pub fn new(homeserver_url: Uri, access_token: Option<String>) -> Self {
|
||||||
Self(Arc::new(ClientData {
|
Self(Arc::new(ClientData {
|
||||||
homeserver_url,
|
homeserver_url,
|
||||||
hyper: HyperClient::builder().build(create_connector()),
|
hyper: HyperClient::builder().build(create_connector()),
|
||||||
session: Mutex::new(session),
|
access_token: Mutex::new(access_token),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -181,20 +176,20 @@ impl Client {
|
|||||||
pub fn custom(
|
pub fn custom(
|
||||||
client_builder: &hyper::client::Builder,
|
client_builder: &hyper::client::Builder,
|
||||||
homeserver_url: Uri,
|
homeserver_url: Uri,
|
||||||
session: Option<Session>,
|
access_token: Option<String>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self(Arc::new(ClientData {
|
Self(Arc::new(ClientData {
|
||||||
homeserver_url,
|
homeserver_url,
|
||||||
hyper: client_builder.build(create_connector()),
|
hyper: client_builder.build(create_connector()),
|
||||||
session: Mutex::new(session),
|
access_token: Mutex::new(access_token),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a copy of the current `Session`, if any.
|
/// Get a copy of the current `access_token`, if any.
|
||||||
///
|
///
|
||||||
/// Useful for serializing and persisting the session to be restored later.
|
/// Useful for serializing and persisting the session to be restored later.
|
||||||
pub fn session(&self) -> Option<Session> {
|
pub fn access_token(&self) -> Option<String> {
|
||||||
self.0.session.lock().expect("session mutex was poisoned").clone()
|
self.0.access_token.lock().expect("session mutex was poisoned").clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Makes a request to a Matrix API endpoint.
|
/// Makes a request to a Matrix API endpoint.
|
||||||
@ -213,11 +208,11 @@ impl Client {
|
|||||||
) -> Result<Request::IncomingResponse, Error<Request::EndpointError>> {
|
) -> Result<Request::IncomingResponse, Error<Request::EndpointError>> {
|
||||||
let client = self.0.clone();
|
let client = self.0.clone();
|
||||||
let mut http_request = {
|
let mut http_request = {
|
||||||
let session;
|
let lock;
|
||||||
let access_token = if Request::METADATA.authentication == AuthScheme::AccessToken {
|
let access_token = if Request::METADATA.authentication == AuthScheme::AccessToken {
|
||||||
session = client.session.lock().unwrap();
|
lock = client.access_token.lock().unwrap();
|
||||||
if let Some(s) = &*session {
|
if let Some(access_token) = &*lock {
|
||||||
SendAccessToken::IfRequired(s.access_token.as_str())
|
SendAccessToken::IfRequired(access_token.as_str())
|
||||||
} else {
|
} else {
|
||||||
return Err(Error::AuthenticationRequired);
|
return Err(Error::AuthenticationRequired);
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user