Compare commits
31 Commits
598215e50e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
f2a1296454
|
|||
|
d52c4cbe9e
|
|||
|
1282c2b8b5
|
|||
|
f7f4fd2813
|
|||
|
46ce08e02f
|
|||
|
8a049edeeb
|
|||
|
0b7e25c792
|
|||
|
554ae23175
|
|||
|
87aa18b7cc
|
|||
|
86291f1eb5
|
|||
|
f8e2dad58a
|
|||
|
2b800c2df4
|
|||
|
9e3d534190
|
|||
|
d74479851f
|
|||
|
4ecbf6da15
|
|||
|
674b58e290
|
|||
|
ef9f88e72c
|
|||
|
97cf3f62ad
|
|||
|
3677b6adfa
|
|||
|
ca8c96306f
|
|||
|
f4f1e4b96f
|
|||
|
1bf5c0f2da
|
|||
|
773d8dffd1
|
|||
|
fb3afaf31c
|
|||
|
3fae599c6f
|
|||
|
a40fc81d0e
|
|||
|
cc468b5b14
|
|||
|
655afa77ac
|
|||
|
91c79d124a
|
|||
|
81d8a96d59
|
|||
|
f9c6f1afd1
|
11
.gitignore
vendored
11
.gitignore
vendored
@@ -7,3 +7,14 @@
|
|||||||
/result
|
/result
|
||||||
|
|
||||||
.env
|
.env
|
||||||
|
|
||||||
|
# Anything the config crate looks for
|
||||||
|
config.ini
|
||||||
|
config.json
|
||||||
|
config.json5
|
||||||
|
config.ron
|
||||||
|
config.toml
|
||||||
|
config.yaml
|
||||||
|
config.yml
|
||||||
|
|
||||||
|
/migrations/.diesel_lock
|
||||||
|
|||||||
636
Cargo.lock
generated
636
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
16
Cargo.toml
@@ -9,16 +9,21 @@ edition = "2024"
|
|||||||
build = "src/build.rs"
|
build = "src/build.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
axum-login = { version = "0.18.0", optional = true }
|
||||||
|
cfg-if = "1.0.4"
|
||||||
|
chrono = { version = "0.4.45", features = ["serde"] }
|
||||||
config = { version = "0.15.24", optional = true }
|
config = { version = "0.15.24", optional = true }
|
||||||
diesel = { version = "2.3.10", optional = true, features = [ "postgres" ] }
|
diesel = { version = "2.3.10", optional = true, features = ["chrono"] }
|
||||||
diesel_migrations = { version = "2.3.2", optional = true, features = [ "postgres" ] }
|
diesel-async = { version = "0.9.1", optional = true, features = ["postgres", "deadpool", "migrations"] }
|
||||||
|
diesel_migrations = { version = "2.3.2", optional = true }
|
||||||
dioxus = { version = "0.7.9", features = ["router", "fullstack"] }
|
dioxus = { version = "0.7.9", features = ["router", "fullstack"] }
|
||||||
dotenvy = { version = "0.15.7", optional = true }
|
dotenvy = { version = "0.15.7", optional = true }
|
||||||
|
fred = { version = "10.1.0", optional = true }
|
||||||
lucide-dioxus = { version = "3.11.0", features = ["notifications"] }
|
lucide-dioxus = { version = "3.11.0", features = ["notifications"] }
|
||||||
|
pbkdf2 = { version = "0.13.0", optional = true, features = ["getrandom", "phc"] }
|
||||||
rand = "0.10.1"
|
rand = "0.10.1"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
thiserror = "2.0.18"
|
thiserror = "2.0.18"
|
||||||
tokio = { version = "1.52.3", optional = true, features = ["rt-multi-thread"] }
|
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
@@ -26,11 +31,14 @@ default = ["web"]
|
|||||||
web = ["dioxus/web"]
|
web = ["dioxus/web"]
|
||||||
server = [
|
server = [
|
||||||
"dioxus/server",
|
"dioxus/server",
|
||||||
|
"dep:axum-login",
|
||||||
"dep:config",
|
"dep:config",
|
||||||
"dep:diesel",
|
"dep:diesel",
|
||||||
|
"dep:diesel-async",
|
||||||
"dep:diesel_migrations",
|
"dep:diesel_migrations",
|
||||||
"dep:dotenvy",
|
"dep:dotenvy",
|
||||||
"dep:tokio",
|
"dep:fred",
|
||||||
|
"dep:pbkdf2",
|
||||||
]
|
]
|
||||||
|
|
||||||
# Disabled until supported
|
# Disabled until supported
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
DROP INDEX users_username_idx;
|
||||||
|
DROP TABLE users;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id INTEGER PRIMARY KEY UNIQUE NOT NULL GENERATED ALWAYS AS IDENTITY,
|
||||||
|
username VARCHAR UNIQUE NOT NULL,
|
||||||
|
hashed_password VARCHAR NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX users_username_idx ON users(username);
|
||||||
@@ -3,9 +3,11 @@ pub mod app;
|
|||||||
pub mod components;
|
pub mod components;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod pages;
|
pub mod pages;
|
||||||
pub mod schema;
|
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
|
#[cfg(feature = "server")]
|
||||||
|
pub mod schema;
|
||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
pub mod server;
|
pub mod server;
|
||||||
|
|
||||||
@@ -26,9 +28,8 @@ fn main() {
|
|||||||
fn main() -> std::process::ExitCode {
|
fn main() -> std::process::ExitCode {
|
||||||
tracing_setup();
|
tracing_setup();
|
||||||
|
|
||||||
if let Err(e) = server::main() {
|
let Err(e) = server::main();
|
||||||
tracing::error!("Server main failed:\n{e}");
|
tracing::error!("Server main failed:\n{e}");
|
||||||
}
|
|
||||||
|
|
||||||
std::process::ExitCode::FAILURE
|
std::process::ExitCode::FAILURE
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
|
pub mod user;
|
||||||
|
|||||||
144
src/models/user.rs
Normal file
144
src/models/user.rs
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
//! Various user types. Some types marked server-only to help prevent
|
||||||
|
//! leaking passwords to the frontend
|
||||||
|
|
||||||
|
/// Standard informational user type, contains no password information
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
#[cfg_attr(feature = "server", derive(Queryable, Selectable, Identifiable))]
|
||||||
|
#[cfg_attr(feature = "server", diesel(table_name = crate::schema::users,
|
||||||
|
check_for_backend(diesel::pg::Pg)))]
|
||||||
|
pub struct User {
|
||||||
|
pub id: i32,
|
||||||
|
pub username: String,
|
||||||
|
pub created_at: chrono::DateTime<chrono::Local>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plaintext user credentials, used for login/signup form
|
||||||
|
pub struct UserCredentials {
|
||||||
|
pub username: String,
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg_if::cfg_if! {
|
||||||
|
if #[cfg(feature = "server")] {
|
||||||
|
|
||||||
|
use diesel::{
|
||||||
|
deserialize::{FromSql, FromSqlRow},
|
||||||
|
expression::AsExpression,
|
||||||
|
prelude::*,
|
||||||
|
serialize::ToSql,
|
||||||
|
sql_types,
|
||||||
|
};
|
||||||
|
use pbkdf2::{
|
||||||
|
PasswordHasher, PasswordVerifier, Pbkdf2, password_hash::Error::PasswordInvalid,
|
||||||
|
phc::PasswordHash,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::util::error::{Error, Result};
|
||||||
|
|
||||||
|
/// Newtype for a `String`-represented hashed password
|
||||||
|
#[derive(Clone, Debug, AsExpression, FromSqlRow)]
|
||||||
|
#[diesel(sql_type = sql_types::Text)]
|
||||||
|
pub struct HashedPassword(String);
|
||||||
|
|
||||||
|
impl HashedPassword {
|
||||||
|
/// Check a password attempt against this hashed password
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// `Ok(true)` for a correct password
|
||||||
|
/// `Ok(false)` for an incorrect password
|
||||||
|
/// `Err` for a hashing error
|
||||||
|
pub fn check(&self, password_attempt: String) -> Result<bool> {
|
||||||
|
let pw_hash = PasswordHash::new(&self.0)
|
||||||
|
.map_err(|e| Error::message_here(format!("Error parsing `HashedPassword`: {e}")))?;
|
||||||
|
|
||||||
|
match Pbkdf2::default().verify_password(password_attempt.as_bytes(), &pw_hash) {
|
||||||
|
Ok(()) => Ok(true),
|
||||||
|
Err(PasswordInvalid) => Ok(false),
|
||||||
|
Err(e) => Err(Error::message_here(format!(
|
||||||
|
"Error comparing password attempt against hash: {e}"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the "session auth hash" for `axum-login`, just the hashed password as bytes
|
||||||
|
pub fn auth_hash(&self) -> &[u8] {
|
||||||
|
self.0.as_bytes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<DB> FromSql<diesel::sql_types::Text, DB> for HashedPassword
|
||||||
|
where
|
||||||
|
DB: diesel::backend::Backend,
|
||||||
|
String: FromSql<sql_types::Text, DB>,
|
||||||
|
{
|
||||||
|
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
|
||||||
|
Ok(Self(String::from_sql(bytes)?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<DB> ToSql<diesel::sql_types::Text, DB> for HashedPassword
|
||||||
|
where
|
||||||
|
DB: diesel::backend::Backend,
|
||||||
|
String: ToSql<sql_types::Text, DB>,
|
||||||
|
{
|
||||||
|
fn to_sql<'b>(
|
||||||
|
&'b self,
|
||||||
|
out: &mut diesel::serialize::Output<'b, '_, DB>,
|
||||||
|
) -> diesel::serialize::Result {
|
||||||
|
self.0.to_sql(out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User as it appears in the database, with hashed password
|
||||||
|
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
|
||||||
|
#[diesel(table_name = crate::schema::users, check_for_backend(diesel::pg::Pg))]
|
||||||
|
pub struct DbUser {
|
||||||
|
pub id: i32,
|
||||||
|
pub username: String,
|
||||||
|
pub hashed_password: HashedPassword,
|
||||||
|
pub created_at: chrono::DateTime<chrono::Local>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<DbUser> for User {
|
||||||
|
fn from(db_user: DbUser) -> Self {
|
||||||
|
User {
|
||||||
|
id: db_user.id,
|
||||||
|
username: db_user.username,
|
||||||
|
created_at: db_user.created_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User credentials with hashed password
|
||||||
|
#[derive(Clone, Debug, Insertable, Queryable, Selectable)]
|
||||||
|
#[diesel(table_name = crate::schema::users, check_for_backend(diesel::pg::Pg))]
|
||||||
|
pub struct HashedUserCredentials {
|
||||||
|
username: String,
|
||||||
|
hashed_password: HashedPassword,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<DbUser> for HashedUserCredentials {
|
||||||
|
fn from(db_user: DbUser) -> Self {
|
||||||
|
HashedUserCredentials {
|
||||||
|
username: db_user.username,
|
||||||
|
hashed_password: db_user.hashed_password,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserCredentials {
|
||||||
|
/// Attempt to convert into `HashedUserCredentials` by hashing the password. Yields a PBKDF2
|
||||||
|
/// error on failure.
|
||||||
|
pub fn try_hash(self) -> Result<HashedUserCredentials, pbkdf2::password_hash::Error> {
|
||||||
|
let hashed_password = Pbkdf2::default().hash_password(self.password.as_bytes())?;
|
||||||
|
|
||||||
|
Ok(HashedUserCredentials {
|
||||||
|
username: self.username,
|
||||||
|
hashed_password: HashedPassword(hashed_password.to_string()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,10 @@
|
|||||||
// @generated automatically by Diesel CLI.
|
// @generated automatically by Diesel CLI.
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
users (id) {
|
||||||
|
id -> Int4,
|
||||||
|
username -> Varchar,
|
||||||
|
hashed_password -> Varchar,
|
||||||
|
created_at -> Timestamptz,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
91
src/server/auth.rs
Normal file
91
src/server/auth.rs
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
use axum_login::{AuthUser, AuthnBackend, UserId};
|
||||||
|
use diesel::prelude::*;
|
||||||
|
use diesel_async::RunQueryDsl;
|
||||||
|
|
||||||
|
use crate::models::user::{DbUser, UserCredentials};
|
||||||
|
use crate::server::database::{DbConn, DbPool};
|
||||||
|
use crate::util::error::{Contextualize, Error, Result};
|
||||||
|
|
||||||
|
impl AuthUser for DbUser {
|
||||||
|
type Id = i32;
|
||||||
|
|
||||||
|
fn id(&self) -> Self::Id {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_auth_hash(&self) -> &[u8] {
|
||||||
|
self.hashed_password.auth_hash()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AuthBackend {
|
||||||
|
pub db_pool: DbPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthnBackend for AuthBackend {
|
||||||
|
type User = DbUser;
|
||||||
|
type Credentials = UserCredentials;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
async fn authenticate(
|
||||||
|
&self,
|
||||||
|
attempt_creds: Self::Credentials,
|
||||||
|
) -> Result<Option<Self::User>, Self::Error> {
|
||||||
|
let mut db_conn = self
|
||||||
|
.db_pool
|
||||||
|
.get()
|
||||||
|
.await
|
||||||
|
.err_context("Failed to get database pool connection")?;
|
||||||
|
|
||||||
|
let user = get_user_by_username(&mut db_conn, attempt_creds.username)
|
||||||
|
.await
|
||||||
|
.err_context("Error fetching user for authentication check")?;
|
||||||
|
|
||||||
|
let Some(user) = user else { return Ok(None) };
|
||||||
|
|
||||||
|
let password_result = user
|
||||||
|
.hashed_password
|
||||||
|
.check(attempt_creds.password)
|
||||||
|
.err_context("Error checking user password attempt")?;
|
||||||
|
|
||||||
|
if password_result {
|
||||||
|
Ok(Some(user))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_user(&self, user_id: &UserId<Self>) -> Result<Option<Self::User>, Self::Error> {
|
||||||
|
let mut db_conn = self
|
||||||
|
.db_pool
|
||||||
|
.get()
|
||||||
|
.await
|
||||||
|
.err_context("Failed to get database pool connection")?;
|
||||||
|
|
||||||
|
get_user_by_id(&mut db_conn, *user_id)
|
||||||
|
.await
|
||||||
|
.err_context("Failed fetching user for session")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_user_by_id(db_conn: &mut DbConn, id: i32) -> Result<Option<DbUser>> {
|
||||||
|
crate::schema::users::table
|
||||||
|
.find(id)
|
||||||
|
.first(db_conn)
|
||||||
|
.await
|
||||||
|
.optional()
|
||||||
|
.err_context("Error fetching user from database by id")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_user_by_username(
|
||||||
|
db_conn: &mut DbConn,
|
||||||
|
username: String,
|
||||||
|
) -> Result<Option<DbUser>> {
|
||||||
|
crate::schema::users::table
|
||||||
|
.filter(crate::schema::users::username.eq(username))
|
||||||
|
.first(db_conn)
|
||||||
|
.await
|
||||||
|
.optional()
|
||||||
|
.err_context("Error fetching user from database by username")
|
||||||
|
}
|
||||||
@@ -1,8 +1,148 @@
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct AuthConfig {
|
||||||
|
pub open_signup: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a connection URI from parts
|
||||||
|
fn format_uri(
|
||||||
|
scheme: &str,
|
||||||
|
username: &Option<String>,
|
||||||
|
password: &Option<String>,
|
||||||
|
host: &str,
|
||||||
|
port: &Option<u16>,
|
||||||
|
path: &Option<String>,
|
||||||
|
) -> String {
|
||||||
|
let mut url = format!("{scheme}://");
|
||||||
|
|
||||||
|
if let Some(username) = username {
|
||||||
|
url.push_str(username);
|
||||||
|
|
||||||
|
if let Some(password) = password {
|
||||||
|
url.push_str(&format!(":{password}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
url.push('@');
|
||||||
|
}
|
||||||
|
|
||||||
|
url.push_str(host);
|
||||||
|
|
||||||
|
if let Some(port) = port {
|
||||||
|
url.push_str(&format!(":{port}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(path) = path {
|
||||||
|
url.push_str(&format!("/{path}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
url
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct DatabaseConfig {
|
||||||
|
#[serde(flatten)]
|
||||||
|
connection: DatabaseConnectionConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DatabaseConfig {
|
||||||
|
/// Get the configured database connection URI
|
||||||
|
pub fn connection_uri(&self) -> String {
|
||||||
|
self.connection.as_uri()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
enum DatabaseConnectionConfig {
|
||||||
|
FromUrl {
|
||||||
|
url: String,
|
||||||
|
},
|
||||||
|
FromParts {
|
||||||
|
host: String,
|
||||||
|
port: Option<u16>,
|
||||||
|
database: Option<String>,
|
||||||
|
username: Option<String>,
|
||||||
|
password: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DatabaseConnectionConfig {
|
||||||
|
/// Convert this configuration into the Postgres connection URI
|
||||||
|
pub fn as_uri(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::FromUrl { url } => url.clone(),
|
||||||
|
Self::FromParts {
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
database,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
} => format_uri("postgres", username, password, host, port, database),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
enum KeyValStoreConnectionConfig {
|
||||||
|
FromUrl {
|
||||||
|
url: String,
|
||||||
|
},
|
||||||
|
FromParts {
|
||||||
|
scheme: Option<String>,
|
||||||
|
host: String,
|
||||||
|
port: Option<u16>,
|
||||||
|
database: Option<String>,
|
||||||
|
username: Option<String>,
|
||||||
|
password: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyValStoreConnectionConfig {
|
||||||
|
/// Convert this configuration into the Redis connection URI
|
||||||
|
pub fn as_uri(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::FromUrl { url } => url.clone(),
|
||||||
|
Self::FromParts {
|
||||||
|
scheme,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
database,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
} => format_uri(
|
||||||
|
scheme.as_deref().unwrap_or("redis"),
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
database,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct KeyValStoreConfig {
|
||||||
|
#[serde(flatten)]
|
||||||
|
connection: KeyValStoreConnectionConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyValStoreConfig {
|
||||||
|
/// Get the configured database connection URI
|
||||||
|
pub fn connection_uri(&self) -> String {
|
||||||
|
self.connection.as_uri()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
/// Top-level application configuration
|
/// Top-level application configuration
|
||||||
pub struct Config {}
|
pub struct Config {
|
||||||
|
pub auth: AuthConfig,
|
||||||
|
pub database: DatabaseConfig,
|
||||||
|
pub key_val_store: KeyValStoreConfig,
|
||||||
|
}
|
||||||
|
|
||||||
/// Parse configuration from the expected files and environment variables
|
/// Parse configuration from the expected files and environment variables
|
||||||
pub fn load_config() -> Result<Config, config::ConfigError> {
|
pub fn load_config() -> Result<Config, config::ConfigError> {
|
||||||
@@ -12,6 +152,7 @@ pub fn load_config() -> Result<Config, config::ConfigError> {
|
|||||||
|
|
||||||
config::Config::builder()
|
config::Config::builder()
|
||||||
.set_default("server.port", 8080)?
|
.set_default("server.port", 8080)?
|
||||||
|
.set_default("auth.open_signup", false)?
|
||||||
.add_source(File::with_name(&format!("/etc/{pkg_name}/config")).required(false))
|
.add_source(File::with_name(&format!("/etc/{pkg_name}/config")).required(false))
|
||||||
.add_source(File::with_name(&format!("/etc/{pkg_name}")).required(false))
|
.add_source(File::with_name(&format!("/etc/{pkg_name}")).required(false))
|
||||||
.add_source(File::with_name("config").required(false))
|
.add_source(File::with_name("config").required(false))
|
||||||
|
|||||||
40
src/server/database.rs
Normal file
40
src/server/database.rs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
use diesel_async::{
|
||||||
|
AsyncMigrationHarness, AsyncPgConnection,
|
||||||
|
pooled_connection::{AsyncDieselConnectionManager, deadpool::Pool},
|
||||||
|
};
|
||||||
|
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
|
||||||
|
|
||||||
|
use crate::util::error::{Contextualize, Error, ErrorType};
|
||||||
|
|
||||||
|
pub const DB_MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
||||||
|
|
||||||
|
pub type DbPool = Pool<AsyncPgConnection>;
|
||||||
|
pub type DbConn = AsyncPgConnection;
|
||||||
|
|
||||||
|
/// Connect to the database using the given URI, and perform migrations
|
||||||
|
pub async fn setup<S: Into<String>>(database_uri: S) -> Result<DbPool, Error> {
|
||||||
|
let pool_manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new(database_uri);
|
||||||
|
|
||||||
|
let pool = Pool::builder(pool_manager)
|
||||||
|
.build()
|
||||||
|
// At time of writing only the `NoRuntimeSpecified` error is possible from the builder,
|
||||||
|
// which should only occur when configuring timeouts without a `Runtime`
|
||||||
|
.map_err(|e| ErrorType::Database(e.to_string()))
|
||||||
|
.err_context("Error creating pool for database connections")?;
|
||||||
|
|
||||||
|
tracing::debug!("Establishing connection to database for migrations...");
|
||||||
|
|
||||||
|
let migration_conn = pool
|
||||||
|
.get()
|
||||||
|
.await
|
||||||
|
.err_context("Failed to get connection to database")?;
|
||||||
|
|
||||||
|
tracing::debug!("Running migrations...");
|
||||||
|
|
||||||
|
AsyncMigrationHarness::new(migration_conn)
|
||||||
|
.run_pending_migrations(DB_MIGRATIONS)
|
||||||
|
.map_err(|e| ErrorType::Database(e.to_string()))
|
||||||
|
.err_context("Failed to run pending database migrations")?;
|
||||||
|
|
||||||
|
Ok(pool)
|
||||||
|
}
|
||||||
29
src/server/key_val_store.rs
Normal file
29
src/server/key_val_store.rs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
use fred::prelude::*;
|
||||||
|
|
||||||
|
use crate::util::error::{Contextualize, Error, ErrorType};
|
||||||
|
|
||||||
|
const KEY_VAL_POOL_SIZE: usize = 4;
|
||||||
|
|
||||||
|
pub type KeyValPool = Pool;
|
||||||
|
|
||||||
|
pub async fn setup(connection_uri: &str) -> Result<KeyValPool, Error> {
|
||||||
|
let config = Config::from_url(connection_uri)
|
||||||
|
.map_err(|e| ErrorType::KeyValStore(e.to_string()))
|
||||||
|
.err_context("Error creating key-value store config")?;
|
||||||
|
|
||||||
|
let pool = Builder::from_config(config)
|
||||||
|
.build_pool(KEY_VAL_POOL_SIZE)
|
||||||
|
// At time of writing the only error that could occur here is if config is not provided.
|
||||||
|
// Since we're building a pool `from_config`, this shouldn't be possible
|
||||||
|
.map_err(|e| ErrorType::KeyValStore(e.to_string()))
|
||||||
|
.err_context("Error creating pool for key-value store")?;
|
||||||
|
|
||||||
|
tracing::debug!("Establishing connection to key-value store...");
|
||||||
|
|
||||||
|
pool.init()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ErrorType::KeyValStore(e.to_string()))
|
||||||
|
.err_context("Error connecting to key-value store")?;
|
||||||
|
|
||||||
|
Ok(pool)
|
||||||
|
}
|
||||||
@@ -1,13 +1,33 @@
|
|||||||
use crate::App;
|
use dioxus::fullstack::axum::Router;
|
||||||
use crate::util::error::{Error, Result};
|
|
||||||
|
|
||||||
pub fn main() -> Result<()> {
|
use crate::App;
|
||||||
|
use crate::server::{config, database, key_val_store};
|
||||||
|
use crate::util::error::{Contextualize, Error, Result};
|
||||||
|
|
||||||
|
pub fn main() -> Result<std::convert::Infallible> {
|
||||||
if let Err(e) = dotenvy::dotenv() {
|
if let Err(e) = dotenvy::dotenv() {
|
||||||
tracing::warn!("Error reading .env: {e}");
|
tracing::warn!("Error reading .env: {e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
tracing::info!("Setup complete, launching web server...");
|
// `Ok(...?)` is because `dioxus::serve` expects an `anyhow::Result`
|
||||||
dioxus::launch(App);
|
dioxus::serve(async move || Ok(router_setup().await?));
|
||||||
|
}
|
||||||
Err(Error::message_here("Web server exited"))
|
|
||||||
|
/// Set up the axum Router
|
||||||
|
async fn router_setup() -> Result<Router> {
|
||||||
|
tracing::debug!("Loading configuration...");
|
||||||
|
let config = config::load_config()
|
||||||
|
.map_err(|e| Error::message_here(e.to_string()))
|
||||||
|
.err_context("Failed to load config")?;
|
||||||
|
|
||||||
|
let _db_pool = database::setup(config.database.connection_uri())
|
||||||
|
.await
|
||||||
|
.err_context("Failed database setup")?;
|
||||||
|
|
||||||
|
let _key_val_pool = key_val_store::setup(&config.key_val_store.connection_uri())
|
||||||
|
.await
|
||||||
|
.err_context("Failed key-value store setup")?;
|
||||||
|
|
||||||
|
tracing::info!("Setup complete, returning Router...");
|
||||||
|
Ok(dioxus::server::router(App))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
pub mod auth;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod database;
|
||||||
|
pub mod key_val_store;
|
||||||
pub mod main;
|
pub mod main;
|
||||||
|
|
||||||
pub use main::main;
|
pub use main::main;
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ impl fmt::Display for ErrorLocation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, Error>;
|
pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, thiserror::Error)]
|
#[derive(Debug, Clone, Deserialize, Serialize, thiserror::Error)]
|
||||||
pub struct Error {
|
pub struct Error {
|
||||||
@@ -242,9 +242,8 @@ impl dioxus_fullstack::AsStatusCode for Error {
|
|||||||
ErrorType::Database(msg) if *msg == (diesel::result::Error::NotFound).to_string() => {
|
ErrorType::Database(msg) if *msg == (diesel::result::Error::NotFound).to_string() => {
|
||||||
StatusCode::NOT_FOUND
|
StatusCode::NOT_FOUND
|
||||||
}
|
}
|
||||||
ErrorType::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
ErrorType::Error(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
ErrorType::ServerFnError(e) => e.as_status_code(),
|
ErrorType::ServerFnError(e) => e.as_status_code(),
|
||||||
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -293,6 +292,11 @@ pub enum ErrorType {
|
|||||||
|
|
||||||
#[error("Server function error: {0}")]
|
#[error("Server function error: {0}")]
|
||||||
ServerFnError(ServerFnError),
|
ServerFnError(ServerFnError),
|
||||||
|
|
||||||
|
// Using string to represent Fred errors, because Fred's Error type is not `Serialize`,
|
||||||
|
// and Fred is only available on the server
|
||||||
|
#[error("Key-value store error: {0}")]
|
||||||
|
KeyValStore(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ErrorType> for Error {
|
impl From<ErrorType> for Error {
|
||||||
@@ -309,3 +313,21 @@ impl From<diesel::result::Error> for Error {
|
|||||||
Error::new_here(ErrorType::Database(format!("{err}")))
|
Error::new_here(ErrorType::Database(format!("{err}")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// This would capture any `deapool::PoolError` and treat it as a database error
|
||||||
|
// but we're only using `deadpool` for our database, so it's fine
|
||||||
|
#[cfg(feature = "server")]
|
||||||
|
impl From<diesel_async::pooled_connection::deadpool::PoolError> for Error {
|
||||||
|
#[track_caller]
|
||||||
|
fn from(err: diesel_async::pooled_connection::deadpool::PoolError) -> Self {
|
||||||
|
Error::new_here(ErrorType::Database(format!("{err}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "server")]
|
||||||
|
impl From<fred::error::Error> for Error {
|
||||||
|
#[track_caller]
|
||||||
|
fn from(err: fred::error::Error) -> Self {
|
||||||
|
Error::new_here(ErrorType::KeyValStore(format!("{err}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user