Merge branch 're-org'

This commit is contained in:
Joe Ardent 2023-05-12 12:39:24 -07:00
commit 744d439098
7 changed files with 916 additions and 106 deletions

796
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -15,4 +15,11 @@ tower = { version = "0.4", features = ["util", "timeout"] }
tower-http = { version = "0.4", features = ["add-extension", "trace"] } tower-http = { version = "0.4", features = ["add-extension", "trace"] }
uuid = { version = "1.3", features = ["serde", "v4"] } uuid = { version = "1.3", features = ["serde", "v4"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
sqlx = { version = "0.5.10", features = ["runtime-tokio-rustls", "any", "sqlite", "chrono", "time", "uuid"] } sqlx = { version = "0.5.10", features = ["runtime-tokio-rustls", "any", "sqlite", "chrono", "time", "uuid"] }
argon2 = "0.5"
rand_core = { version = "0.6", features = ["getrandom"] }
thiserror = "1.0.40"
justerror = "1.1.0"
password-hash = { version = "0.5.0", features = ["std", "getrandom"] }
async-sqlx-session = { version = "0.4.0", default-features = false, features = ["sqlite", "rustls"] }
axum-sessions = "0.5.0"

View file

@ -7,7 +7,8 @@
create table if not exists witches ( create table if not exists witches (
id blob not null primary key, id blob not null primary key,
last_seen int, last_seen int,
name text, username text not null unique,
displayname text,
email text, email text,
secret blob not null, -- encrypted password? need to figure auth out secret blob not null, -- encrypted password? need to figure auth out
created_at int not null default (unixepoch()), created_at int not null default (unixepoch()),

32
src/db.rs Normal file
View file

@ -0,0 +1,32 @@
use std::time::Duration;
use sqlx::{
sqlite::{SqliteConnectOptions, SqlitePoolOptions},
SqlitePool,
};
const MAX_CONNS: u32 = 100;
const TIMEOUT: u64 = 5;
pub async fn get_pool() -> SqlitePool {
let db_filename = {
std::env::var("DATABASE_FILE").unwrap_or_else(|_| {
let home =
std::env::var("HOME").expect("Could not determine $HOME for finding db file");
format!("{home}/.witch-watch.db")
})
};
let conn_opts = SqliteConnectOptions::new()
.foreign_keys(true)
.auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Incremental)
.filename(&db_filename);
// setup connection pool
SqlitePoolOptions::new()
.max_connections(MAX_CONNS)
.connect_timeout(Duration::from_secs(TIMEOUT))
.connect_with(conn_opts)
.await
.expect("can't connect to database")
}

55
src/handlers.rs Normal file
View file

@ -0,0 +1,55 @@
use axum::{
async_trait,
extract::{FromRef, FromRequestParts, State},
http::{request::Parts, StatusCode},
};
use sqlx::SqlitePool;
pub async fn using_connection_pool_extractor(
State(pool): State<SqlitePool>,
) -> Result<String, (StatusCode, String)> {
sqlx::query_scalar("select 'hello world from sqlite get'")
.fetch_one(&pool)
.await
.map_err(internal_error)
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
pub struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Sqlite>);
#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
SqlitePool: FromRef<S>,
S: Send + Sync,
{
type Rejection = (StatusCode, String);
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let pool = SqlitePool::from_ref(state);
let conn = pool.acquire().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
pub async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
let mut conn = conn;
sqlx::query_scalar("select 'hello world from sqlite post'")
.fetch_one(&mut conn)
.await
.map_err(internal_error)
}
/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}

35
src/lib.rs Normal file
View file

@ -0,0 +1,35 @@
#[macro_use]
extern crate justerror;
use argon2::{
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Argon2,
};
use uuid::Uuid;
pub mod db;
pub mod handlers;
fn create_user(username: &str, password: &[u8]) -> Result<Uuid, CreateUserError> {
// Argon2 with default params (Argon2id v19)
let argon2 = Argon2::default();
let salt = SaltString::generate(&mut OsRng);
let password_hash = argon2
.hash_password(password, &salt)
.unwrap() // safe to unwrap, we know the salt is valid
.to_string();
todo!()
}
#[Error(desc = "Could not create user.")]
#[non_exhaustive]
pub struct CreateUserError(#[from] CreateUserErrorKind);
#[Error]
#[non_exhaustive]
pub enum CreateUserErrorKind {
AlreadyExists,
Unknown,
}

View file

@ -1,48 +1,23 @@
use std::{net::SocketAddr, time::Duration}; use std::net::SocketAddr;
use axum::{ use axum::{routing::get, Router};
async_trait,
extract::{FromRef, FromRequestParts, State},
http::{request::Parts, StatusCode},
routing::get,
Router,
};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
// use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use witch_watch::{db, handlers};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
tracing_subscriber::registry() tracing_subscriber::registry()
.with( .with(
tracing_subscriber::EnvFilter::try_from_default_env() tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "ww_main=debug".into()), .unwrap_or_else(|_| "witch_watch=debug,axum::routing=info".into()),
) )
.with(tracing_subscriber::fmt::layer()) .with(tracing_subscriber::fmt::layer())
.init(); .init();
let db_filename = { let pool = db::get_pool().await;
std::env::var("DATABASE_FILE").unwrap_or_else(|_| {
let home =
std::env::var("HOME").expect("Could not determine $HOME for finding db file");
format!("{home}/.witch-watch.db")
})
};
let conn_opts = SqliteConnectOptions::new()
.foreign_keys(true)
.auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Incremental)
.filename(&db_filename);
// setup connection pool
let pool = SqlitePoolOptions::new()
.max_connections(5)
.connect_timeout(Duration::from_secs(3))
.connect_with(conn_opts)
.await
.expect("can't connect to database");
// build our application with some routes // build our application with some routes
use handlers::*;
let app = Router::new() let app = Router::new()
.route( .route(
"/", "/",
@ -50,62 +25,9 @@ async fn main() {
) )
.with_state(pool); .with_state(pool);
// run it with hyper tracing::debug!("binding to 0.0.0.0:3000");
//let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
//axum::serve(listener, app).await.unwrap();
tracing::info!("binding to 0.0.0.0:3000");
axum::Server::bind(&SocketAddr::from(([0, 0, 0, 0], 3000))) axum::Server::bind(&SocketAddr::from(([0, 0, 0, 0], 3000)))
.serve(app.into_make_service()) .serve(app.into_make_service())
.await .await
.unwrap(); .unwrap();
} }
// we can extract the connection pool with `State`
async fn using_connection_pool_extractor(
State(pool): State<SqlitePool>,
) -> Result<String, (StatusCode, String)> {
sqlx::query_scalar("select 'hello world from sqlite get'")
.fetch_one(&pool)
.await
.map_err(internal_error)
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Sqlite>);
#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
where
SqlitePool: FromRef<S>,
S: Send + Sync,
{
type Rejection = (StatusCode, String);
async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let pool = SqlitePool::from_ref(state);
let conn = pool.acquire().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
let mut conn = conn;
sqlx::query_scalar("select 'hello world from sqlite post'")
.fetch_one(&mut conn)
.await
.map_err(internal_error)
}
/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}