Subscriptions working

This commit is contained in:
2021-06-05 14:17:23 +02:00
parent a96cbdc059
commit 473b553662
12 changed files with 306 additions and 34 deletions

View File

@ -1,10 +1,15 @@
mod handler;
pub mod subscription;
pub use handler::endpoint;
use serde_json::Value;
use crate::error::{Error, ErrorClass, ErrorKind};
use crate::database;
use serde_json::Value;
use serde::{Serialize, Deserialize};
use crypto::sha2::Sha256;
use crypto::digest::Digest;
use base64_url;
#[derive(Serialize, Deserialize)]
pub struct InputEnvelope {
@ -22,14 +27,43 @@ pub struct OutputEnvelope {
pub data: Value,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Event {
data: Value,
}
pub struct Account {
id: String,
name: String,
domain: String,
}
pub struct Session {
id: String,
nr: i32,
account: Option<Account>,
}
pub struct Account {
pub fn get_id(input: &[&str]) -> String {
let mut hasher = Sha256::new();
hasher.input_str(chrono::Utc::now().timestamp_millis().to_string().as_str());
for part in input {
hasher.input_str(" ");
hasher.input_str(part);
}
let mut result = [0u8; 32];
hasher.result(&mut result);
base64_url::encode(&result)
}
pub fn get_account(session: &Option<Session>) -> Result<&Account, Error> {
match session {
Some(session) => match &session.account {
Some(account) => Ok(&account),
None => return Err(Error::new(ErrorKind::UsimpError, ErrorClass::ClientProtocolError, None))
},
None => return Err(Error::new(ErrorKind::UsimpError, ErrorClass::ClientProtocolError, None))
}
}
impl InputEnvelope {
@ -43,7 +77,32 @@ impl InputEnvelope {
}
impl Session {
pub async fn from_token(token: &str) -> Self {
todo!("session")
pub async fn from_token(token: &str) -> Result<Self, Error> {
let backend = database::client().await?;
let session;
match backend {
database::Client::Postgres(client) => {
let res = client.query(
"SELECT session_id, session_nr, a.account_id, account_name, domain_id \
FROM accounts a JOIN sessions s ON a.account_id = s.account_id \
WHERE session_token = $1;",
&[&token]
).await?;
if res.len() == 0 {
return Err(Error::new(ErrorKind::InvalidSessionError, ErrorClass::ClientError, None));
}
let row = &res[0];
session = Session {
id: row.get(0),
nr: row.get(1),
account: Some(Account {
id: row.get(2),
name: row.get(3),
domain: row.get(4),
}),
};
}
}
Ok(session)
}
}