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,9 +1,10 @@
use crate::usimp;
use crate::usimp::*;
use crate::database;
use serde_json::{Value, from_value, to_value};
use serde::{Serialize, Deserialize};
use std::ops::Deref;
use rand::Rng;
#[derive(Serialize, Deserialize, Clone)]
struct Input {
@ -13,22 +14,56 @@ struct Input {
#[derive(Serialize, Deserialize, Clone)]
struct Output {
session: String,
session_id: String,
token: String,
}
pub async fn handle(input: &InputEnvelope, session: &Session) -> Result<Value, Error> {
Ok(to_value(authenticate(from_value(input.data.clone())?).await?)?)
pub async fn handle(input: &InputEnvelope, session: Option<Session>) -> Result<Value, Error> {
Ok(to_value(authenticate(from_value(input.data.clone())?, session).await?)?)
}
async fn authenticate(input: Input) -> Result<Output, Error> {
match database::client().await? {
async fn authenticate(input: Input, _session: Option<Session>) -> Result<Output, Error> {
let backend = database::client().await?;
let token;
let session_id;
match backend {
database::Client::Postgres(client) => {
client.execute("SELECT * FROM asdf;", &[]).await?;
let res = client.query(
"SELECT account_id, domain_id \
FROM accounts \
WHERE account_name = $1",
&[&input.name]
).await?;
if res.len() == 0 {
return Err(Error::new(ErrorKind::AuthenticationError, ErrorClass::ClientError, None));
}
let row = &res[0];
let account_id: String = row.get(0);
let domain_id: String = row.get(1);
// TODO password check
if !input.password.eq("MichaelScott") {
return Err(Error::new(ErrorKind::AuthenticationError, ErrorClass::ClientError, None));
}
session_id = usimp::get_id(&[domain_id.as_str(), account_id.as_str()]);
token = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(256)
.map(char::from)
.collect();
client.execute(
"INSERT INTO sessions (account_id, session_nr, session_id, session_token) \
VALUES ($1, COALESCE((SELECT MAX(session_nr) + 1 \
FROM sessions \
WHERE account_id = $1), 1), $2, $3);",
&[&account_id, &session_id, &token],
).await?;
}
}
Ok(Output {
session: "".to_string(),
token: "".to_string(),
session_id,
token,
})
}