awc_firebase_auth/
lib.rs

1pub mod error;
2mod model;
3
4use awc::{Client, http::StatusCode};
5use crate::{error::{ErrorContainer, LoginError, RegisterError}, model::{LoginResponse, RegisterResponse, LoginBody}};
6
7#[derive(Clone)]
8pub struct Firebase {
9    base_url: String,
10    auth_token: String,
11    client: Client,
12}
13
14impl Firebase {
15
16    pub fn auth(base_url: String, auth_token: String) -> Firebase {
17        let client = Client::builder()
18            .add_default_header(("Content-Type", "application/json"))
19            .finish();
20        Firebase {
21            base_url,
22            auth_token,
23            client: client,
24        }        
25    }
26
27}
28
29impl Firebase {
30
31    pub async fn login(&self, email: String, password: String) -> Result<LoginResponse, LoginError> {
32        let url = self.sign_in_url();
33        let body = LoginBody::new(email, password);
34        let mut res = self.client.post(url)
35            .send_json(&body)
36            .await
37            .map_err(|_| LoginError::Unknown)?;
38
39
40        match res.status() {
41            StatusCode::OK => {
42                res.json::<LoginResponse>().await
43                    .and_then(|body| Ok(body))
44                    .map_err(|_| LoginError::Unknown)
45            },
46            _ => {
47                match res.json::<ErrorContainer>().await {
48                    Ok(error) => Err(error.error.login_error()),
49                    Err(_) => Err(LoginError::Unknown)
50                }
51            }
52        }
53    }
54
55}
56
57impl Firebase {
58
59    pub async fn register(&self, email: String, password: String) -> Result<RegisterResponse, RegisterError> {
60        let url = self.sign_up_url();
61        let body = LoginBody::new(email, password);
62        let mut res = self.client.post(url)
63            .send_json(&body)
64            .await
65            .map_err(|_| RegisterError::Unknown)?;
66
67
68        match res.status() {
69            StatusCode::OK => {
70                res.json::<RegisterResponse>().await
71                    .and_then(|body| Ok(body))
72                    .map_err(|_| RegisterError::Unknown)
73            },
74            _ => {
75                match res.json::<ErrorContainer>().await {
76                    Ok(error) => Err(error.error.register_error()),
77                    Err(_) => Err(RegisterError::Unknown)
78                }
79            }
80        }        
81    }
82
83}
84
85impl Firebase {
86
87    fn sign_in_url(&self) -> String {
88        format!("{}/accounts:signInWithPassword?key={}", self.base_url, self.auth_token)
89    }
90
91    fn sign_up_url(&self) -> String {
92        format!("{}/accounts:signUp?key={}", self.base_url, self.auth_token) 
93    }
94
95}