Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ddboline committed Nov 24, 2024
1 parent 2d203c2 commit 6cc8d16
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 37 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sync_app_rust"
version = "0.11.21"
version = "0.12.0"
authors = ["Daniel Boline <[email protected]>"]
edition = "2018"

Expand All @@ -21,9 +21,9 @@ env_logger = "0.11"
futures = "0.3"
gdrive_lib = {path="gdrive_lib"}
log = "0.4"
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types"], tag="0.9.3" }
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types"], tag="1.0.2" }
time = {version="0.3", features=["serde-human-readable", "macros", "formatting"]}
tokio = {version="1.40", features=["rt", "macros", "rt-multi-thread"]}
tokio = {version="1.41", features=["rt", "macros", "rt-multi-thread"]}
walkdir = "2.3"

[workspace]
Expand Down
1 change: 0 additions & 1 deletion Dockerfile.build.ubuntu16.04
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
FROM rust_stable:xenial_latest
MAINTAINER Daniel Boline

WORKDIR /sync_app_rust

Expand Down
6 changes: 3 additions & 3 deletions gdrive_lib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "gdrive_lib"
version = "0.11.21"
version = "0.12.0"
authors = ["Daniel Boline <[email protected]>"]
edition = "2018"

Expand All @@ -27,8 +27,8 @@ rand = "0.8"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types"], tag="0.9.3" }
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types"], tag="1.0.2" }
stdout-channel = "0.6"
time = {version="0.3", features=["serde-human-readable", "macros", "formatting"]}
url = "2.3"
tokio = {version="1.35", features=["rt", "macros", "rt-multi-thread"]}
tokio = {version="1.41", features=["rt", "macros", "rt-multi-thread"]}
2 changes: 2 additions & 0 deletions migrations/V11__authorized_users_created_deleted.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE authorized_users ADD COLUMN created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now();
ALTER TABLE authorized_users ADD COLUMN deleted_at TIMESTAMP WITH TIME ZONE;
10 changes: 5 additions & 5 deletions sync_app_http/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sync_app_http"
version = "0.11.21"
version = "0.12.0"
authors = ["Daniel Boline <[email protected]>"]
edition = "2018"

Expand All @@ -9,7 +9,7 @@ edition = "2018"
[dependencies]
anyhow = "1.0"
async-trait = "0.1"
authorized_users = { git = "https://github.com/ddboline/auth_server_rust.git", tag="0.11.15"}
authorized_users = { git = "https://github.com/ddboline/auth_server_rust.git", tag="0.12.0"}
deadqueue = "0.2"
dioxus = "0.5"
dioxus-core = "0.5"
Expand All @@ -28,11 +28,11 @@ serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
serde_yaml = "0.9"
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types", "rweb-openapi"], tag="0.9.3" }
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types", "rweb-openapi"], tag="1.0.2" }
stdout-channel = "0.6"
sync_app_lib = {path = "../sync_app_lib"}
thiserror = "1.0"
thiserror = "2.0"
time = {version="0.3", features=["serde-human-readable", "macros", "formatting"]}
tokio = {version="1.40", features=["time"]}
tokio = {version="1.41", features=["time"]}
url = "2.3"
uuid = "1.0"
67 changes: 47 additions & 20 deletions sync_app_http/src/logged_user.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
pub use authorized_users::{
get_random_key, get_secrets, token::Token, AuthorizedUser, AUTHORIZED_USERS, JWT_SECRET,
KEY_LENGTH, LOGIN_HTML, SECRET_KEY, TRIGGER_DB_UPDATE,
get_random_key, get_secrets, token::Token, AuthorizedUser as ExternalUser, AUTHORIZED_USERS,
JWT_SECRET, KEY_LENGTH, LOGIN_HTML, SECRET_KEY, TRIGGER_DB_UPDATE,
};
use futures::TryStreamExt;
use log::debug;
use maplit::hashset;
use maplit::hashmap;
use reqwest::Client;
use rweb::{filters::cookie::cookie, Filter, Rejection, Schema};
use rweb_helper::UuidWrapper;
use serde::{Deserialize, Serialize};
use stack_string::{format_sstr, StackString};
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
env::var,
str::FromStr,
Expand Down Expand Up @@ -69,7 +70,7 @@ impl LoggedUser {
session_key: &str,
) -> Result<Option<SyncSession>, anyhow::Error> {
let base_url: Url = format_sstr!("https://{}", config.domain).parse()?;
let session: Option<SyncSession> = AuthorizedUser::get_session_data(
let session: Option<SyncSession> = ExternalUser::get_session_data(
&base_url,
self.session.into(),
&self.secret_key,
Expand All @@ -94,7 +95,7 @@ impl LoggedUser {
session_value: SyncSession,
) -> Result<(), anyhow::Error> {
let base_url: Url = format_sstr!("https://{}", config.domain).parse()?;
AuthorizedUser::set_session_data(
ExternalUser::set_session_data(
&base_url,
self.session.into(),
&self.secret_key,
Expand All @@ -115,7 +116,7 @@ impl LoggedUser {
session_key: &str,
) -> Result<(), anyhow::Error> {
let base_url: Url = format_sstr!("https://{}", config.domain).parse()?;
AuthorizedUser::rm_session_data(
ExternalUser::rm_session_data(
&base_url,
self.session.into(),
&self.secret_key,
Expand Down Expand Up @@ -166,8 +167,8 @@ impl LoggedUser {
}
}

impl From<AuthorizedUser> for LoggedUser {
fn from(user: AuthorizedUser) -> Self {
impl From<ExternalUser> for LoggedUser {
fn from(user: ExternalUser) -> Self {
Self {
email: user.email,
session: user.session.into(),
Expand Down Expand Up @@ -202,21 +203,47 @@ impl FromStr for LoggedUser {
/// # Errors
/// Return error if db query fails
pub async fn fill_from_db(pool: &PgPool) -> Result<(), Error> {
debug!("{:?}", *TRIGGER_DB_UPDATE);
let users = if TRIGGER_DB_UPDATE.check() {
AuthorizedUsers::get_authorized_users(pool)
.await?
.map_ok(|user| user.email)
.try_collect()
.await?
} else {
AUTHORIZED_USERS.get_users()
};
if let Ok("true") = var("TESTENV").as_ref().map(String::as_str) {
AUTHORIZED_USERS.update_users(hashset! {"user@test".into()});
AUTHORIZED_USERS.update_users(hashmap! {
"user@test".into() => ExternalUser {
email: "user@test".into(),
session: Uuid::new_v4(),
secret_key: StackString::default(),
created_at: Some(OffsetDateTime::now_utc())
}
});
return Ok(());
}
let (created_at, deleted_at) = AuthorizedUsers::get_most_recent(pool).await?;
let most_recent_user_db = created_at.max(deleted_at);
let existing_users = AUTHORIZED_USERS.get_users();
let most_recent_user = existing_users.values().map(|i| i.created_at).max();
debug!("most_recent_user_db {most_recent_user_db:?} most_recent_user {most_recent_user:?}");
if most_recent_user_db.is_some()
&& most_recent_user.is_some()
&& most_recent_user_db <= most_recent_user
{
return Ok(());
}

let result: Result<HashMap<StackString, _>, _> = AuthorizedUsers::get_authorized_users(pool)
.await?
.map_ok(|u| {
(
u.email.clone(),
ExternalUser {
email: u.email,
session: Uuid::new_v4(),
secret_key: StackString::default(),
created_at: Some(u.created_at),
},
)
})
.try_collect()
.await;
let users = result?;
AUTHORIZED_USERS.update_users(users);
debug!("{:?}", *AUTHORIZED_USERS);
debug!("AUTHORIZED_USERS {:?}", *AUTHORIZED_USERS);
Ok(())
}

Expand Down
8 changes: 4 additions & 4 deletions sync_app_lib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sync_app_lib"
version = "0.11.21"
version = "0.12.0"
authors = ["Daniel Boline <[email protected]>"]
edition = "2018"

Expand Down Expand Up @@ -41,11 +41,11 @@ rust_decimal = "1.26"
serde = {version="1.0", features=["derive"]}
serde_json = "1.0"
smallvec = "1.6"
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types"], tag="0.9.3" }
stack-string = { git = "https://github.com/ddboline/stack-string-rs.git", features=["postgres_types"], tag="1.0.2" }
stdout-channel = "0.6"
thiserror = "1.0"
thiserror = "2.0"
time = {version="0.3", features=["serde-human-readable", "macros", "formatting"]}
tokio = {version="1.40", features=["rt", "macros", "rt-multi-thread"]}
tokio = {version="1.41", features=["rt", "macros", "rt-multi-thread"]}
tokio-postgres = {version = "0.7", features = ["with-time-0_3", "with-uuid-1", "with-serde_json-1"]}
url = "2.3"
uuid = "1.1"
Expand Down
26 changes: 25 additions & 1 deletion sync_app_lib/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use log::info;
use postgres_query::{query, Error as PqError, FromSqlRow};
use smallvec::{smallvec, SmallVec};
use stack_string::StackString;
use time::OffsetDateTime;
use url::Url;
use uuid::Uuid;

Expand Down Expand Up @@ -682,6 +683,7 @@ impl FileSyncConfig {
#[derive(FromSqlRow, Clone, Debug)]
pub struct AuthorizedUsers {
pub email: StackString,
pub created_at: OffsetDateTime,
}

impl AuthorizedUsers {
Expand All @@ -690,8 +692,30 @@ impl AuthorizedUsers {
pub async fn get_authorized_users(
pool: &PgPool,
) -> Result<impl Stream<Item = Result<Self, PqError>>, Error> {
let query = query!("SELECT * FROM authorized_users");
let query = query!("SELECT * FROM authorized_users WHERE deleted_at IS NULL");
let conn = pool.get().await?;
query.fetch_streaming(&conn).await.map_err(Into::into)
}

/// # Errors
/// Returns error if db query fails
pub async fn get_most_recent(
pool: &PgPool,
) -> Result<(Option<OffsetDateTime>, Option<OffsetDateTime>), Error> {
#[derive(FromSqlRow)]
struct CreatedDeleted {
created_at: Option<OffsetDateTime>,
deleted_at: Option<OffsetDateTime>,
}

let query = query!(
"SELECT max(created_at) as created_at, max(deleted_at) as deleted_at FROM users"
);
let conn = pool.get().await?;
let result: Option<CreatedDeleted> = query.fetch_opt(&conn).await?;
match result {
Some(result) => Ok((result.created_at, result.deleted_at)),
None => Ok((None, None)),
}
}
}

0 comments on commit 6cc8d16

Please sign in to comment.