hexagonal refactor
This commit is contained in:
@@ -1,858 +0,0 @@
|
||||
use std::{
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use sha2::{Digest, Sha256};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum DbError {
|
||||
#[error("database error: {0}")]
|
||||
Message(String),
|
||||
#[error("record not found")]
|
||||
NotFound,
|
||||
#[error("record already exists")]
|
||||
Conflict,
|
||||
#[error("database worker failed: {0}")]
|
||||
Worker(String),
|
||||
}
|
||||
|
||||
pub type DbResult<T> = Result<T, DbError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Database {
|
||||
connection: Arc<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct User {
|
||||
pub id: i64,
|
||||
pub email: String,
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SessionUser {
|
||||
pub user: User,
|
||||
pub csrf_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GroceryList {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub revision: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Item {
|
||||
pub id: i64,
|
||||
pub list_id: i64,
|
||||
pub name: String,
|
||||
pub quantity: String,
|
||||
pub note: String,
|
||||
pub category_id: Option<i64>,
|
||||
pub checked: bool,
|
||||
pub version: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Category {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub fn open(path: impl AsRef<Path>) -> DbResult<Self> {
|
||||
let connection = Connection::open(path).map_err(sql_error)?;
|
||||
configure(&connection)?;
|
||||
migrate(&connection)?;
|
||||
|
||||
Ok(Self {
|
||||
connection: Arc::new(Mutex::new(connection)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn open_in_memory() -> DbResult<Self> {
|
||||
Self::open(":memory:")
|
||||
}
|
||||
|
||||
async fn call<T, F>(&self, operation: F) -> DbResult<T>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&mut Connection) -> DbResult<T> + Send + 'static,
|
||||
{
|
||||
let connection = Arc::clone(&self.connection);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut connection = connection
|
||||
.lock()
|
||||
.map_err(|error| DbError::Worker(error.to_string()))?;
|
||||
operation(&mut connection)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| DbError::Worker(error.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn create_user(
|
||||
&self,
|
||||
email: String,
|
||||
display_name: String,
|
||||
password_hash: String,
|
||||
) -> DbResult<User> {
|
||||
self.call(move |connection| {
|
||||
let result = connection.execute(
|
||||
"INSERT INTO users (email, display_name, password_hash, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![email, display_name, password_hash, now()],
|
||||
);
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
let id = connection.last_insert_rowid();
|
||||
Ok(User {
|
||||
id,
|
||||
email,
|
||||
display_name,
|
||||
})
|
||||
}
|
||||
Err(error) if error.to_string().contains("UNIQUE") => Err(DbError::Conflict),
|
||||
Err(error) => Err(sql_error(error)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn find_user_by_email(&self, email: String) -> DbResult<Option<(User, String)>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT id, email, display_name, password_hash
|
||||
FROM users WHERE email = ?1 COLLATE NOCASE",
|
||||
params![email],
|
||||
|row| {
|
||||
Ok((
|
||||
User {
|
||||
id: row.get(0)?,
|
||||
email: row.get(1)?,
|
||||
display_name: row.get(2)?,
|
||||
},
|
||||
row.get(3)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn has_users(&self) -> DbResult<bool> {
|
||||
self.call(|connection| {
|
||||
connection
|
||||
.query_row("SELECT EXISTS(SELECT 1 FROM users)", [], |row| {
|
||||
Ok(row.get::<_, i64>(0)? != 0)
|
||||
})
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_session(&self, user_id: i64) -> DbResult<(String, String)> {
|
||||
self.call(move |connection| {
|
||||
let session_token = new_secret();
|
||||
let csrf_token = new_secret();
|
||||
connection
|
||||
.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
hash_secret(&session_token),
|
||||
user_id,
|
||||
csrf_token,
|
||||
now() + 60 * 60 * 24 * 30
|
||||
],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
Ok((session_token, csrf_token))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn session_user(&self, session_token: String) -> DbResult<Option<SessionUser>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT u.id, u.email, u.display_name, s.csrf_token
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ?1 AND s.expires_at > ?2",
|
||||
params![hash_secret(&session_token), now()],
|
||||
|row| {
|
||||
Ok(SessionUser {
|
||||
user: User {
|
||||
id: row.get(0)?,
|
||||
email: row.get(1)?,
|
||||
display_name: row.get(2)?,
|
||||
},
|
||||
csrf_token: row.get(3)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete_session(&self, session_token: String) -> DbResult<()> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = ?1",
|
||||
params![hash_secret(&session_token)],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_summaries(&self) -> DbResult<Vec<GroceryList>> {
|
||||
self.call(move |connection| {
|
||||
let mut statement = connection
|
||||
.prepare(
|
||||
"SELECT l.id, l.name, l.revision
|
||||
FROM lists l
|
||||
ORDER BY l.created_at DESC",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
Ok(GroceryList {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
revision: row.get(2)?,
|
||||
})
|
||||
})
|
||||
.map_err(sql_error)?;
|
||||
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_list(&self, name: String) -> DbResult<GroceryList> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO lists (name, revision, created_at)
|
||||
VALUES (?1, 0, ?2)",
|
||||
params![name, now()],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let list_id = transaction.last_insert_rowid();
|
||||
for (position, category_name) in DEFAULT_CATEGORIES.iter().enumerate() {
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO categories (list_id, name, position, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![list_id, category_name, position as i64, now()],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
}
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(GroceryList {
|
||||
id: list_id,
|
||||
name,
|
||||
revision: 0,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_access(&self, list_id: i64) -> DbResult<Option<GroceryList>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT l.id, l.name, l.revision
|
||||
FROM lists l
|
||||
WHERE l.id = ?1",
|
||||
params![list_id],
|
||||
|row| {
|
||||
Ok(GroceryList {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
revision: row.get(2)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn items(&self, list_id: i64) -> DbResult<Vec<Item>> {
|
||||
self.call(move |connection| {
|
||||
let mut statement = connection
|
||||
.prepare(
|
||||
"SELECT id, list_id, name, quantity, note, category_id, checked, version
|
||||
FROM items
|
||||
WHERE list_id = ?1
|
||||
ORDER BY position ASC, created_at ASC",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let rows = statement
|
||||
.query_map(params![list_id], |row| {
|
||||
Ok(Item {
|
||||
id: row.get(0)?,
|
||||
list_id: row.get(1)?,
|
||||
name: row.get(2)?,
|
||||
quantity: row.get(3)?,
|
||||
note: row.get(4)?,
|
||||
category_id: row.get(5)?,
|
||||
checked: row.get::<_, i64>(6)? != 0,
|
||||
version: row.get(7)?,
|
||||
})
|
||||
})
|
||||
.map_err(sql_error)?;
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn categories(&self, list_id: i64) -> DbResult<Vec<Category>> {
|
||||
self.call(move |connection| {
|
||||
let mut statement = connection
|
||||
.prepare(
|
||||
"SELECT id, name
|
||||
FROM categories
|
||||
WHERE list_id = ?1
|
||||
ORDER BY position ASC, name COLLATE NOCASE ASC",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let rows = statement
|
||||
.query_map(params![list_id], |row| {
|
||||
Ok(Category {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
})
|
||||
})
|
||||
.map_err(sql_error)?;
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_category(&self, list_id: i64, name: String) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let position: i64 = transaction
|
||||
.query_row(
|
||||
"SELECT COALESCE(MAX(position), -1) + 1
|
||||
FROM categories WHERE list_id = ?1",
|
||||
params![list_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let result = transaction.execute(
|
||||
"INSERT INTO categories (list_id, name, position, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![list_id, name, position, now()],
|
||||
);
|
||||
match result {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.to_string().contains("UNIQUE") => {
|
||||
return Err(DbError::Conflict);
|
||||
}
|
||||
Err(error) => return Err(sql_error(error)),
|
||||
}
|
||||
let revision = bump_revision(&transaction, list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn add_item(
|
||||
&self,
|
||||
list_id: i64,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<i64>,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
ensure_category(&transaction, list_id, category_id)?;
|
||||
let position: i64 = transaction
|
||||
.query_row(
|
||||
"SELECT COALESCE(MAX(position), -1) + 1 FROM items WHERE list_id = ?1",
|
||||
params![list_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO items
|
||||
(list_id, name, quantity, note, category_id, checked, version, position, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 0, 1, ?6, ?7, ?7)",
|
||||
params![list_id, name, quantity, note, category_id, position, now()],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let revision = bump_revision(&transaction, list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn set_item_checked(
|
||||
&self,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
checked: bool,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let changed = transaction
|
||||
.execute(
|
||||
"UPDATE items
|
||||
SET checked = ?1, version = version + 1, updated_at = ?2
|
||||
WHERE id = ?3 AND list_id = ?4",
|
||||
params![checked as i64, now(), item_id, list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
if changed == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
let revision = bump_revision(&transaction, list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_item(
|
||||
&self,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<i64>,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
ensure_category(&transaction, list_id, category_id)?;
|
||||
let changed = transaction
|
||||
.execute(
|
||||
"UPDATE items
|
||||
SET name = ?1, quantity = ?2, note = ?3, category_id = ?4,
|
||||
version = version + 1, updated_at = ?5
|
||||
WHERE id = ?6 AND list_id = ?7",
|
||||
params![name, quantity, note, category_id, now(), item_id, list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
if changed == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
let revision = bump_revision(&transaction, list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete_item(&self, list_id: i64, item_id: i64) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let changed = transaction
|
||||
.execute(
|
||||
"DELETE FROM items WHERE id = ?1 AND list_id = ?2",
|
||||
params![item_id, list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
if changed == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
let revision = bump_revision(&transaction, list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_invitation(&self, created_by: i64, token: String) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let expires_at = now() + 60 * 60 * 24 * 7;
|
||||
connection
|
||||
.execute(
|
||||
"INSERT INTO invitations (token_hash, created_by, expires_at)
|
||||
VALUES (?1, ?2, ?3)",
|
||||
params![hash_secret(&token), created_by, expires_at],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
Ok(expires_at)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn invitation(&self, token: String) -> DbResult<bool> {
|
||||
self.call(move |connection| {
|
||||
let valid = connection
|
||||
.query_row(
|
||||
"SELECT 1 FROM invitations
|
||||
WHERE token_hash = ?1 AND expires_at > ?2",
|
||||
params![hash_secret(&token), now()],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)?
|
||||
.is_some();
|
||||
Ok(valid)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn accept_invitation(&self, token: String) -> DbResult<()> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let valid = transaction
|
||||
.query_row(
|
||||
"SELECT 1 FROM invitations
|
||||
WHERE token_hash = ?1 AND expires_at > ?2",
|
||||
params![hash_secret(&token), now()],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)?
|
||||
.is_some();
|
||||
if !valid {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
transaction
|
||||
.execute(
|
||||
"DELETE FROM invitations WHERE token_hash = ?1",
|
||||
params![hash_secret(&token)],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn configure(connection: &Connection) -> DbResult<()> {
|
||||
connection
|
||||
.pragma_update(None, "foreign_keys", true)
|
||||
.map_err(sql_error)?;
|
||||
connection
|
||||
.pragma_update(None, "journal_mode", "WAL")
|
||||
.map_err(sql_error)?;
|
||||
connection
|
||||
.busy_timeout(std::time::Duration::from_secs(5))
|
||||
.map_err(sql_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn migrate(connection: &Connection) -> DbResult<()> {
|
||||
connection
|
||||
.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
csrf_token TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
revision INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
list_id INTEGER NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL COLLATE NOCASE,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (list_id, name)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS invitations (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
list_id INTEGER NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
quantity TEXT NOT NULL DEFAULT '',
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
|
||||
checked INTEGER NOT NULL DEFAULT 0,
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS items_list_idx ON items(list_id);
|
||||
CREATE INDEX IF NOT EXISTS categories_list_idx ON categories(list_id);
|
||||
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions(user_id);",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_category(
|
||||
transaction: &rusqlite::Transaction<'_>,
|
||||
list_id: i64,
|
||||
category_id: Option<i64>,
|
||||
) -> DbResult<()> {
|
||||
let Some(category_id) = category_id else {
|
||||
return Ok(());
|
||||
};
|
||||
let exists = transaction
|
||||
.query_row(
|
||||
"SELECT 1 FROM categories WHERE id = ?1 AND list_id = ?2",
|
||||
params![category_id, list_id],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)?;
|
||||
if exists.is_none() {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const DEFAULT_CATEGORIES: &[&str] = &[
|
||||
"Produce",
|
||||
"Meat & seafood",
|
||||
"Dairy & eggs",
|
||||
"Pantry",
|
||||
"Frozen",
|
||||
"Household",
|
||||
];
|
||||
|
||||
fn bump_revision(transaction: &rusqlite::Transaction<'_>, list_id: i64) -> DbResult<i64> {
|
||||
transaction
|
||||
.execute(
|
||||
"UPDATE lists SET revision = revision + 1 WHERE id = ?1",
|
||||
params![list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction
|
||||
.query_row(
|
||||
"SELECT revision FROM lists WHERE id = ?1",
|
||||
params![list_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(sql_error)
|
||||
}
|
||||
|
||||
fn sql_error(error: impl std::fmt::Display) -> DbError {
|
||||
DbError::Message(error.to_string())
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64
|
||||
}
|
||||
|
||||
pub fn new_secret() -> String {
|
||||
let mut bytes = [0_u8; 32];
|
||||
OsRng.fill_bytes(&mut bytes);
|
||||
hex::encode(bytes)
|
||||
}
|
||||
|
||||
pub fn hash_secret(secret: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(secret.as_bytes());
|
||||
hex::encode(hasher.finalize())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_a_list_and_item() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let list = database
|
||||
.create_list("Weekly shop".into())
|
||||
.await
|
||||
.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"Milk".into(),
|
||||
"2 litres".into(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let items = database.items(list.id).await.unwrap();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].name, "Milk");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_and_invitations_are_scoped_to_users() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let owner = database
|
||||
.create_user("owner@example.com".into(), "Owner".into(), "hash".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let list = database
|
||||
.create_list("Household".into())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(database.categories(list.id.clone()).await.unwrap().len(), 6);
|
||||
let (session_token, csrf_token) = database.create_session(owner.id.clone()).await.unwrap();
|
||||
|
||||
let session = database
|
||||
.session_user(session_token.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(session.user.id, owner.id);
|
||||
assert_eq!(session.csrf_token, csrf_token);
|
||||
|
||||
// Any registered account can access every list.
|
||||
assert_eq!(
|
||||
database
|
||||
.list_access(list.id.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.name,
|
||||
"Household"
|
||||
);
|
||||
|
||||
let invitation_token = "test-invitation".to_owned();
|
||||
database
|
||||
.create_invitation(owner.id.clone(), invitation_token.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
database
|
||||
.invitation(invitation_token.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
database
|
||||
.accept_invitation(invitation_token.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!database
|
||||
.invitation(invitation_token)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
// A list created later is also accessible to every account.
|
||||
let future_list = database
|
||||
.create_list("Future shop".into())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
database
|
||||
.list_access(future_list.id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.name,
|
||||
"Future shop"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checked_state_is_set_not_toggled() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let list = database.create_list("List".into()).await.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"Coffee".into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let item = database.items(list.id.clone()).await.unwrap().remove(0);
|
||||
|
||||
database
|
||||
.set_item_checked(list.id.clone(), item.id.clone(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
database
|
||||
.set_item_checked(list.id.clone(), item.id.clone(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let item = database.items(list.id).await.unwrap().remove(0);
|
||||
assert!(item.checked);
|
||||
assert_eq!(item.version, 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checking_an_item_does_not_change_list_order() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let list = database.create_list("List".into()).await.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"First".into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"Second".into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first_item = database.items(list.id.clone()).await.unwrap().remove(0);
|
||||
|
||||
database
|
||||
.set_item_checked(list.id.clone(), first_item.id, true)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let items = database.items(list.id).await.unwrap();
|
||||
assert_eq!(items[0].name, "First");
|
||||
assert!(items[0].checked);
|
||||
assert_eq!(items[1].name, "Second");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum DomainError {
|
||||
#[error("database error: {0}")]
|
||||
Database(String),
|
||||
#[error("record not found")]
|
||||
NotFound,
|
||||
#[error("record already exists")]
|
||||
Conflict,
|
||||
}
|
||||
|
||||
pub type DomainResult<T> = Result<T, DomainError>;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct User {
|
||||
pub id: i64,
|
||||
pub email: String,
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SessionUser {
|
||||
pub user: User,
|
||||
pub csrf_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GroceryList {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub revision: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Item {
|
||||
pub id: i64,
|
||||
pub list_id: i64,
|
||||
pub name: String,
|
||||
pub quantity: String,
|
||||
pub note: String,
|
||||
pub category_id: Option<i64>,
|
||||
pub checked: bool,
|
||||
pub version: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Category {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PresenceUser {
|
||||
pub user_id: i64,
|
||||
pub display_name: String,
|
||||
}
|
||||
+771
@@ -0,0 +1,771 @@
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{
|
||||
Form, FromRequest, FromRequestParts, Path, Query, Request, State,
|
||||
ws::{Message, WebSocket, WebSocketUpgrade},
|
||||
},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header, request::Parts},
|
||||
middleware::{self, Next},
|
||||
response::{Html, IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::{Deserialize, de::DeserializeOwned};
|
||||
use thiserror::Error;
|
||||
use tower_http::{services::ServeDir, trace::TraceLayer};
|
||||
use tracing::{error, warn};
|
||||
|
||||
use crate::domain::{DomainError, SessionUser};
|
||||
use crate::ports::{HubEvent, RealtimeNotifier};
|
||||
use crate::services::{AuthService, InvitationService, ListService};
|
||||
use crate::views;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub auth: Arc<AuthService>,
|
||||
pub lists: Arc<ListService>,
|
||||
pub invitations: Arc<InvitationService>,
|
||||
pub realtime: Arc<dyn RealtimeNotifier>,
|
||||
pub cookie_secure: bool,
|
||||
pub public_base_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AppError {
|
||||
#[error("database error")]
|
||||
Database(#[from] DomainError),
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
match self {
|
||||
AppError::Database(_) => status_html_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
views::error_page("500", "Something went wrong."),
|
||||
),
|
||||
AppError::BadRequest(message) => {
|
||||
status_html_response(StatusCode::BAD_REQUEST, views::error_page("400", &message))
|
||||
}
|
||||
AppError::NotFound => status_html_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
views::error_page("404", "That page could not be found."),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/", get(home))
|
||||
.route("/login", get(login_page).post(login))
|
||||
.route("/register", get(register_page).post(register))
|
||||
.route("/logout", post(logout))
|
||||
.route("/lists", get(lists_page).post(create_list))
|
||||
.route("/lists/{list_id}", get(list_page))
|
||||
.route("/lists/{list_id}/items", post(add_item))
|
||||
.route("/lists/{list_id}/items/{item_id}/check", post(check_item))
|
||||
.route("/lists/{list_id}/items/{item_id}/edit", post(edit_item))
|
||||
.route("/lists/{list_id}/items/{item_id}/delete", post(delete_item))
|
||||
.route("/lists/{list_id}/categories", post(create_category))
|
||||
.route("/invitations", post(create_invitation))
|
||||
.route("/lists/{list_id}/stream", get(list_stream))
|
||||
.route("/invite/{token}", get(invitation_page))
|
||||
.route("/invite/{token}/accept", post(accept_invitation))
|
||||
.nest_service("/static", ServeDir::new("static"))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(middleware::from_fn(log_response_status))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CurrentUser {
|
||||
session_token: String,
|
||||
session: SessionUser,
|
||||
}
|
||||
|
||||
impl FromRequestParts<AppState> for CurrentUser {
|
||||
type Rejection = Response;
|
||||
|
||||
fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &AppState,
|
||||
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
|
||||
let session_token = cookie_value(&parts.headers, "session");
|
||||
let auth = Arc::clone(&state.auth);
|
||||
async move {
|
||||
let Some(session_token) = session_token else {
|
||||
return Err(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
match auth.session_user(session_token.clone()).await {
|
||||
Ok(Some(session)) => Ok(Self {
|
||||
session_token,
|
||||
session,
|
||||
}),
|
||||
Ok(None) => Err(Redirect::to("/login").into_response()),
|
||||
Err(error) => Err(AppError::Database(error).into_response()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LoggedForm<T>(T);
|
||||
|
||||
impl<S, T> FromRequest<S> for LoggedForm<T>
|
||||
where
|
||||
S: Send + Sync,
|
||||
T: DeserializeOwned + Send,
|
||||
{
|
||||
type Rejection = Response;
|
||||
|
||||
fn from_request(
|
||||
request: Request,
|
||||
state: &S,
|
||||
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
|
||||
let method = request.method().clone();
|
||||
let uri = request.uri().clone();
|
||||
async move {
|
||||
match Form::<T>::from_request(request, state).await {
|
||||
Ok(Form(value)) => Ok(Self(value)),
|
||||
Err(rejection) => {
|
||||
warn!(
|
||||
%method,
|
||||
%uri,
|
||||
rejection = ?rejection,
|
||||
"request form deserialization failed"
|
||||
);
|
||||
Err(rejection.into_response())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InviteQuery {
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RegisterForm {
|
||||
display_name: String,
|
||||
email: String,
|
||||
password: String,
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct LoginForm {
|
||||
email: String,
|
||||
password: String,
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CreateListForm {
|
||||
name: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ItemForm {
|
||||
name: String,
|
||||
quantity: String,
|
||||
#[serde(default)]
|
||||
note: String,
|
||||
#[serde(default)]
|
||||
category_id: Option<String>,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CheckForm {
|
||||
checked: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CsrfForm {
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CategoryForm {
|
||||
name: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
async fn home() -> Redirect {
|
||||
Redirect::to("/lists")
|
||||
}
|
||||
|
||||
async fn log_response_status(request: Request, next: Next) -> Response {
|
||||
let method = request.method().clone();
|
||||
let uri = request.uri().clone();
|
||||
let response = next.run(request).await;
|
||||
let status = response.status();
|
||||
|
||||
if status.is_server_error() {
|
||||
error!(%method, %uri, %status, "request returned server error");
|
||||
} else if status.is_client_error() {
|
||||
warn!(%method, %uri, %status, "request returned client error");
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
async fn login_page(Query(query): Query<InviteQuery>) -> Result<Response, AppError> {
|
||||
Ok(html_response(views::login_page(
|
||||
None,
|
||||
query.invite.as_deref(),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn register_page(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<InviteQuery>,
|
||||
) -> Result<Response, AppError> {
|
||||
if state.auth.can_register(query.invite.as_deref()).await? {
|
||||
Ok(html_response(views::register_page(
|
||||
None,
|
||||
query.invite.as_deref(),
|
||||
)))
|
||||
} else {
|
||||
Ok(status_html_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
views::registration_closed_page(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
async fn register(
|
||||
State(state): State<AppState>,
|
||||
LoggedForm(form): LoggedForm<RegisterForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
if !state.auth.can_register(form.invite.as_deref()).await? {
|
||||
return Ok(status_html_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
views::registration_closed_page(),
|
||||
));
|
||||
}
|
||||
let display_name = form.display_name.trim().to_owned();
|
||||
let email = form.email.trim().to_lowercase();
|
||||
if display_name.is_empty() || display_name.chars().count() > 50 {
|
||||
return Ok(html_response(views::register_page(
|
||||
Some("Enter a name between 1 and 50 characters."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
if !email.contains('@') || email.len() > 200 {
|
||||
return Ok(html_response(views::register_page(
|
||||
Some("Enter a valid email address."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
|
||||
let (_user, session_token) = match state
|
||||
.auth
|
||||
.register(display_name, email, form.password, form.invite.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(result) => result,
|
||||
Err(DomainError::Conflict) => {
|
||||
return Ok(html_response(views::register_page(
|
||||
Some("An account with that email already exists."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
Err(error) => return Err(AppError::Database(error)),
|
||||
};
|
||||
|
||||
let destination = form
|
||||
.invite
|
||||
.filter(|invite| !invite.is_empty())
|
||||
.map(|invite| format!("/invite/{invite}"))
|
||||
.unwrap_or_else(|| "/lists".into());
|
||||
let mut response = Redirect::to(&destination).into_response();
|
||||
set_session_cookie(&mut response, &session_token, state.cookie_secure);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn login(
|
||||
State(state): State<AppState>,
|
||||
LoggedForm(form): LoggedForm<LoginForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
let email = form.email.trim().to_lowercase();
|
||||
let result = state.auth.login(email, form.password).await?;
|
||||
let Some((_user, session_token)) = result else {
|
||||
return Ok(html_response(views::login_page(
|
||||
Some("Email or password is incorrect."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
};
|
||||
|
||||
let destination = form
|
||||
.invite
|
||||
.filter(|invite| !invite.is_empty())
|
||||
.map(|invite| format!("/invite/{invite}"))
|
||||
.unwrap_or_else(|| "/lists".into());
|
||||
let mut response = Redirect::to(&destination).into_response();
|
||||
set_session_cookie(&mut response, &session_token, state.cookie_secure);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn logout(State(state): State<AppState>, user: CurrentUser) -> Result<Response, AppError> {
|
||||
state.auth.logout(user.session_token).await?;
|
||||
let mut response = Redirect::to("/login").into_response();
|
||||
clear_session_cookie(&mut response, state.cookie_secure);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn lists_page(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
) -> Result<Response, AppError> {
|
||||
let lists = state.lists.list_summaries().await?;
|
||||
Ok(html_response(views::lists_page(
|
||||
&user.session.user,
|
||||
&lists,
|
||||
&user.session.csrf_token,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn create_list(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
LoggedForm(form): LoggedForm<CreateListForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
let name = form.name.trim().to_owned();
|
||||
if name.is_empty() || name.chars().count() > 80 {
|
||||
return Err(AppError::BadRequest(
|
||||
"List names must be between 1 and 80 characters.".into(),
|
||||
));
|
||||
}
|
||||
let list = state.lists.create_list(name).await?;
|
||||
Ok(Redirect::to(&format!("/lists/{}", list.id)).into_response())
|
||||
}
|
||||
|
||||
async fn list_page(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
) -> Result<Response, AppError> {
|
||||
let access = require_list(&state, list_id).await?;
|
||||
let items = state.lists.items(list_id).await?;
|
||||
let categories = state.lists.categories(list_id).await?;
|
||||
let presence = state.realtime.presence(list_id).await;
|
||||
Ok(html_response(views::list_page(
|
||||
&user.session.user,
|
||||
&access,
|
||||
&items,
|
||||
&categories,
|
||||
&presence,
|
||||
&user.session.csrf_token,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn add_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
LoggedForm(form): LoggedForm<ItemForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_list(&state, list_id).await?;
|
||||
let name = form.name.trim().to_owned();
|
||||
let quantity = form.quantity.trim().to_owned();
|
||||
let note = form.note.trim().to_owned();
|
||||
let category_id = parse_category_id(form.category_id);
|
||||
if name.is_empty() || name.chars().count() > 120 {
|
||||
return Err(AppError::BadRequest(
|
||||
"Item names must be between 1 and 120 characters.".into(),
|
||||
));
|
||||
}
|
||||
state
|
||||
.lists
|
||||
.add_item(list_id, name, quantity, note, category_id)
|
||||
.await?;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn check_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path((list_id, item_id)): Path<(i64, i64)>,
|
||||
LoggedForm(form): LoggedForm<CheckForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_list(&state, list_id).await?;
|
||||
let checked = match form.checked.as_str() {
|
||||
"1" | "true" => true,
|
||||
"0" | "false" => false,
|
||||
_ => return Err(AppError::BadRequest("Invalid checked value.".into())),
|
||||
};
|
||||
state
|
||||
.lists
|
||||
.set_item_checked(list_id, item_id, checked)
|
||||
.await?;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn edit_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path((list_id, item_id)): Path<(i64, i64)>,
|
||||
LoggedForm(form): LoggedForm<ItemForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_list(&state, list_id).await?;
|
||||
let name = form.name.trim().to_owned();
|
||||
if name.is_empty() || name.chars().count() > 120 {
|
||||
return Err(AppError::BadRequest(
|
||||
"Item names must be between 1 and 120 characters.".into(),
|
||||
));
|
||||
}
|
||||
state
|
||||
.lists
|
||||
.update_item(
|
||||
list_id,
|
||||
item_id,
|
||||
name,
|
||||
form.quantity.trim().to_owned(),
|
||||
form.note.trim().to_owned(),
|
||||
parse_category_id(form.category_id),
|
||||
)
|
||||
.await?;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn delete_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path((list_id, item_id)): Path<(i64, i64)>,
|
||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_list(&state, list_id).await?;
|
||||
state.lists.delete_item(list_id, item_id).await?;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn create_category(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
LoggedForm(form): LoggedForm<CategoryForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_list(&state, list_id).await?;
|
||||
let name = form.name.trim().to_owned();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::BadRequest(
|
||||
"Category names must be between 1 and 60 characters.".into(),
|
||||
));
|
||||
}
|
||||
state.lists.create_category(list_id, name).await?;
|
||||
|
||||
let access = require_list(&state, list_id).await?;
|
||||
let items = state.lists.items(list_id).await?;
|
||||
let categories = state.lists.categories(list_id).await?;
|
||||
Ok(html_response(views::category_created(
|
||||
&access,
|
||||
&items,
|
||||
&categories,
|
||||
&user.session.csrf_token,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn create_invitation(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
let token = state
|
||||
.invitations
|
||||
.create_invitation(user.session.user.id)
|
||||
.await?;
|
||||
let url = format!(
|
||||
"{}/invite/{token}",
|
||||
state.public_base_url.trim_end_matches('/')
|
||||
);
|
||||
Ok(html_response(views::invite_result(&url)))
|
||||
}
|
||||
|
||||
async fn invitation_page(
|
||||
State(state): State<AppState>,
|
||||
Path(token): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, AppError> {
|
||||
let info = state.invitations.invitation(token.clone()).await?;
|
||||
if !info {
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
let user = optional_user(&state, &headers).await?;
|
||||
Ok(html_response(views::invite_page(
|
||||
user.as_ref().map(|current| ¤t.session.user),
|
||||
&token,
|
||||
None,
|
||||
user.as_ref()
|
||||
.map(|current| current.session.csrf_token.as_str()),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn accept_invitation(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(token): Path<String>,
|
||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
state.invitations.accept_invitation(token).await?;
|
||||
Ok(Redirect::to("/lists").into_response())
|
||||
}
|
||||
|
||||
async fn list_stream(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
websocket: WebSocketUpgrade,
|
||||
) -> Result<Response, AppError> {
|
||||
require_list(&state, list_id).await?;
|
||||
let state_for_socket = state.clone();
|
||||
let user_for_socket = user.clone();
|
||||
Ok(websocket
|
||||
.on_upgrade(move |socket| handle_socket(state_for_socket, user_for_socket, list_id, socket))
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn handle_socket(state: AppState, user: CurrentUser, list_id: i64, socket: WebSocket) {
|
||||
let subscription = state
|
||||
.realtime
|
||||
.join(
|
||||
list_id,
|
||||
user.session.user.id,
|
||||
user.session.user.display_name.clone(),
|
||||
)
|
||||
.await;
|
||||
let connection_id = subscription.connection_id.clone();
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
let mut heartbeat = tokio::time::interval(Duration::from_secs(30));
|
||||
heartbeat.tick().await;
|
||||
|
||||
match websocket_snapshot(&state, &user, list_id, &subscription.presence).await {
|
||||
Ok(snapshot) => {
|
||||
if sender.send(Message::Text(snapshot.into())).await.is_err() {
|
||||
state.realtime.leave(list_id, &connection_id).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!(%error, "could not render websocket snapshot");
|
||||
state.realtime.leave(list_id, &connection_id).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let mut events = subscription.receiver;
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = events.recv() => {
|
||||
match event {
|
||||
Ok(HubEvent::ListChanged { list_id: event_list_id, revision }) if event_list_id == list_id => {
|
||||
tracing::debug!(%list_id, revision, "list changed on websocket");
|
||||
match websocket_list_update(&state, &user, list_id).await {
|
||||
Ok(update) => {
|
||||
if sender.send(Message::Text(update.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!(%error, "could not render websocket list update");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(HubEvent::PresenceChanged { list_id: event_list_id }) if event_list_id == list_id => {
|
||||
let presence = state.realtime.presence(list_id).await;
|
||||
let update = views::presence_panel(&presence, true).into_string();
|
||||
if sender.send(Message::Text(update.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
match websocket_snapshot(&state, &user, list_id, &state.realtime.presence(list_id).await).await {
|
||||
Ok(snapshot) => {
|
||||
if sender.send(Message::Text(snapshot.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!(%error, "could not resync websocket");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
if sender.send(Message::Ping(Vec::new().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
incoming = receiver.next() => {
|
||||
match incoming {
|
||||
Some(Ok(Message::Ping(payload))) => {
|
||||
if sender.send(Message::Pong(payload)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(Ok(Message::Close(_))) | None => break,
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(_)) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
state.realtime.leave(list_id, &connection_id).await;
|
||||
}
|
||||
|
||||
async fn websocket_snapshot(
|
||||
state: &AppState,
|
||||
user: &CurrentUser,
|
||||
list_id: i64,
|
||||
presence: &[crate::domain::PresenceUser],
|
||||
) -> Result<String, AppError> {
|
||||
let access = require_list(state, list_id).await?;
|
||||
let items = state.lists.items(list_id).await?;
|
||||
let categories = state.lists.categories(list_id).await?;
|
||||
Ok(
|
||||
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token)
|
||||
.into_string()
|
||||
+ &views::presence_panel(presence, true).into_string(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn websocket_list_update(
|
||||
state: &AppState,
|
||||
user: &CurrentUser,
|
||||
list_id: i64,
|
||||
) -> Result<String, AppError> {
|
||||
let access = require_list(state, list_id).await?;
|
||||
let items = state.lists.items(list_id).await?;
|
||||
let categories = state.lists.categories(list_id).await?;
|
||||
Ok(
|
||||
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token)
|
||||
.into_string(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_fragment_response(
|
||||
state: &AppState,
|
||||
user: &CurrentUser,
|
||||
list_id: i64,
|
||||
) -> Result<Response, AppError> {
|
||||
let access = require_list(state, list_id).await?;
|
||||
let items = state.lists.items(list_id).await?;
|
||||
let categories = state.lists.categories(list_id).await?;
|
||||
Ok(html_response(views::list_items_fragment(
|
||||
&access,
|
||||
&items,
|
||||
&categories,
|
||||
&user.session.csrf_token,
|
||||
false,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn require_list(
|
||||
state: &AppState,
|
||||
list_id: i64,
|
||||
) -> Result<crate::domain::GroceryList, AppError> {
|
||||
state
|
||||
.lists
|
||||
.get_list(list_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)
|
||||
}
|
||||
|
||||
async fn optional_user(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<Option<CurrentUser>, AppError> {
|
||||
let Some(session_token) = cookie_value(headers, "session") else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(state
|
||||
.auth
|
||||
.session_user(session_token.clone())
|
||||
.await?
|
||||
.map(|session| CurrentUser {
|
||||
session_token,
|
||||
session,
|
||||
}))
|
||||
}
|
||||
|
||||
fn verify_csrf(user: &CurrentUser, token: &str) -> Result<(), AppError> {
|
||||
if token.is_empty() || token != user.session.csrf_token {
|
||||
return Err(AppError::BadRequest(
|
||||
"Your form has expired. Refresh and try again.".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_category_id(category_id: Option<String>) -> Option<i64> {
|
||||
category_id
|
||||
.filter(|category_id| !category_id.trim().is_empty())
|
||||
.and_then(|category_id| category_id.trim().parse().ok())
|
||||
}
|
||||
|
||||
fn html_response(markup: maud::Markup) -> Response {
|
||||
Html(markup.into_string()).into_response()
|
||||
}
|
||||
|
||||
fn status_html_response(status: StatusCode, markup: maud::Markup) -> Response {
|
||||
(status, Html(markup.into_string())).into_response()
|
||||
}
|
||||
|
||||
fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(header::COOKIE)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.split(';')
|
||||
.map(str::trim)
|
||||
.find_map(|cookie| {
|
||||
let (key, value) = cookie.split_once('=')?;
|
||||
(key == name).then(|| value.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
fn set_session_cookie(response: &mut Response, token: &str, secure: bool) {
|
||||
let secure_attribute = if secure { "; Secure" } else { "" };
|
||||
let cookie = format!(
|
||||
"session={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000{secure_attribute}"
|
||||
);
|
||||
response.headers_mut().append(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie).expect("session cookie is valid"),
|
||||
);
|
||||
}
|
||||
|
||||
fn clear_session_cookie(response: &mut Response, secure: bool) {
|
||||
let secure_attribute = if secure { "; Secure" } else { "" };
|
||||
let cookie = format!("session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0{secure_attribute}");
|
||||
response.headers_mut().append(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie).expect("session cookie is valid"),
|
||||
);
|
||||
}
|
||||
+11
-29
@@ -1,19 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::{Mutex, broadcast};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PresenceUser {
|
||||
pub user_id: i64,
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum HubEvent {
|
||||
ListChanged { list_id: i64, revision: i64 },
|
||||
PresenceChanged { list_id: i64 },
|
||||
}
|
||||
use crate::domain::PresenceUser;
|
||||
use crate::ports::{HubEvent, RealtimeNotifier, Subscription};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ConnectionInfo {
|
||||
@@ -26,24 +18,14 @@ struct Room {
|
||||
connections: HashMap<String, ConnectionInfo>,
|
||||
}
|
||||
|
||||
pub struct Subscription {
|
||||
pub connection_id: String,
|
||||
pub receiver: broadcast::Receiver<HubEvent>,
|
||||
pub presence: Vec<PresenceUser>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Hub {
|
||||
pub struct InMemoryHub {
|
||||
rooms: Arc<Mutex<HashMap<i64, Room>>>,
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub async fn join(
|
||||
&self,
|
||||
list_id: i64,
|
||||
user_id: i64,
|
||||
display_name: String,
|
||||
) -> Subscription {
|
||||
#[async_trait]
|
||||
impl RealtimeNotifier for InMemoryHub {
|
||||
async fn join(&self, list_id: i64, user_id: i64, display_name: String) -> Subscription {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
let room = rooms.entry(list_id).or_insert_with(|| {
|
||||
let (sender, _) = broadcast::channel(64);
|
||||
@@ -53,7 +35,7 @@ impl Hub {
|
||||
}
|
||||
});
|
||||
|
||||
let connection_id = crate::db::new_secret();
|
||||
let connection_id = crate::security::new_secret();
|
||||
let already_present = room
|
||||
.connections
|
||||
.values()
|
||||
@@ -79,7 +61,7 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn leave(&self, list_id: i64, connection_id: &str) {
|
||||
async fn leave(&self, list_id: i64, connection_id: &str) {
|
||||
let mut rooms = self.rooms.lock().await;
|
||||
let mut remove_room = false;
|
||||
if let Some(room) = rooms.get_mut(&list_id) {
|
||||
@@ -100,7 +82,7 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn publish_list_changed(&self, list_id: i64, revision: i64) {
|
||||
async fn publish_list_changed(&self, list_id: i64, revision: i64) {
|
||||
let rooms = self.rooms.lock().await;
|
||||
if let Some(room) = rooms.get(&list_id) {
|
||||
let _ = room
|
||||
@@ -109,7 +91,7 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn presence(&self, list_id: i64) -> Vec<PresenceUser> {
|
||||
async fn presence(&self, list_id: i64) -> Vec<PresenceUser> {
|
||||
let rooms = self.rooms.lock().await;
|
||||
rooms
|
||||
.get(&list_id)
|
||||
|
||||
+63
-853
@@ -1,224 +1,32 @@
|
||||
mod db;
|
||||
mod domain;
|
||||
mod http;
|
||||
mod hub;
|
||||
mod ports;
|
||||
mod security;
|
||||
mod seed;
|
||||
mod services;
|
||||
mod sqlite;
|
||||
mod views;
|
||||
|
||||
use std::time::Duration;
|
||||
use std::{env, future::Future, path::Path as FilePath, sync::Arc};
|
||||
use std::env;
|
||||
use std::path::Path as FilePath;
|
||||
use std::sync::Arc;
|
||||
|
||||
use argon2::{
|
||||
Argon2,
|
||||
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString, rand_core::OsRng},
|
||||
};
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{
|
||||
Form, FromRequest, FromRequestParts, Path, Query, Request, State,
|
||||
ws::{Message, WebSocket, WebSocketUpgrade},
|
||||
},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header, request::Parts},
|
||||
middleware::{self, Next},
|
||||
response::{Html, IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::{Deserialize, de::DeserializeOwned};
|
||||
use thiserror::Error;
|
||||
use tokio::net::TcpListener;
|
||||
use tower_http::{services::ServeDir, trace::TraceLayer};
|
||||
use tracing::{error, info, warn};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::{
|
||||
db::{Database, DbError, SessionUser},
|
||||
hub::{Hub, HubEvent},
|
||||
use crate::http::{AppState, build_router};
|
||||
use crate::hub::InMemoryHub;
|
||||
use crate::ports::{
|
||||
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, PasswordHasher,
|
||||
RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
|
||||
};
|
||||
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
|
||||
use crate::services::{AuthService, InvitationService, ListService, RegistrationMode};
|
||||
use crate::sqlite::{
|
||||
SqliteCategoryRepository, SqliteInvitationRepository, SqliteItemRepository,
|
||||
SqliteListRepository, SqliteSessionRepository, SqliteDatabase, SqliteUserRepository,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
db: Database,
|
||||
hub: Arc<Hub>,
|
||||
cookie_secure: bool,
|
||||
public_base_url: String,
|
||||
registration_mode: RegistrationMode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum RegistrationMode {
|
||||
Open,
|
||||
InviteOnly,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
enum AppError {
|
||||
#[error("database error")]
|
||||
Database(#[from] DbError),
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
#[error("internal error: {0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, heading, message): (StatusCode, &str, String) = match self {
|
||||
Self::Database(DbError::NotFound) | Self::NotFound => (
|
||||
StatusCode::NOT_FOUND,
|
||||
"Not found",
|
||||
"We could not find that page or list.".into(),
|
||||
),
|
||||
Self::Database(DbError::Conflict) => (
|
||||
StatusCode::CONFLICT,
|
||||
"Already exists",
|
||||
"That value is already in use.".into(),
|
||||
),
|
||||
Self::BadRequest(message) => {
|
||||
warn!(reason = %message, "request rejected");
|
||||
(StatusCode::BAD_REQUEST, "Check that again", message)
|
||||
}
|
||||
Self::Database(error) => {
|
||||
error!(%error, "database request failed");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Something went wrong",
|
||||
"The request could not be completed.".into(),
|
||||
)
|
||||
}
|
||||
Self::Internal(error) => {
|
||||
error!(%error, "request failed");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Something went wrong",
|
||||
"The request could not be completed.".into(),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
status,
|
||||
Html(views::error_page(heading, &message).into_string()),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CurrentUser {
|
||||
session_token: String,
|
||||
session: SessionUser,
|
||||
}
|
||||
|
||||
impl FromRequestParts<AppState> for CurrentUser {
|
||||
type Rejection = Response;
|
||||
|
||||
fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &AppState,
|
||||
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
|
||||
let session_token = cookie_value(&parts.headers, "session");
|
||||
async move {
|
||||
let Some(session_token) = session_token else {
|
||||
return Err(Redirect::to("/login").into_response());
|
||||
};
|
||||
|
||||
match state.db.session_user(session_token.clone()).await {
|
||||
Ok(Some(session)) => Ok(Self {
|
||||
session_token,
|
||||
session,
|
||||
}),
|
||||
Ok(None) => Err(Redirect::to("/login").into_response()),
|
||||
Err(error) => Err(AppError::Database(error).into_response()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LoggedForm<T>(T);
|
||||
|
||||
impl<S, T> FromRequest<S> for LoggedForm<T>
|
||||
where
|
||||
S: Send + Sync,
|
||||
T: DeserializeOwned + Send,
|
||||
{
|
||||
type Rejection = Response;
|
||||
|
||||
fn from_request(
|
||||
request: Request,
|
||||
state: &S,
|
||||
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
|
||||
let method = request.method().clone();
|
||||
let uri = request.uri().clone();
|
||||
async move {
|
||||
match Form::<T>::from_request(request, state).await {
|
||||
Ok(Form(value)) => Ok(Self(value)),
|
||||
Err(rejection) => {
|
||||
warn!(
|
||||
%method,
|
||||
%uri,
|
||||
rejection = ?rejection,
|
||||
"request form deserialization failed"
|
||||
);
|
||||
Err(rejection.into_response())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct InviteQuery {
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RegisterForm {
|
||||
display_name: String,
|
||||
email: String,
|
||||
password: String,
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct LoginForm {
|
||||
email: String,
|
||||
password: String,
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CreateListForm {
|
||||
name: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ItemForm {
|
||||
name: String,
|
||||
quantity: String,
|
||||
#[serde(default)]
|
||||
note: String,
|
||||
#[serde(default)]
|
||||
category_id: Option<String>,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CheckForm {
|
||||
checked: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CsrfForm {
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CategoryForm {
|
||||
name: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -248,37 +56,52 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
};
|
||||
|
||||
let state = AppState {
|
||||
db: Database::open(database_path)?,
|
||||
hub: Arc::new(Hub::default()),
|
||||
cookie_secure,
|
||||
public_base_url,
|
||||
// Build the adapters (ports) and wire them into application services.
|
||||
let db = SqliteDatabase::open(&database_path).await?;
|
||||
let users: Arc<dyn UserRepository> = Arc::new(SqliteUserRepository);
|
||||
let sessions: Arc<dyn SessionRepository> = Arc::new(SqliteSessionRepository);
|
||||
let lists: Arc<dyn ListRepository> = Arc::new(SqliteListRepository);
|
||||
let categories: Arc<dyn CategoryRepository> = Arc::new(SqliteCategoryRepository);
|
||||
let items: Arc<dyn ItemRepository> = Arc::new(SqliteItemRepository);
|
||||
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
|
||||
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
||||
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
||||
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
||||
|
||||
let auth = Arc::new(AuthService::new(
|
||||
db.clone(),
|
||||
Arc::clone(&users),
|
||||
Arc::clone(&sessions),
|
||||
Arc::clone(&invitations),
|
||||
Arc::clone(&hasher),
|
||||
registration_mode,
|
||||
};
|
||||
));
|
||||
let lists_service = Arc::new(ListService::new(
|
||||
db.clone(),
|
||||
Arc::clone(&lists),
|
||||
Arc::clone(&categories),
|
||||
Arc::clone(&items),
|
||||
Arc::clone(&realtime),
|
||||
));
|
||||
let invitations_service = Arc::new(InvitationService::new(
|
||||
db.clone(),
|
||||
Arc::clone(&invitations),
|
||||
Arc::clone(&tokens),
|
||||
));
|
||||
|
||||
let seed_path = env::var("SEED_CONFIG").unwrap_or_else(|_| "seed.json".into());
|
||||
seed::seed_if_needed(&state.db, FilePath::new(&seed_path)).await;
|
||||
seed::seed_if_needed(&db, &users, &hasher, FilePath::new(&seed_path)).await;
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(home))
|
||||
.route("/login", get(login_page).post(login))
|
||||
.route("/register", get(register_page).post(register))
|
||||
.route("/logout", post(logout))
|
||||
.route("/lists", get(lists_page).post(create_list))
|
||||
.route("/lists/{list_id}", get(list_page))
|
||||
.route("/lists/{list_id}/items", post(add_item))
|
||||
.route("/lists/{list_id}/items/{item_id}/check", post(check_item))
|
||||
.route("/lists/{list_id}/items/{item_id}/edit", post(edit_item))
|
||||
.route("/lists/{list_id}/items/{item_id}/delete", post(delete_item))
|
||||
.route("/lists/{list_id}/categories", post(create_category))
|
||||
.route("/invitations", post(create_invitation))
|
||||
.route("/lists/{list_id}/stream", get(list_stream))
|
||||
.route("/invite/{token}", get(invitation_page))
|
||||
.route("/invite/{token}/accept", post(accept_invitation))
|
||||
.nest_service("/static", ServeDir::new("static"))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(middleware::from_fn(log_response_status))
|
||||
.with_state(state);
|
||||
let state = AppState {
|
||||
auth,
|
||||
lists: lists_service,
|
||||
invitations: invitations_service,
|
||||
realtime,
|
||||
cookie_secure,
|
||||
public_base_url,
|
||||
};
|
||||
|
||||
let app = build_router(state);
|
||||
|
||||
let listener = TcpListener::bind(&bind_address).await?;
|
||||
info!(address = %bind_address, "sustenance listening");
|
||||
@@ -314,616 +137,3 @@ async fn shutdown_signal() {
|
||||
|
||||
info!("signal received; starting graceful shutdown");
|
||||
}
|
||||
|
||||
async fn home() -> Redirect {
|
||||
Redirect::to("/lists")
|
||||
}
|
||||
|
||||
async fn log_response_status(request: Request, next: Next) -> Response {
|
||||
let method = request.method().clone();
|
||||
let uri = request.uri().clone();
|
||||
let response = next.run(request).await;
|
||||
let status = response.status();
|
||||
|
||||
if status.is_server_error() {
|
||||
error!(%method, %uri, %status, "request returned server error");
|
||||
} else if status.is_client_error() {
|
||||
warn!(%method, %uri, %status, "request returned client error");
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
async fn login_page(Query(query): Query<InviteQuery>) -> Result<Response, AppError> {
|
||||
Ok(html_response(views::login_page(
|
||||
None,
|
||||
query.invite.as_deref(),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn register_page(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<InviteQuery>,
|
||||
) -> Result<Response, AppError> {
|
||||
if can_register(&state, query.invite.as_deref()).await? {
|
||||
Ok(html_response(views::register_page(
|
||||
None,
|
||||
query.invite.as_deref(),
|
||||
)))
|
||||
} else {
|
||||
Ok(status_html_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
views::registration_closed_page(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
async fn register(
|
||||
State(state): State<AppState>,
|
||||
LoggedForm(form): LoggedForm<RegisterForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
if !can_register(&state, form.invite.as_deref()).await? {
|
||||
return Ok(status_html_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
views::registration_closed_page(),
|
||||
));
|
||||
}
|
||||
let display_name = form.display_name.trim().to_owned();
|
||||
let email = form.email.trim().to_lowercase();
|
||||
if display_name.is_empty() || display_name.chars().count() > 50 {
|
||||
return Ok(html_response(views::register_page(
|
||||
Some("Enter a name between 1 and 50 characters."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
if !email.contains('@') || email.len() > 200 {
|
||||
return Ok(html_response(views::register_page(
|
||||
Some("Enter a valid email address."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
|
||||
let password = form.password;
|
||||
let password_hash = tokio::task::spawn_blocking(move || hash_password(&password))
|
||||
.await
|
||||
.map_err(|error| AppError::Internal(error.to_string()))?
|
||||
.map_err(AppError::Internal)?;
|
||||
let user = match state
|
||||
.db
|
||||
.create_user(email, display_name, password_hash)
|
||||
.await
|
||||
{
|
||||
Ok(user) => user,
|
||||
Err(DbError::Conflict) => {
|
||||
return Ok(html_response(views::register_page(
|
||||
Some("An account with that email already exists."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
Err(error) => return Err(AppError::Database(error)),
|
||||
};
|
||||
|
||||
let (session_token, _) = state.db.create_session(user.id).await?;
|
||||
let destination = form
|
||||
.invite
|
||||
.filter(|invite| !invite.is_empty())
|
||||
.map(|invite| format!("/invite/{invite}"))
|
||||
.unwrap_or_else(|| "/lists".into());
|
||||
let mut response = Redirect::to(&destination).into_response();
|
||||
set_session_cookie(&mut response, &session_token, state.cookie_secure);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn login(
|
||||
State(state): State<AppState>,
|
||||
LoggedForm(form): LoggedForm<LoginForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
let email = form.email.trim().to_lowercase();
|
||||
let Some((user, password_hash)) = state.db.find_user_by_email(email).await? else {
|
||||
return Ok(html_response(views::login_page(
|
||||
Some("Email or password is incorrect."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
};
|
||||
|
||||
let password = form.password;
|
||||
let valid = tokio::task::spawn_blocking(move || verify_password(&password, &password_hash))
|
||||
.await
|
||||
.map_err(|error| AppError::Internal(error.to_string()))?
|
||||
.map_err(AppError::Internal)?;
|
||||
if !valid {
|
||||
return Ok(html_response(views::login_page(
|
||||
Some("Email or password is incorrect."),
|
||||
form.invite.as_deref(),
|
||||
)));
|
||||
}
|
||||
|
||||
let (session_token, _) = state.db.create_session(user.id).await?;
|
||||
let destination = form
|
||||
.invite
|
||||
.filter(|invite| !invite.is_empty())
|
||||
.map(|invite| format!("/invite/{invite}"))
|
||||
.unwrap_or_else(|| "/lists".into());
|
||||
let mut response = Redirect::to(&destination).into_response();
|
||||
set_session_cookie(&mut response, &session_token, state.cookie_secure);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn logout(State(state): State<AppState>, user: CurrentUser) -> Result<Response, AppError> {
|
||||
state.db.delete_session(user.session_token).await?;
|
||||
let mut response = Redirect::to("/login").into_response();
|
||||
clear_session_cookie(&mut response, state.cookie_secure);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn lists_page(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
) -> Result<Response, AppError> {
|
||||
let lists = state.db.list_summaries().await?;
|
||||
Ok(html_response(views::lists_page(
|
||||
&user.session.user,
|
||||
&lists,
|
||||
&user.session.csrf_token,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn create_list(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
LoggedForm(form): LoggedForm<CreateListForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
let name = form.name.trim().to_owned();
|
||||
if name.is_empty() || name.chars().count() > 80 {
|
||||
return Err(AppError::BadRequest(
|
||||
"List names must be between 1 and 80 characters.".into(),
|
||||
));
|
||||
}
|
||||
let list = state.db.create_list(name).await?;
|
||||
Ok(Redirect::to(&format!("/lists/{}", list.id)).into_response())
|
||||
}
|
||||
|
||||
async fn list_page(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
) -> Result<Response, AppError> {
|
||||
let access = require_access(&state, list_id).await?;
|
||||
let items = state.db.items(list_id).await?;
|
||||
let categories = state.db.categories(list_id).await?;
|
||||
let presence = state.hub.presence(list_id).await;
|
||||
Ok(html_response(views::list_page(
|
||||
&user.session.user,
|
||||
&access,
|
||||
&items,
|
||||
&categories,
|
||||
&presence,
|
||||
&user.session.csrf_token,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn add_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
LoggedForm(form): LoggedForm<ItemForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_access(&state, list_id).await?;
|
||||
let name = form.name.trim().to_owned();
|
||||
let quantity = form.quantity.trim().to_owned();
|
||||
let note = form.note.trim().to_owned();
|
||||
let category_id = parse_category_id(form.category_id);
|
||||
if name.is_empty() || name.chars().count() > 120 {
|
||||
return Err(AppError::BadRequest(
|
||||
"Item names must be between 1 and 120 characters.".into(),
|
||||
));
|
||||
}
|
||||
let revision = state
|
||||
.db
|
||||
.add_item(list_id, name, quantity, note, category_id)
|
||||
.await?;
|
||||
state.hub.publish_list_changed(list_id, revision).await;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn check_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path((list_id, item_id)): Path<(i64, i64)>,
|
||||
LoggedForm(form): LoggedForm<CheckForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_access(&state, list_id).await?;
|
||||
let checked = match form.checked.as_str() {
|
||||
"1" | "true" => true,
|
||||
"0" | "false" => false,
|
||||
_ => return Err(AppError::BadRequest("Invalid checked value.".into())),
|
||||
};
|
||||
let revision = state.db.set_item_checked(list_id, item_id, checked).await?;
|
||||
state.hub.publish_list_changed(list_id, revision).await;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn edit_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path((list_id, item_id)): Path<(i64, i64)>,
|
||||
LoggedForm(form): LoggedForm<ItemForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_access(&state, list_id).await?;
|
||||
let name = form.name.trim().to_owned();
|
||||
if name.is_empty() || name.chars().count() > 120 {
|
||||
return Err(AppError::BadRequest(
|
||||
"Item names must be between 1 and 120 characters.".into(),
|
||||
));
|
||||
}
|
||||
let revision = state
|
||||
.db
|
||||
.update_item(
|
||||
list_id,
|
||||
item_id,
|
||||
name,
|
||||
form.quantity.trim().to_owned(),
|
||||
form.note.trim().to_owned(),
|
||||
parse_category_id(form.category_id),
|
||||
)
|
||||
.await?;
|
||||
state.hub.publish_list_changed(list_id, revision).await;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn delete_item(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path((list_id, item_id)): Path<(i64, i64)>,
|
||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_access(&state, list_id).await?;
|
||||
let revision = state.db.delete_item(list_id, item_id).await?;
|
||||
state.hub.publish_list_changed(list_id, revision).await;
|
||||
list_fragment_response(&state, &user, list_id).await
|
||||
}
|
||||
|
||||
async fn create_category(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
LoggedForm(form): LoggedForm<CategoryForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
require_access(&state, list_id).await?;
|
||||
let name = form.name.trim().to_owned();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::BadRequest(
|
||||
"Category names must be between 1 and 60 characters.".into(),
|
||||
));
|
||||
}
|
||||
let revision = state.db.create_category(list_id, name).await?;
|
||||
state.hub.publish_list_changed(list_id, revision).await;
|
||||
|
||||
let access = require_access(&state, list_id).await?;
|
||||
let items = state.db.items(list_id).await?;
|
||||
let categories = state.db.categories(list_id).await?;
|
||||
Ok(html_response(views::category_created(
|
||||
&access,
|
||||
&items,
|
||||
&categories,
|
||||
&user.session.csrf_token,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn create_invitation(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
let token = db::new_secret();
|
||||
state
|
||||
.db
|
||||
.create_invitation(user.session.user.id, token.clone())
|
||||
.await?;
|
||||
let url = format!(
|
||||
"{}/invite/{token}",
|
||||
state.public_base_url.trim_end_matches('/')
|
||||
);
|
||||
Ok(html_response(views::invite_result(&url)))
|
||||
}
|
||||
|
||||
async fn invitation_page(
|
||||
State(state): State<AppState>,
|
||||
Path(token): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, AppError> {
|
||||
let info = state.db.invitation(token.clone()).await?;
|
||||
if !info {
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
let user = optional_user(&state, &headers).await?;
|
||||
Ok(html_response(views::invite_page(
|
||||
user.as_ref().map(|current| ¤t.session.user),
|
||||
&token,
|
||||
None,
|
||||
user.as_ref()
|
||||
.map(|current| current.session.csrf_token.as_str()),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn accept_invitation(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(token): Path<String>,
|
||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
verify_csrf(&user, &form.csrf)?;
|
||||
state.db.accept_invitation(token).await?;
|
||||
Ok(Redirect::to("/lists").into_response())
|
||||
}
|
||||
|
||||
async fn list_stream(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(list_id): Path<i64>,
|
||||
websocket: WebSocketUpgrade,
|
||||
) -> Result<Response, AppError> {
|
||||
require_access(&state, list_id).await?;
|
||||
let state_for_socket = state.clone();
|
||||
let user_for_socket = user.clone();
|
||||
Ok(websocket
|
||||
.on_upgrade(move |socket| handle_socket(state_for_socket, user_for_socket, list_id, socket))
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn handle_socket(state: AppState, user: CurrentUser, list_id: i64, socket: WebSocket) {
|
||||
let subscription = state
|
||||
.hub
|
||||
.join(
|
||||
list_id,
|
||||
user.session.user.id,
|
||||
user.session.user.display_name.clone(),
|
||||
)
|
||||
.await;
|
||||
let connection_id = subscription.connection_id.clone();
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
let mut heartbeat = tokio::time::interval(Duration::from_secs(30));
|
||||
heartbeat.tick().await;
|
||||
|
||||
match websocket_snapshot(&state, &user, list_id, &subscription.presence).await {
|
||||
Ok(snapshot) => {
|
||||
if sender.send(Message::Text(snapshot.into())).await.is_err() {
|
||||
state.hub.leave(list_id, &connection_id).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!(%error, "could not render websocket snapshot");
|
||||
state.hub.leave(list_id, &connection_id).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let mut events = subscription.receiver;
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = events.recv() => {
|
||||
match event {
|
||||
Ok(HubEvent::ListChanged { list_id: event_list_id, revision }) if event_list_id == list_id => {
|
||||
tracing::debug!(%list_id, revision, "list changed on websocket");
|
||||
match websocket_list_update(&state, &user, list_id).await {
|
||||
Ok(update) => {
|
||||
if sender.send(Message::Text(update.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!(%error, "could not render websocket list update");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(HubEvent::PresenceChanged { list_id: event_list_id }) if event_list_id == list_id => {
|
||||
let presence = state.hub.presence(list_id).await;
|
||||
let update = views::presence_panel(&presence, true).into_string();
|
||||
if sender.send(Message::Text(update.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
match websocket_snapshot(&state, &user, list_id, &state.hub.presence(list_id).await).await {
|
||||
Ok(snapshot) => {
|
||||
if sender.send(Message::Text(snapshot.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
error!(%error, "could not resync websocket");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
if sender.send(Message::Ping(Vec::new().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
incoming = receiver.next() => {
|
||||
match incoming {
|
||||
Some(Ok(Message::Ping(payload))) => {
|
||||
if sender.send(Message::Pong(payload)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(Ok(Message::Close(_))) | None => break,
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(_)) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
state.hub.leave(list_id, &connection_id).await;
|
||||
}
|
||||
|
||||
async fn websocket_snapshot(
|
||||
state: &AppState,
|
||||
user: &CurrentUser,
|
||||
list_id: i64,
|
||||
presence: &[hub::PresenceUser],
|
||||
) -> Result<String, AppError> {
|
||||
let access = require_access(state, list_id).await?;
|
||||
let items = state.db.items(list_id).await?;
|
||||
let categories = state.db.categories(list_id).await?;
|
||||
Ok(
|
||||
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token)
|
||||
.into_string()
|
||||
+ &views::presence_panel(presence, true).into_string(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn websocket_list_update(
|
||||
state: &AppState,
|
||||
user: &CurrentUser,
|
||||
list_id: i64,
|
||||
) -> Result<String, AppError> {
|
||||
let access = require_access(state, list_id).await?;
|
||||
let items = state.db.items(list_id).await?;
|
||||
let categories = state.db.categories(list_id).await?;
|
||||
Ok(
|
||||
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token)
|
||||
.into_string(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_fragment_response(
|
||||
state: &AppState,
|
||||
user: &CurrentUser,
|
||||
list_id: i64,
|
||||
) -> Result<Response, AppError> {
|
||||
let access = require_access(state, list_id).await?;
|
||||
let items = state.db.items(list_id).await?;
|
||||
let categories = state.db.categories(list_id).await?;
|
||||
Ok(html_response(views::list_items_fragment(
|
||||
&access,
|
||||
&items,
|
||||
&categories,
|
||||
&user.session.csrf_token,
|
||||
false,
|
||||
)))
|
||||
}
|
||||
|
||||
async fn require_access(state: &AppState, list_id: i64) -> Result<db::GroceryList, AppError> {
|
||||
state
|
||||
.db
|
||||
.list_access(list_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)
|
||||
}
|
||||
|
||||
async fn optional_user(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<Option<CurrentUser>, AppError> {
|
||||
let Some(session_token) = cookie_value(headers, "session") else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(state
|
||||
.db
|
||||
.session_user(session_token.clone())
|
||||
.await?
|
||||
.map(|session| CurrentUser {
|
||||
session_token,
|
||||
session,
|
||||
}))
|
||||
}
|
||||
|
||||
fn verify_csrf(user: &CurrentUser, token: &str) -> Result<(), AppError> {
|
||||
if token.is_empty() || token != user.session.csrf_token {
|
||||
return Err(AppError::BadRequest(
|
||||
"Your form has expired. Refresh and try again.".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_category_id(category_id: Option<String>) -> Option<i64> {
|
||||
category_id
|
||||
.filter(|category_id| !category_id.trim().is_empty())
|
||||
.and_then(|category_id| category_id.trim().parse().ok())
|
||||
}
|
||||
|
||||
async fn can_register(state: &AppState, invite: Option<&str>) -> Result<bool, AppError> {
|
||||
if state.registration_mode == RegistrationMode::Open {
|
||||
return Ok(true);
|
||||
}
|
||||
if !state.db.has_users().await? {
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(invite) = invite.filter(|invite| !invite.is_empty()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(state.db.invitation(invite.to_owned()).await?)
|
||||
}
|
||||
|
||||
fn hash_password(password: &str) -> Result<String, String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|hash| hash.to_string())
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn verify_password(password: &str, encoded_hash: &str) -> Result<bool, String> {
|
||||
let hash = PasswordHash::new(encoded_hash).map_err(|error| error.to_string())?;
|
||||
Ok(Argon2::default()
|
||||
.verify_password(password.as_bytes(), &hash)
|
||||
.is_ok())
|
||||
}
|
||||
|
||||
fn html_response(markup: maud::Markup) -> Response {
|
||||
Html(markup.into_string()).into_response()
|
||||
}
|
||||
|
||||
fn status_html_response(status: StatusCode, markup: maud::Markup) -> Response {
|
||||
(status, Html(markup.into_string())).into_response()
|
||||
}
|
||||
|
||||
fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(header::COOKIE)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.split(';')
|
||||
.map(str::trim)
|
||||
.find_map(|cookie| {
|
||||
let (key, value) = cookie.split_once('=')?;
|
||||
(key == name).then(|| value.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
fn set_session_cookie(response: &mut Response, token: &str, secure: bool) {
|
||||
let secure_attribute = if secure { "; Secure" } else { "" };
|
||||
let cookie = format!(
|
||||
"session={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000{secure_attribute}"
|
||||
);
|
||||
response.headers_mut().append(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie).expect("session cookie is valid"),
|
||||
);
|
||||
}
|
||||
|
||||
fn clear_session_cookie(response: &mut Response, secure: bool) {
|
||||
let secure_attribute = if secure { "; Secure" } else { "" };
|
||||
let cookie = format!("session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0{secure_attribute}");
|
||||
response.headers_mut().append(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie).expect("session cookie is valid"),
|
||||
);
|
||||
}
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
use async_trait::async_trait;
|
||||
use sqlx::SqliteConnection;
|
||||
|
||||
use crate::domain::{Category, DomainResult, GroceryList, Item, PresenceUser, SessionUser, User};
|
||||
|
||||
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
||||
/// so several repositories can commit together atomically within a single
|
||||
/// transaction coordinated by the unit of work.
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserRepository: Send + Sync {
|
||||
async fn create_user(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
email: String,
|
||||
display_name: String,
|
||||
password_hash: String,
|
||||
) -> DomainResult<User>;
|
||||
async fn find_user_by_email(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
email: String,
|
||||
) -> DomainResult<Option<(User, String)>>;
|
||||
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait SessionRepository: Send + Sync {
|
||||
async fn create_session(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
user_id: i64,
|
||||
) -> DomainResult<(String, String)>;
|
||||
async fn session_user(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
session_token: String,
|
||||
) -> DomainResult<Option<SessionUser>>;
|
||||
async fn delete_session(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
session_token: String,
|
||||
) -> DomainResult<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ListRepository: Send + Sync {
|
||||
async fn list_summaries(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<GroceryList>>;
|
||||
async fn create_list(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
name: String,
|
||||
) -> DomainResult<GroceryList>;
|
||||
async fn get_list(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
) -> DomainResult<Option<GroceryList>>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait CategoryRepository: Send + Sync {
|
||||
async fn categories(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
) -> DomainResult<Vec<Category>>;
|
||||
async fn create_category(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
name: String,
|
||||
) -> DomainResult<i64>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ItemRepository: Send + Sync {
|
||||
async fn items(&self, txn: &mut SqliteConnection, list_id: i64) -> DomainResult<Vec<Item>>;
|
||||
async fn add_item(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<i64>,
|
||||
) -> DomainResult<i64>;
|
||||
async fn set_item_checked(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
checked: bool,
|
||||
) -> DomainResult<i64>;
|
||||
async fn update_item(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<i64>,
|
||||
) -> DomainResult<i64>;
|
||||
async fn delete_item(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
) -> DomainResult<i64>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait InvitationRepository: Send + Sync {
|
||||
async fn create_invitation(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
created_by: i64,
|
||||
token: String,
|
||||
) -> DomainResult<i64>;
|
||||
async fn invitation(&self, txn: &mut SqliteConnection, token: String) -> DomainResult<bool>;
|
||||
async fn accept_invitation(
|
||||
&self,
|
||||
txn: &mut SqliteConnection,
|
||||
token: String,
|
||||
) -> DomainResult<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait PasswordHasher: Send + Sync {
|
||||
fn hash(&self, password: &str) -> Result<String, String>;
|
||||
fn verify(&self, password: &str, encoded_hash: &str) -> Result<bool, String>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait TokenGenerator: Send + Sync {
|
||||
fn generate(&self) -> String;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait RealtimeNotifier: Send + Sync {
|
||||
async fn join(&self, list_id: i64, user_id: i64, display_name: String) -> Subscription;
|
||||
async fn leave(&self, list_id: i64, connection_id: &str);
|
||||
async fn publish_list_changed(&self, list_id: i64, revision: i64);
|
||||
async fn presence(&self, list_id: i64) -> Vec<PresenceUser>;
|
||||
}
|
||||
|
||||
pub struct Subscription {
|
||||
pub connection_id: String,
|
||||
pub receiver: tokio::sync::broadcast::Receiver<HubEvent>,
|
||||
pub presence: Vec<PresenceUser>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum HubEvent {
|
||||
ListChanged { list_id: i64, revision: i64 },
|
||||
PresenceChanged { list_id: i64 },
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use argon2::{
|
||||
Argon2,
|
||||
password_hash::{
|
||||
PasswordHash, PasswordHasher as Argon2Hasher, PasswordVerifier, SaltString,
|
||||
rand_core::OsRng,
|
||||
},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use rand::RngCore;
|
||||
|
||||
use crate::ports::{PasswordHasher, TokenGenerator};
|
||||
|
||||
pub struct Argon2PasswordHasher;
|
||||
|
||||
#[async_trait]
|
||||
impl PasswordHasher for Argon2PasswordHasher {
|
||||
fn hash(&self, password: &str) -> Result<String, String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|hash| hash.to_string())
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn verify(&self, password: &str, encoded_hash: &str) -> Result<bool, String> {
|
||||
let hash = PasswordHash::new(encoded_hash).map_err(|error| error.to_string())?;
|
||||
Ok(Argon2::default()
|
||||
.verify_password(password.as_bytes(), &hash)
|
||||
.is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RandomTokenGenerator;
|
||||
|
||||
#[async_trait]
|
||||
impl TokenGenerator for RandomTokenGenerator {
|
||||
fn generate(&self) -> String {
|
||||
new_secret()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_secret() -> String {
|
||||
let mut bytes = [0_u8; 32];
|
||||
OsRng.fill_bytes(&mut bytes);
|
||||
hex::encode(bytes)
|
||||
}
|
||||
+35
-9
@@ -1,9 +1,11 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Deserialize;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::db::Database;
|
||||
use crate::ports::{PasswordHasher, UserRepository};
|
||||
use crate::sqlite::SqliteDatabase;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SeedConfig {
|
||||
@@ -21,7 +23,12 @@ pub struct SeedUser {
|
||||
/// Reads the seed config file and creates the configured default user if the
|
||||
/// database has no users yet. The file is optional; if it does not exist (or
|
||||
/// cannot be parsed) seeding is skipped.
|
||||
pub async fn seed_if_needed(db: &Database, path: &Path) {
|
||||
pub async fn seed_if_needed(
|
||||
db: &SqliteDatabase,
|
||||
users: &Arc<dyn UserRepository>,
|
||||
hasher: &Arc<dyn PasswordHasher>,
|
||||
path: &Path,
|
||||
) {
|
||||
let Ok(contents) = std::fs::read_to_string(path) else {
|
||||
return;
|
||||
};
|
||||
@@ -39,23 +46,42 @@ pub async fn seed_if_needed(db: &Database, path: &Path) {
|
||||
warn!("seed user requires a non-empty email; skipping");
|
||||
return;
|
||||
}
|
||||
if db.has_users().await.unwrap_or(true) {
|
||||
let users_for_check = users.clone();
|
||||
let has_users = match db
|
||||
.run(move |txn| Box::pin(async move { users_for_check.has_users(txn).await }))
|
||||
.await
|
||||
{
|
||||
Ok(has_users) => has_users,
|
||||
Err(error) => {
|
||||
warn!(%error, "could not check for existing users; skipping seed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if has_users {
|
||||
info!("database already has users; skipping seed");
|
||||
return;
|
||||
}
|
||||
let password_hash = match crate::hash_password(&user.password) {
|
||||
let password_hash = match hasher.hash(&user.password) {
|
||||
Ok(hash) => hash,
|
||||
Err(error) => {
|
||||
warn!(%error, "could not hash seed password; skipping");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let users_for_create = users.clone();
|
||||
match db
|
||||
.create_user(
|
||||
user.email.trim().to_lowercase(),
|
||||
user.display_name.trim().to_owned(),
|
||||
password_hash,
|
||||
)
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
users_for_create
|
||||
.create_user(
|
||||
txn,
|
||||
user.email.trim().to_lowercase(),
|
||||
user.display_name.trim().to_owned(),
|
||||
password_hash,
|
||||
)
|
||||
.await
|
||||
})
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(user) => info!(id = user.id, email = %user.email, "seeded default user"),
|
||||
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::domain::{DomainError, DomainResult, GroceryList, Item, SessionUser, User};
|
||||
use crate::ports::{
|
||||
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, PasswordHasher,
|
||||
RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
|
||||
};
|
||||
use crate::sqlite::SqliteDatabase;
|
||||
|
||||
pub struct AuthService {
|
||||
db: SqliteDatabase,
|
||||
users: Arc<dyn UserRepository>,
|
||||
sessions: Arc<dyn SessionRepository>,
|
||||
invitations: Arc<dyn InvitationRepository>,
|
||||
hasher: Arc<dyn PasswordHasher>,
|
||||
registration_mode: RegistrationMode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RegistrationMode {
|
||||
Open,
|
||||
InviteOnly,
|
||||
}
|
||||
|
||||
impl AuthService {
|
||||
pub fn new(
|
||||
db: SqliteDatabase,
|
||||
users: Arc<dyn UserRepository>,
|
||||
sessions: Arc<dyn SessionRepository>,
|
||||
invitations: Arc<dyn InvitationRepository>,
|
||||
hasher: Arc<dyn PasswordHasher>,
|
||||
registration_mode: RegistrationMode,
|
||||
) -> Self {
|
||||
Self {
|
||||
db,
|
||||
users,
|
||||
sessions,
|
||||
invitations,
|
||||
hasher,
|
||||
registration_mode,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn can_register(&self, invite: Option<&str>) -> DomainResult<bool> {
|
||||
if self.registration_mode == RegistrationMode::Open {
|
||||
return Ok(true);
|
||||
}
|
||||
let users = Arc::clone(&self.users);
|
||||
let invitations = Arc::clone(&self.invitations);
|
||||
let invite = invite.map(str::to_owned);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
if !users.has_users(txn).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(invite) = invite.filter(|invite| !invite.is_empty()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
invitations.invitation(txn, invite).await
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
&self,
|
||||
display_name: String,
|
||||
email: String,
|
||||
password: String,
|
||||
invite: Option<&str>,
|
||||
) -> DomainResult<(User, String)> {
|
||||
if !self.can_register(invite).await? {
|
||||
return Err(DomainError::Conflict);
|
||||
}
|
||||
let password_hash = self.hasher.hash(&password).map_err(DomainError::Database)?;
|
||||
let users = Arc::clone(&self.users);
|
||||
let sessions = Arc::clone(&self.sessions);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
let user = users
|
||||
.create_user(txn, email, display_name, password_hash)
|
||||
.await?;
|
||||
let (session_token, _) = sessions.create_session(txn, user.id).await?;
|
||||
Ok((user, session_token))
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
&self,
|
||||
email: String,
|
||||
password: String,
|
||||
) -> DomainResult<Option<(User, String)>> {
|
||||
let users = Arc::clone(&self.users);
|
||||
let sessions = Arc::clone(&self.sessions);
|
||||
let hasher = Arc::clone(&self.hasher);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
let Some((user, password_hash)) = users.find_user_by_email(txn, email).await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let valid = hasher
|
||||
.verify(&password, &password_hash)
|
||||
.map_err(DomainError::Database)?;
|
||||
if !valid {
|
||||
return Ok(None);
|
||||
}
|
||||
let (session_token, _) = sessions.create_session(txn, user.id).await?;
|
||||
Ok(Some((user, session_token)))
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn session_user(&self, session_token: String) -> DomainResult<Option<SessionUser>> {
|
||||
let sessions = Arc::clone(&self.sessions);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move { sessions.session_user(txn, session_token).await })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn logout(&self, session_token: String) -> DomainResult<()> {
|
||||
let sessions = Arc::clone(&self.sessions);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move { sessions.delete_session(txn, session_token).await })
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ListService {
|
||||
db: SqliteDatabase,
|
||||
lists: Arc<dyn ListRepository>,
|
||||
categories: Arc<dyn CategoryRepository>,
|
||||
items: Arc<dyn ItemRepository>,
|
||||
realtime: Arc<dyn RealtimeNotifier>,
|
||||
}
|
||||
|
||||
impl ListService {
|
||||
pub fn new(
|
||||
db: SqliteDatabase,
|
||||
lists: Arc<dyn ListRepository>,
|
||||
categories: Arc<dyn CategoryRepository>,
|
||||
items: Arc<dyn ItemRepository>,
|
||||
realtime: Arc<dyn RealtimeNotifier>,
|
||||
) -> Self {
|
||||
Self {
|
||||
db,
|
||||
lists,
|
||||
categories,
|
||||
items,
|
||||
realtime,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_summaries(&self) -> DomainResult<Vec<GroceryList>> {
|
||||
let lists = Arc::clone(&self.lists);
|
||||
self.db
|
||||
.run(move |txn| Box::pin(async move { lists.list_summaries(txn).await }))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_list(&self, name: String) -> DomainResult<GroceryList> {
|
||||
let lists = Arc::clone(&self.lists);
|
||||
self.db
|
||||
.run(move |txn| Box::pin(async move { lists.create_list(txn, name).await }))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_list(&self, list_id: i64) -> DomainResult<Option<GroceryList>> {
|
||||
let lists = Arc::clone(&self.lists);
|
||||
self.db
|
||||
.run(move |txn| Box::pin(async move { lists.get_list(txn, list_id).await }))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn items(&self, list_id: i64) -> DomainResult<Vec<Item>> {
|
||||
let items = Arc::clone(&self.items);
|
||||
self.db
|
||||
.run(move |txn| Box::pin(async move { items.items(txn, list_id).await }))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn categories(&self, list_id: i64) -> DomainResult<Vec<crate::domain::Category>> {
|
||||
let categories = Arc::clone(&self.categories);
|
||||
self.db
|
||||
.run(move |txn| Box::pin(async move { categories.categories(txn, list_id).await }))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn add_item(
|
||||
&self,
|
||||
list_id: i64,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<i64>,
|
||||
) -> DomainResult<i64> {
|
||||
let items = Arc::clone(&self.items);
|
||||
let revision = self
|
||||
.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
items
|
||||
.add_item(txn, list_id, name, quantity, note, category_id)
|
||||
.await
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
self.realtime.publish_list_changed(list_id, revision).await;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
pub async fn set_item_checked(
|
||||
&self,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
checked: bool,
|
||||
) -> DomainResult<i64> {
|
||||
let items = Arc::clone(&self.items);
|
||||
let revision = self
|
||||
.db
|
||||
.run(move |txn| {
|
||||
Box::pin(
|
||||
async move { items.set_item_checked(txn, list_id, item_id, checked).await },
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
self.realtime.publish_list_changed(list_id, revision).await;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
pub async fn update_item(
|
||||
&self,
|
||||
list_id: i64,
|
||||
item_id: i64,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<i64>,
|
||||
) -> DomainResult<i64> {
|
||||
let items = Arc::clone(&self.items);
|
||||
let revision = self
|
||||
.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
items
|
||||
.update_item(txn, list_id, item_id, name, quantity, note, category_id)
|
||||
.await
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
self.realtime.publish_list_changed(list_id, revision).await;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
pub async fn delete_item(&self, list_id: i64, item_id: i64) -> DomainResult<i64> {
|
||||
let items = Arc::clone(&self.items);
|
||||
let revision = self
|
||||
.db
|
||||
.run(move |txn| Box::pin(async move { items.delete_item(txn, list_id, item_id).await }))
|
||||
.await?;
|
||||
self.realtime.publish_list_changed(list_id, revision).await;
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
pub async fn create_category(&self, list_id: i64, name: String) -> DomainResult<i64> {
|
||||
let categories = Arc::clone(&self.categories);
|
||||
let revision = self
|
||||
.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move { categories.create_category(txn, list_id, name).await })
|
||||
})
|
||||
.await?;
|
||||
self.realtime.publish_list_changed(list_id, revision).await;
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InvitationService {
|
||||
db: SqliteDatabase,
|
||||
invitations: Arc<dyn InvitationRepository>,
|
||||
tokens: Arc<dyn TokenGenerator>,
|
||||
}
|
||||
|
||||
impl InvitationService {
|
||||
pub fn new(
|
||||
db: SqliteDatabase,
|
||||
invitations: Arc<dyn InvitationRepository>,
|
||||
tokens: Arc<dyn TokenGenerator>,
|
||||
) -> Self {
|
||||
Self {
|
||||
db,
|
||||
invitations,
|
||||
tokens,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_invitation(&self, created_by: i64) -> DomainResult<String> {
|
||||
let token = self.tokens.generate();
|
||||
let invitations = Arc::clone(&self.invitations);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move {
|
||||
invitations
|
||||
.create_invitation(txn, created_by, token.clone())
|
||||
.await?;
|
||||
Ok(token)
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn invitation(&self, token: String) -> DomainResult<bool> {
|
||||
let invitations = Arc::clone(&self.invitations);
|
||||
self.db
|
||||
.run(move |txn| Box::pin(async move { invitations.invitation(txn, token).await }))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn accept_invitation(&self, token: String) -> DomainResult<()> {
|
||||
let invitations = Arc::clone(&self.invitations);
|
||||
self.db
|
||||
.run(move |txn| {
|
||||
Box::pin(async move { invitations.accept_invitation(txn, token).await })
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
+1388
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -1,8 +1,8 @@
|
||||
use maud::{DOCTYPE, Markup, html};
|
||||
|
||||
use crate::{
|
||||
db::{Category, GroceryList, Item, User},
|
||||
hub::PresenceUser,
|
||||
domain::PresenceUser,
|
||||
domain::{Category, GroceryList, Item, User},
|
||||
};
|
||||
|
||||
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
|
||||
|
||||
Reference in New Issue
Block a user