| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::time::SystemTime; |
| 8 | |
| 9 | use sqlx::SqlitePool; |
| 10 | use topcoat::{ |
| 11 | Result, |
| 12 | context::{Cx, app_context}, |
| 13 | router::error::internal_server_error, |
| 14 | session, |
| 15 | }; |
| 16 | |
| 17 | use crate::{ |
| 18 | application::{Identity, describe_identity, is_claimed, resolve_actor}, |
| 19 | domain::{Actor, SessionTokenHash}, |
| 20 | infrastructure::repository::{ |
| 21 | SqliteMembershipRepo, SqliteOrgRepo, SqliteSessionRepo, SqliteUserRepo, |
| 22 | }, |
| 23 | }; |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | pub struct SetupState(pub crate::domain::SetupToken); |
| 29 | |
| 30 | pub fn pool(cx: &Cx) -> &SqlitePool { |
| 31 | app_context::<SqlitePool>(cx) |
| 32 | } |
| 33 | |
| 34 | |
| 35 | |
| 36 | pub fn server_error<E>(error: E) -> topcoat::Error |
| 37 | where |
| 38 | E: std::error::Error + Send + Sync + 'static, |
| 39 | { |
| 40 | eprintln!("steid: {error}"); |
| 41 | internal_server_error(error).into() |
| 42 | } |
| 43 | |
| 44 | pub fn orgs(cx: &Cx) -> SqliteOrgRepo { |
| 45 | SqliteOrgRepo::new(pool(cx).clone()) |
| 46 | } |
| 47 | |
| 48 | pub fn memberships(cx: &Cx) -> SqliteMembershipRepo { |
| 49 | SqliteMembershipRepo::new(pool(cx).clone()) |
| 50 | } |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | pub async fn current_actor(cx: &Cx) -> Result<Actor> { |
| 57 | let presented = session::token_hash(cx) |
| 58 | .await? |
| 59 | .map(|hash| SessionTokenHash::from_trusted(hex(&hash))); |
| 60 | |
| 61 | let sessions = SqliteSessionRepo::new(pool(cx).clone()); |
| 62 | |
| 63 | resolve_actor(presented.as_ref(), SystemTime::now(), &sessions) |
| 64 | .await |
| 65 | .map_err(server_error) |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | pub async fn identity(cx: &Cx) -> Result<Option<Identity>> { |
| 72 | let actor = current_actor(cx).await?; |
| 73 | let pool = pool(cx).clone(); |
| 74 | |
| 75 | describe_identity( |
| 76 | &actor, |
| 77 | &SqliteUserRepo::new(pool.clone()), |
| 78 | &SqliteOrgRepo::new(pool), |
| 79 | ) |
| 80 | .await |
| 81 | .map_err(server_error) |
| 82 | } |
| 83 | |
| 84 | |
| 85 | pub async fn claimed(cx: &Cx) -> Result<bool> { |
| 86 | let users = SqliteUserRepo::new(pool(cx).clone()); |
| 87 | |
| 88 | is_claimed(&users).await.map_err(server_error) |
| 89 | } |
| 90 | |
| 91 | |
| 92 | pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> { |
| 93 | topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0) |
| 94 | } |
| 95 | |
| 96 | |
| 97 | pub fn hex(hash: &session::TokenHash) -> String { |
| 98 | hash.iter().map(|byte| format!("{byte:02x}")).collect() |
| 99 | } |