[fractal] Backend: Implement and use register request and response types



commit ede3e4b454e8023f1635df0c30d296408f07d16f
Author: Alejandro Domínguez <adomu net-c com>
Date:   Sun Jan 20 16:31:18 2019 +0100

    Backend: Implement and use register request and response types

 fractal-matrix-api/src/backend/mod.rs      |  2 +-
 fractal-matrix-api/src/backend/register.rs | 60 +++++++++++++++++++-----------
 fractal-matrix-api/src/model/register.rs   | 50 +++++++++++++++++++++++++
 3 files changed, 90 insertions(+), 22 deletions(-)
---
diff --git a/fractal-matrix-api/src/backend/mod.rs b/fractal-matrix-api/src/backend/mod.rs
index 5dfdb781..8dfca561 100644
--- a/fractal-matrix-api/src/backend/mod.rs
+++ b/fractal-matrix-api/src/backend/mod.rs
@@ -95,7 +95,7 @@ impl Backend {
                 bkerror!(r, tx, BKResponse::LogoutError);
             }
             Ok(BKCommand::Register(user, passwd, server)) => {
-                let r = register::register(self, &user, &passwd, &server);
+                let r = register::register(self, user, passwd, &server);
                 bkerror!(r, tx, BKResponse::LoginError);
             }
             Ok(BKCommand::Guest(server)) => {
diff --git a/fractal-matrix-api/src/backend/register.rs b/fractal-matrix-api/src/backend/register.rs
index 8623427f..1bb3b79a 100644
--- a/fractal-matrix-api/src/backend/register.rs
+++ b/fractal-matrix-api/src/backend/register.rs
@@ -8,8 +8,12 @@ use crate::error::Error;
 use crate::globals;
 use crate::util::json_q;
 
+use crate::types::AuthenticationData;
+use crate::types::AuthenticationKind;
 use crate::types::LoginRequest;
 use crate::types::LoginResponse;
+use crate::types::RegisterRequest;
+use crate::types::RegisterResponse;
 
 use crate::backend::types::BKResponse;
 use crate::backend::types::Backend;
@@ -23,19 +27,25 @@ pub fn guest(bk: &Backend, server: &str) -> Result<(), Error> {
 
     let data = bk.data.clone();
     let tx = bk.tx.clone();
-    let attrs = json!({});
+    let attrs = RegisterRequest::default();
+    let attrs_json =
+        serde_json::to_value(attrs).expect("Failed to serialize guest register request");
     post!(
         &url,
-        &attrs,
-        |r: JsonValue| {
-            let uid = String::from(r["user_id"].as_str().unwrap_or_default());
-            let tk = String::from(r["access_token"].as_str().unwrap_or_default());
-            let dev = String::from(r["device_id"].as_str().unwrap_or_default());
+        &attrs_json,
+        |r: JsonValue| if let Ok(response) = serde_json::from_value::<RegisterResponse>(r) {
+            let uid = response.user_id;
+            let tk = response.access_token.unwrap_or_default();
+            let dev = response.device_id;
+
             data.lock().unwrap().user_id = uid.clone();
             data.lock().unwrap().access_token = tk.clone();
             data.lock().unwrap().since = None;
-            tx.send(BKResponse::Token(uid, tk, Some(dev))).unwrap();
+            tx.send(BKResponse::Token(uid, tk, dev)).unwrap();
             tx.send(BKResponse::Rooms(vec![], None)).unwrap();
+        } else {
+            tx.send(BKResponse::GuestLoginError(Error::BackendError))
+                .unwrap();
         },
         |err| tx.send(BKResponse::GuestLoginError(err)).unwrap()
     );
@@ -109,31 +119,39 @@ pub fn logout(bk: &Backend) -> Result<(), Error> {
     Ok(())
 }
 
-pub fn register(bk: &Backend, user: &str, password: &str, server: &str) -> Result<(), Error> {
+pub fn register(bk: &Backend, user: String, password: String, server: &str) -> Result<(), Error> {
     bk.data.lock().unwrap().server_url = Url::parse(server)?;
     let url = bk.url("register", vec![("kind", String::from("user"))])?;
 
-    let attrs = json!({
-        "auth": {"type": "m.login.password"},
-        "username": user,
-        "bind_email": false,
-        "password": password
-    });
-
+    let attrs = RegisterRequest {
+        auth: Some(AuthenticationData {
+            kind: AuthenticationKind::Password,
+            session: None,
+        }),
+        username: Some(user),
+        password: Some(password),
+        ..Default::default()
+    };
+
+    let attrs_json =
+        serde_json::to_value(attrs).expect("Failed to serialize user register request");
     let data = bk.data.clone();
     let tx = bk.tx.clone();
     post!(
         &url,
-        &attrs,
-        |r: JsonValue| {
-            let uid = String::from(r["user_id"].as_str().unwrap_or_default());
-            let tk = String::from(r["access_token"].as_str().unwrap_or_default());
-            let dev = String::from(r["device_id"].as_str().unwrap_or_default());
+        &attrs_json,
+        |r: JsonValue| if let Ok(response) = serde_json::from_value::<RegisterResponse>(r) {
+            let uid = response.user_id;
+            let tk = response.access_token.unwrap_or_default();
+            let dev = response.device_id;
 
             data.lock().unwrap().user_id = uid.clone();
             data.lock().unwrap().access_token = tk.clone();
             data.lock().unwrap().since = None;
-            tx.send(BKResponse::Token(uid, tk, Some(dev))).unwrap();
+            tx.send(BKResponse::Token(uid, tk, dev)).unwrap();
+        } else {
+            tx.send(BKResponse::LoginError(Error::BackendError))
+                .unwrap();
         },
         |err| tx.send(BKResponse::LoginError(err)).unwrap()
     );
diff --git a/fractal-matrix-api/src/model/register.rs b/fractal-matrix-api/src/model/register.rs
index 34a90d5b..4e6230be 100644
--- a/fractal-matrix-api/src/model/register.rs
+++ b/fractal-matrix-api/src/model/register.rs
@@ -1,5 +1,6 @@
 use crate::globals;
 use serde::{Deserialize, Serialize};
+use std::ops::Not;
 
 #[derive(Clone, Debug, Serialize)]
 pub struct LoginRequest {
@@ -113,3 +114,52 @@ impl LoginRequest {
         }
     }
 }
+
+#[derive(Clone, Debug, Default, Serialize)]
+pub struct RegisterRequest {
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub auth: Option<AuthenticationData>,
+    #[serde(skip_serializing_if = "Not::not")]
+    pub bind_email: bool,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub password: Option<String>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub username: Option<String>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub device_id: Option<String>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub initial_device_display_name: Option<String>,
+    #[serde(skip_serializing_if = "Not::not")]
+    pub inhibit_login: bool,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+pub struct RegisterResponse {
+    pub user_id: String,
+    pub access_token: Option<String>,
+    pub device_id: Option<String>,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub struct AuthenticationData {
+    #[serde(rename = "type")]
+    pub kind: AuthenticationKind,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub session: Option<String>,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub enum AuthenticationKind {
+    #[serde(rename = "m.login.password")]
+    Password,
+    #[serde(rename = "m.login.recaptcha")]
+    Recaptcha,
+    #[serde(rename = "m.login.oauth2")]
+    OAuth2,
+    #[serde(rename = "m.login.email.identity")]
+    Email,
+    #[serde(rename = "m.login.token")]
+    Token,
+    #[serde(rename = "m.login.dummy")]
+    Dummy,
+}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]