| 1 | use steid::{ |
| 2 | application::{AppConfig, is_claimed}, |
| 3 | domain::SetupToken, |
| 4 | infrastructure::{ |
| 5 | self, |
| 6 | repository::SqliteUserRepo, |
| 7 | web::{context::SetupState, session_cookie::InsecureCookieTokenStore}, |
| 8 | }, |
| 9 | }; |
| 10 | use topcoat::{ |
| 11 | cookie::RouterBuilderCookieExt, |
| 12 | router::{Router, RouterBuilderDiscoverExt}, |
| 13 | session::{RouterBuilderSessionExt, SessionConfig}, |
| 14 | }; |
| 15 | |
| 16 | #[tokio::main] |
| 17 | async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 18 | dotenvy::dotenv().ok(); |
| 19 | |
| 20 | let config = AppConfig::from_env()?; |
| 21 | let pool = infrastructure::database::connect(&config.database_url).await?; |
| 22 | |
| 23 | let mut builder = Router::builder() |
| 24 | .cookies() |
| 25 | .sessions(session_config(config.insecure_cookies)) |
| 26 | .discover() |
| 27 | .app_context(config) |
| 28 | .app_context(pool.clone()); |
| 29 | |
| 30 | |
| 31 | |
| 32 | if !is_claimed(&SqliteUserRepo::new(pool)).await? { |
| 33 | let token = SetupToken::generate(); |
| 34 | announce_setup(&token); |
| 35 | builder = builder.app_context(SetupState(token)); |
| 36 | } |
| 37 | |
| 38 | topcoat::start(builder.build()).await?; |
| 39 | |
| 40 | Ok(()) |
| 41 | } |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | fn session_config(insecure_cookies: bool) -> SessionConfig { |
| 49 | if insecure_cookies { |
| 50 | eprintln!(); |
| 51 | eprintln!(" !! STEID_INSECURE_COOKIES is on: the session cookie has no Secure"); |
| 52 | eprintln!(" !! flag and travels unencrypted. Local development only."); |
| 53 | eprintln!(); |
| 54 | |
| 55 | SessionConfig::builder() |
| 56 | .token_store(InsecureCookieTokenStore::new()) |
| 57 | .build() |
| 58 | } else { |
| 59 | SessionConfig::default() |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | |
| 64 | fn announce_setup(token: &SetupToken) { |
| 65 | println!(); |
| 66 | println!(" This steid has no owner yet. Claim it at /setup with:"); |
| 67 | println!(); |
| 68 | println!(" {}", token.reveal()); |
| 69 | println!(); |
| 70 | println!(" The token is held in memory only — restarting issues a new one."); |
| 71 | println!(); |
| 72 | } |