| 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::{is_claimed, resolve_actor}, |
| 19 | domain::{Actor, SessionTokenHash}, |
| 20 | infrastructure::repository::{SqliteSessionRepo, SqliteUserRepo}, |
| 21 | }; |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | pub struct SetupState(pub crate::domain::SetupToken); |
| 27 | |
| 28 | pub fn pool(cx: &Cx) -> &SqlitePool { |
| 29 | app_context::<SqlitePool>(cx) |
| 30 | } |
| 31 | |
| 32 | |
| 33 | |
| 34 | fn server_error<E>(error: E) -> topcoat::Error |
| 35 | where |
| 36 | E: std::error::Error + Send + Sync + 'static, |
| 37 | { |
| 38 | eprintln!("steid: {error}"); |
| 39 | internal_server_error(error).into() |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | pub async fn current_actor(cx: &Cx) -> Result<Actor> { |
| 47 | let presented = session::token_hash(cx) |
| 48 | .await? |
| 49 | .map(|hash| SessionTokenHash::from_trusted(hex(&hash))); |
| 50 | |
| 51 | let sessions = SqliteSessionRepo::new(pool(cx).clone()); |
| 52 | |
| 53 | resolve_actor(presented.as_ref(), SystemTime::now(), &sessions) |
| 54 | .await |
| 55 | .map_err(server_error) |
| 56 | } |
| 57 | |
| 58 | |
| 59 | pub async fn claimed(cx: &Cx) -> Result<bool> { |
| 60 | let users = SqliteUserRepo::new(pool(cx).clone()); |
| 61 | |
| 62 | is_claimed(&users).await.map_err(server_error) |
| 63 | } |
| 64 | |
| 65 | |
| 66 | pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> { |
| 67 | topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0) |
| 68 | } |
| 69 | |
| 70 | |
| 71 | pub fn hex(hash: &session::TokenHash) -> String { |
| 72 | hash.iter().map(|byte| format!("{byte:02x}")).collect() |
| 73 | } |