pub mod v3 {
use std::{borrow::Cow, fmt, time::Duration};
use as_variant::as_variant;
use ruma_common::{
OwnedDeviceId, OwnedServerName, OwnedUserId,
api::{auth_scheme::AppserviceTokenOptional, request, response},
metadata,
serde::JsonObject,
};
use serde::{
Deserialize, Deserializer, Serialize,
de::{self, DeserializeOwned},
};
use serde_json::Value as JsonValue;
use crate::uiaa::UserIdentifier;
metadata! {
method: POST,
rate_limited: true,
authentication: AppserviceTokenOptional,
history: {
1.0 => "/_matrix/client/r0/login",
1.1 => "/_matrix/client/v3/login",
}
}
#[request]
pub struct Request {
#[serde(flatten)]
pub login_info: LoginInfo,
#[serde(skip_serializing_if = "Option::is_none")]
pub device_id: Option<OwnedDeviceId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub initial_device_display_name: Option<String>,
#[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
pub refresh_token: bool,
}
#[response]
pub struct Response {
pub user_id: OwnedUserId,
pub access_token: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[deprecated = "\
Since Matrix Client-Server API r0.4.0. Clients should instead use the \
`user_id.server_name()` method if they require it.\
"]
pub home_server: Option<OwnedServerName>,
pub device_id: OwnedDeviceId,
#[serde(skip_serializing_if = "Option::is_none")]
pub well_known: Option<DiscoveryInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(
with = "ruma_common::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none",
rename = "expires_in_ms"
)]
pub expires_in: Option<Duration>,
}
impl Request {
pub fn new(login_info: LoginInfo) -> Self {
Self {
login_info,
device_id: None,
initial_device_display_name: None,
refresh_token: false,
}
}
}
impl Response {
#[allow(deprecated)]
pub fn new(user_id: OwnedUserId, access_token: String, device_id: OwnedDeviceId) -> Self {
Self {
user_id,
access_token,
home_server: None,
device_id,
well_known: None,
refresh_token: None,
expires_in: None,
}
}
}
#[derive(Clone, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
#[serde(untagged)]
pub enum LoginInfo {
Password(Password),
Token(Token),
ApplicationService(ApplicationService),
#[doc(hidden)]
_Custom(CustomLoginInfo),
}
impl LoginInfo {
pub fn new(login_type: &str, data: JsonObject) -> serde_json::Result<Self> {
Ok(match login_type {
"m.login.password" => {
Self::Password(serde_json::from_value(JsonValue::Object(data))?)
}
"m.login.token" => Self::Token(serde_json::from_value(JsonValue::Object(data))?),
"m.login.application_service" => {
Self::ApplicationService(serde_json::from_value(JsonValue::Object(data))?)
}
_ => Self::_Custom(CustomLoginInfo { login_type: login_type.into(), data }),
})
}
pub fn login_type(&self) -> &str {
match self {
LoginInfo::Password(_) => "m.login.password",
LoginInfo::Token(_) => "m.login.token",
LoginInfo::ApplicationService(_) => "m.login.application_service",
LoginInfo::_Custom(c) => &c.login_type,
}
}
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(obj: &T) -> JsonObject {
match serde_json::to_value(obj).expect("login info serialization to succeed") {
JsonValue::Object(obj) => obj,
_ => panic!("all login info variants must serialize to objects"),
}
}
match self {
Self::Password(d) => Cow::Owned(serialize(d)),
Self::Token(d) => Cow::Owned(serialize(d)),
Self::ApplicationService(d) => Cow::Owned(serialize(d)),
Self::_Custom(c) => Cow::Borrowed(&c.data),
}
}
}
impl fmt::Debug for LoginInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Password(inner) => inner.fmt(f),
Self::Token(inner) => inner.fmt(f),
Self::ApplicationService(inner) => inner.fmt(f),
Self::_Custom(inner) => inner.fmt(f),
}
}
}
impl<'de> Deserialize<'de> for LoginInfo {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
fn from_json_value<T: DeserializeOwned, E: de::Error>(val: JsonValue) -> Result<T, E> {
serde_json::from_value(val).map_err(E::custom)
}
let mut data = JsonObject::deserialize(deserializer)?;
let login_type =
data["type"].as_str().ok_or_else(|| de::Error::missing_field("type"))?;
match login_type {
"m.login.password" => from_json_value(data.into()).map(Self::Password),
"m.login.token" => from_json_value(data.into()).map(Self::Token),
"m.login.application_service" => {
from_json_value(data.into()).map(Self::ApplicationService)
}
_ => {
let login_type = as_variant!(
data.remove("type")
.expect("we already checked that the object has a type field"),
JsonValue::String
)
.expect("we already checked that the type field is a string");
Ok(Self::_Custom(CustomLoginInfo { login_type, data }))
}
}
}
}
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
#[serde(tag = "type", rename = "m.login.password")]
pub struct Password {
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier: Option<UserIdentifier>,
pub password: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[deprecated = "\
Since Matrix Client-Server API r0.4.0, clients should use `identifier`\
instead.\
"]
pub user: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[deprecated = "\
Since Matrix Client-Server API r0.4.0, clients should use `identifier`\
instead.\
"]
pub address: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[deprecated = "\
Since Matrix Client-Server API r0.4.0, clients should use `identifier`\
instead.\
"]
pub medium: Option<String>,
}
impl Password {
#[allow(deprecated)]
pub fn new(identifier: UserIdentifier, password: String) -> Self {
Self { identifier: Some(identifier), password, user: None, address: None, medium: None }
}
}
impl fmt::Debug for Password {
#[allow(deprecated)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { identifier, password: _, user, address, medium } = self;
f.debug_struct("Password")
.field("identifier", identifier)
.field("user", user)
.field("address", address)
.field("medium", medium)
.finish_non_exhaustive()
}
}
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
#[serde(tag = "type", rename = "m.login.token")]
pub struct Token {
pub token: String,
}
impl Token {
pub fn new(token: String) -> Self {
Self { token }
}
}
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { token: _ } = self;
f.debug_struct("Token").finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
#[serde(tag = "type", rename = "m.login.application_service")]
pub struct ApplicationService {
pub identifier: Option<UserIdentifier>,
#[serde(skip_serializing_if = "Option::is_none")]
#[deprecated = "\
Since Matrix Client-Server API r0.4.0, clients should use `identifier`\
instead.\
"]
pub user: Option<String>,
}
impl ApplicationService {
#[allow(deprecated)]
pub fn new(identifier: UserIdentifier) -> Self {
Self { identifier: Some(identifier), user: None }
}
}
#[doc(hidden)]
#[derive(Clone, Serialize)]
#[non_exhaustive]
pub struct CustomLoginInfo {
#[serde(rename = "type")]
login_type: String,
#[serde(flatten)]
data: JsonObject,
}
impl fmt::Debug for CustomLoginInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { login_type, data: _ } = self;
f.debug_struct("CustomLoginInfo")
.field("login_type", login_type)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
pub struct DiscoveryInfo {
#[serde(rename = "m.homeserver")]
pub homeserver: HomeserverInfo,
#[serde(rename = "m.identity_server", skip_serializing_if = "Option::is_none")]
pub identity_server: Option<IdentityServerInfo>,
}
impl DiscoveryInfo {
pub fn new(homeserver: HomeserverInfo) -> Self {
Self { homeserver, identity_server: None }
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
pub struct HomeserverInfo {
pub base_url: String,
}
impl HomeserverInfo {
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
pub struct IdentityServerInfo {
pub base_url: String,
}
impl IdentityServerInfo {
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
#[cfg(test)]
mod tests {
use ruma_common::canonical_json::assert_to_canonical_json_eq;
use serde_json::{from_value as from_json_value, json};
use strass::assert_let;
use super::{LoginInfo, Token};
use crate::uiaa::UserIdentifier;
#[test]
fn deserialize_login_type() {
assert_let!(
LoginInfo::Password(login) = from_json_value(json!({
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
"user": "cheeky_monkey"
},
"password": "ilovebananas"
}))
.unwrap()
);
assert_let!(Some(UserIdentifier::Matrix(id)) = login.identifier);
assert_eq!(id.user, "cheeky_monkey");
assert_eq!(login.password, "ilovebananas");
assert_let!(
LoginInfo::Token(Token { token }) = from_json_value(json!({
"type": "m.login.token",
"token": "1234567890abcdef"
}))
.unwrap()
);
assert_eq!(token, "1234567890abcdef");
}
#[test]
fn login_info_serialize_roundtrip() {
let json = json!({
"type": "local.dev.custom",
"identifier": "dGhpcy5pcy5tZQ",
});
let login_info = from_json_value::<LoginInfo>(json.clone()).unwrap();
assert_eq!(login_info.login_type(), "local.dev.custom");
let data = login_info.data();
assert_eq!(data.len(), 1);
assert_eq!(data.get("identifier").unwrap().as_str(), Some("dGhpcy5pcy5tZQ"));
assert_to_canonical_json_eq!(login_info, json);
}
#[test]
#[cfg(feature = "client")]
fn serialize_login_request_body() {
use std::borrow::Cow;
use ruma_common::api::{
MatrixVersion, OutgoingRequestExt as _, SupportedVersions,
auth_scheme::SendAccessToken,
};
use serde_json::Value as JsonValue;
use super::{LoginInfo, Password, Request, Token};
use crate::uiaa::{EmailUserIdentifier, UserIdentifier};
let supported = SupportedVersions {
versions: [MatrixVersion::V1_1].into(),
features: Default::default(),
};
let req: http::Request<Vec<u8>> = Request {
login_info: LoginInfo::Token(Token { token: "0xdeadbeef".to_owned() }),
device_id: None,
initial_device_display_name: Some("test".to_owned()),
refresh_token: false,
}
.try_into_http_request(
"https://homeserver.tld",
SendAccessToken::None,
Cow::Borrowed(&supported),
)
.unwrap();
let req_body_value: JsonValue = serde_json::from_slice(req.body()).unwrap();
assert_eq!(
req_body_value,
json!({
"type": "m.login.token",
"token": "0xdeadbeef",
"initial_device_display_name": "test",
})
);
let req: http::Request<Vec<u8>> = Request {
#[allow(deprecated)]
login_info: LoginInfo::Password(Password {
identifier: Some(UserIdentifier::Email(EmailUserIdentifier::new(
"hello@example.com".to_owned(),
))),
password: "deadbeef".to_owned(),
user: None,
address: None,
medium: None,
}),
device_id: None,
initial_device_display_name: Some("test".to_owned()),
refresh_token: false,
}
.try_into_http_request(
"https://homeserver.tld",
SendAccessToken::None,
Cow::Borrowed(&supported),
)
.unwrap();
let req_body_value: JsonValue = serde_json::from_slice(req.body()).unwrap();
assert_eq!(
req_body_value,
json!({
"identifier": {
"type": "m.id.thirdparty",
"medium": "email",
"address": "hello@example.com"
},
"type": "m.login.password",
"password": "deadbeef",
"initial_device_display_name": "test",
})
);
}
}
}