A very performant and light (2mb in memory) link shortener and tracker. Written in Rust and React and uses Postgres/SQLite.
1use rand::Rng;
2use sqlx::PgPool;
3use std::fs::File;
4use std::io::Write;
5use tracing::info;
6
7pub mod auth;
8pub mod error;
9pub mod handlers;
10pub mod models;
11
12#[derive(Clone)]
13pub struct AppState {
14 pub db: PgPool,
15 pub admin_token: Option<String>,
16}
17
18pub async fn check_and_generate_admin_token(pool: &sqlx::PgPool) -> anyhow::Result<Option<String>> {
19 // Check if any users exist
20 let user_count = sqlx::query!("SELECT COUNT(*) as count FROM users")
21 .fetch_one(pool)
22 .await?
23 .count
24 .unwrap_or(0);
25
26 if user_count == 0 {
27 // Generate a random token using simple characters
28 let token: String = (0..32)
29 .map(|_| {
30 let idx = rand::thread_rng().gen_range(0..62);
31 match idx {
32 0..=9 => (b'0' + idx as u8) as char,
33 10..=35 => (b'a' + (idx - 10) as u8) as char,
34 _ => (b'A' + (idx - 36) as u8) as char,
35 }
36 })
37 .collect();
38
39 // Save token to file
40 let mut file = File::create("admin-setup-token.txt")?;
41 writeln!(file, "{}", token)?;
42
43 info!("No users found - generated admin setup token");
44 info!("Token has been saved to admin-setup-token.txt");
45 info!("Use this token to create the admin user");
46 info!("Admin setup token: {}", token);
47
48 Ok(Some(token))
49 } else {
50 Ok(None)
51 }
52}