Compare commits
No commits in common. "visions-game-management" and "main" have entirely different histories.
visions-ga
...
main
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -5377,7 +5377,6 @@ dependencies = [
|
|||||||
"authdb",
|
"authdb",
|
||||||
"axum",
|
"axum",
|
||||||
"axum-test",
|
"axum-test",
|
||||||
"chrono",
|
|
||||||
"cool_asserts",
|
"cool_asserts",
|
||||||
"futures",
|
"futures",
|
||||||
"include_dir",
|
"include_dir",
|
||||||
|
@ -156,13 +156,6 @@ pub fn fatal<A, E: Error, FE: FatalError>(err: FE) -> ResultExt<A, E, FE> {
|
|||||||
ResultExt::Fatal(err)
|
ResultExt::Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn result_as_fatal<A, E: Error, FE: FatalError>(result: Result<A, FE>) -> ResultExt<A, E, FE> {
|
|
||||||
match result {
|
|
||||||
Ok(a) => ResultExt::Ok(a),
|
|
||||||
Err(err) => ResultExt::Fatal(err),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Return early from the current function if the value is a fatal error.
|
/// Return early from the current function if the value is a fatal error.
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! return_fatal {
|
macro_rules! return_fatal {
|
||||||
|
@ -10,7 +10,6 @@ async-std = { version = "1.13.0" }
|
|||||||
async-trait = { version = "0.1.83" }
|
async-trait = { version = "0.1.83" }
|
||||||
authdb = { path = "../../authdb/" }
|
authdb = { path = "../../authdb/" }
|
||||||
axum = { version = "0.7.9", features = [ "macros" ] }
|
axum = { version = "0.7.9", features = [ "macros" ] }
|
||||||
chrono = { version = "0.4.39", features = ["serde"] }
|
|
||||||
futures = { version = "0.3.31" }
|
futures = { version = "0.3.31" }
|
||||||
include_dir = { version = "0.7.4" }
|
include_dir = { version = "0.7.4" }
|
||||||
lazy_static = { version = "1.5.0" }
|
lazy_static = { version = "1.5.0" }
|
||||||
|
@ -3,7 +3,7 @@ version: '3'
|
|||||||
tasks:
|
tasks:
|
||||||
build:
|
build:
|
||||||
cmds:
|
cmds:
|
||||||
- cargo watch -x build
|
- cargo build
|
||||||
|
|
||||||
test:
|
test:
|
||||||
cmds:
|
cmds:
|
||||||
|
@ -3,7 +3,7 @@ CREATE TABLE users(
|
|||||||
name TEXT UNIQUE,
|
name TEXT UNIQUE,
|
||||||
password TEXT,
|
password TEXT,
|
||||||
admin BOOLEAN,
|
admin BOOLEAN,
|
||||||
state TEXT
|
enabled BOOLEAN
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE sessions(
|
CREATE TABLE sessions(
|
||||||
@ -14,9 +14,9 @@ CREATE TABLE sessions(
|
|||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE games(
|
CREATE TABLE games(
|
||||||
id TEXT PRIMARY KEY,
|
uuid TEXT PRIMARY KEY,
|
||||||
type_ TEXT,
|
|
||||||
gm TEXT,
|
gm TEXT,
|
||||||
|
game_type TEXT,
|
||||||
name TEXT,
|
name TEXT,
|
||||||
|
|
||||||
FOREIGN KEY(gm) REFERENCES users(uuid)
|
FOREIGN KEY(gm) REFERENCES users(uuid)
|
||||||
@ -39,3 +39,4 @@ CREATE TABLE roles(
|
|||||||
FOREIGN KEY(game_id) REFERENCES games(uuid)
|
FOREIGN KEY(game_id) REFERENCES games(uuid)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
INSERT INTO users VALUES ('admin', 'admin', '', true, true);
|
||||||
|
@ -1,19 +1,16 @@
|
|||||||
use std::{collections::HashMap, sync::Arc};
|
use std::{collections::HashMap, sync::Arc};
|
||||||
|
|
||||||
use async_std::sync::RwLock;
|
use async_std::sync::RwLock;
|
||||||
use chrono::{DateTime, TimeDelta, Utc};
|
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
use result_extended::{error, fatal, ok, result_as_fatal, return_error, ResultExt};
|
use result_extended::{error, fatal, ok, return_error, ResultExt};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::Serialize;
|
||||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
||||||
use typeshare::typeshare;
|
use typeshare::typeshare;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
asset_db::{self, AssetId, Assets},
|
asset_db::{self, AssetId, Assets},
|
||||||
database::{CharacterId, Database, GameId, SessionId, UserId},
|
database::{CharacterId, Database, GameId, SessionId, UserId}, types::{AppError, FatalError, GameOverview, Message, Rgb, Tabletop, User, UserProfile},
|
||||||
types::AccountState,
|
|
||||||
types::{AppError, FatalError, GameOverview, Message, Rgb, Tabletop, User, UserOverview},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_BACKGROUND_COLOR: Rgb = Rgb {
|
const DEFAULT_BACKGROUND_COLOR: Rgb = Rgb {
|
||||||
@ -25,16 +22,7 @@ const DEFAULT_BACKGROUND_COLOR: Rgb = Rgb {
|
|||||||
#[derive(Clone, Serialize)]
|
#[derive(Clone, Serialize)]
|
||||||
#[typeshare]
|
#[typeshare]
|
||||||
pub struct Status {
|
pub struct Status {
|
||||||
pub ok: bool,
|
pub admin_enabled: bool,
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
||||||
#[serde(tag = "type", content = "content")]
|
|
||||||
#[typeshare]
|
|
||||||
pub enum AuthResponse {
|
|
||||||
Success(SessionId),
|
|
||||||
PasswordReset(SessionId),
|
|
||||||
Locked,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -71,7 +59,6 @@ impl Core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn status(&self) -> ResultExt<Status, AppError, FatalError> {
|
pub async fn status(&self) -> ResultExt<Status, AppError, FatalError> {
|
||||||
/*
|
|
||||||
let state = self.0.write().await;
|
let state = self.0.write().await;
|
||||||
let admin_user = return_error!(match state.db.user(&UserId::from("admin")).await {
|
let admin_user = return_error!(match state.db.user(&UserId::from("admin")).await {
|
||||||
Ok(Some(admin_user)) => ok(admin_user),
|
Ok(Some(admin_user)) => ok(admin_user),
|
||||||
@ -84,10 +71,8 @@ impl Core {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ok(Status {
|
ok(Status {
|
||||||
ok: !admin_user.password.is_empty(),
|
admin_enabled: !admin_user.password.is_empty(),
|
||||||
})
|
})
|
||||||
*/
|
|
||||||
ok(Status { ok: true })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn register_client(&self) -> String {
|
pub async fn register_client(&self) -> String {
|
||||||
@ -132,34 +117,27 @@ impl Core {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_users(&self) -> ResultExt<Vec<UserOverview>, AppError, FatalError> {
|
pub async fn list_users(&self) -> ResultExt<Vec<User>, AppError, FatalError> {
|
||||||
let users = self.0.write().await.db.users().await;
|
let users = self.0.write().await.db.users().await;
|
||||||
match users {
|
match users {
|
||||||
Ok(users) => ok(users
|
Ok(users) => ok(users.into_iter().map(User::from).collect()),
|
||||||
.into_iter()
|
|
||||||
.map(|user| UserOverview {
|
|
||||||
id: user.id,
|
|
||||||
name: user.name,
|
|
||||||
is_admin: user.admin,
|
|
||||||
})
|
|
||||||
.collect()),
|
|
||||||
Err(err) => fatal(err),
|
Err(err) => fatal(err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn user(
|
pub async fn user(&self, user_id: UserId) -> ResultExt<Option<UserProfile>, AppError, FatalError> {
|
||||||
&self,
|
|
||||||
user_id: UserId,
|
|
||||||
) -> ResultExt<Option<UserOverview>, AppError, FatalError> {
|
|
||||||
let users = return_error!(self.list_users().await);
|
let users = return_error!(self.list_users().await);
|
||||||
|
let games = return_error!(self.list_games().await);
|
||||||
let user = match users.into_iter().find(|user| user.id == user_id) {
|
let user = match users.into_iter().find(|user| user.id == user_id) {
|
||||||
Some(user) => user,
|
Some(user) => user,
|
||||||
None => return ok(None),
|
None => return ok(None),
|
||||||
};
|
};
|
||||||
ok(Some(UserOverview {
|
let user_games = games.into_iter().filter(|g| g.gm == user.id).collect();
|
||||||
id: user.id.clone(),
|
ok(Some(UserProfile {
|
||||||
|
id: user.id,
|
||||||
name: user.name,
|
name: user.name,
|
||||||
is_admin: user.is_admin,
|
games: user_games,
|
||||||
|
is_admin: user.admin,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -167,47 +145,25 @@ impl Core {
|
|||||||
let state = self.0.read().await;
|
let state = self.0.read().await;
|
||||||
match return_error!(self.user_by_username(username).await) {
|
match return_error!(self.user_by_username(username).await) {
|
||||||
Some(_) => error(AppError::UsernameUnavailable),
|
Some(_) => error(AppError::UsernameUnavailable),
|
||||||
None => match state
|
None => match state.db.save_user(None, username, "", false, true).await {
|
||||||
.db
|
|
||||||
.create_user(username, "", false, AccountState::PasswordReset(Utc::now()))
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(user_id) => ok(user_id),
|
Ok(user_id) => ok(user_id),
|
||||||
Err(err) => fatal(err),
|
Err(err) => fatal(err),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn disable_user(&self, _userid: UserId) -> ResultExt<(), AppError, FatalError> {
|
|
||||||
unimplemented!();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_games(&self) -> ResultExt<Vec<GameOverview>, AppError, FatalError> {
|
pub async fn list_games(&self) -> ResultExt<Vec<GameOverview>, AppError, FatalError> {
|
||||||
let games = self.0.read().await.db.games().await;
|
let games = self.0.read().await.db.games().await;
|
||||||
match games {
|
match games {
|
||||||
// Ok(games) => ok(games.into_iter().map(|g| Game::from(g)).collect()),
|
// Ok(games) => ok(games.into_iter().map(|g| Game::from(g)).collect()),
|
||||||
Ok(games) => ok(games
|
Ok(games) => ok(games.into_iter().map(GameOverview::from).collect()),
|
||||||
.into_iter()
|
|
||||||
.map(|game| GameOverview {
|
|
||||||
id: game.id,
|
|
||||||
type_: "".to_owned(),
|
|
||||||
name: game.name,
|
|
||||||
gm: game.gm,
|
|
||||||
players: game.players,
|
|
||||||
})
|
|
||||||
.collect::<Vec<GameOverview>>()),
|
|
||||||
Err(err) => fatal(err),
|
Err(err) => fatal(err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create_game(
|
pub async fn create_game(&self, gm: &UserId, game_type: &str, game_name: &str) -> ResultExt<GameId, AppError, FatalError> {
|
||||||
&self,
|
|
||||||
gm: &UserId,
|
|
||||||
game_type: &str,
|
|
||||||
game_name: &str,
|
|
||||||
) -> ResultExt<GameId, AppError, FatalError> {
|
|
||||||
let state = self.0.read().await;
|
let state = self.0.read().await;
|
||||||
match state.db.create_game(gm, game_type, game_name).await {
|
match state.db.save_game(None, gm, game_type, game_name).await {
|
||||||
Ok(game_id) => ok(game_id),
|
Ok(game_id) => ok(game_id),
|
||||||
Err(err) => fatal(err),
|
Err(err) => fatal(err),
|
||||||
}
|
}
|
||||||
@ -290,22 +246,16 @@ impl Core {
|
|||||||
|
|
||||||
pub async fn save_user(
|
pub async fn save_user(
|
||||||
&self,
|
&self,
|
||||||
id: UserId,
|
uuid: Option<UserId>,
|
||||||
name: &str,
|
username: &str,
|
||||||
password: &str,
|
password: &str,
|
||||||
admin: bool,
|
admin: bool,
|
||||||
account_state: AccountState,
|
enabled: bool,
|
||||||
) -> ResultExt<UserId, AppError, FatalError> {
|
) -> ResultExt<UserId, AppError, FatalError> {
|
||||||
let state = self.0.read().await;
|
let state = self.0.read().await;
|
||||||
match state
|
match state
|
||||||
.db
|
.db
|
||||||
.save_user(User {
|
.save_user(uuid, username, password, admin, enabled)
|
||||||
id,
|
|
||||||
name: name.to_owned(),
|
|
||||||
password: password.to_owned(),
|
|
||||||
admin,
|
|
||||||
state: account_state,
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(uuid) => ok(uuid),
|
Ok(uuid) => ok(uuid),
|
||||||
@ -326,11 +276,7 @@ impl Core {
|
|||||||
};
|
};
|
||||||
match state
|
match state
|
||||||
.db
|
.db
|
||||||
.save_user(User {
|
.save_user(Some(uuid), &user.name, &password, user.admin, user.enabled)
|
||||||
password,
|
|
||||||
state: AccountState::Normal,
|
|
||||||
..user
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(_) => ok(()),
|
Ok(_) => ok(()),
|
||||||
@ -342,36 +288,19 @@ impl Core {
|
|||||||
&self,
|
&self,
|
||||||
username: &str,
|
username: &str,
|
||||||
password: &str,
|
password: &str,
|
||||||
) -> ResultExt<AuthResponse, AppError, FatalError> {
|
) -> ResultExt<SessionId, AppError, FatalError> {
|
||||||
let now = Utc::now();
|
let state = self.0.write().await;
|
||||||
let state = self.0.read().await;
|
match state.db.user_by_username(username).await {
|
||||||
let user_info = return_error!(match state.db.user_by_username(username).await {
|
Ok(Some(row)) if (row.password == password) => {
|
||||||
Ok(Some(row)) if row.password == password => ok(row),
|
let session_id = state.db.create_session(&row.id).await.unwrap();
|
||||||
|
ok(session_id)
|
||||||
|
}
|
||||||
Ok(_) => error(AppError::AuthFailed),
|
Ok(_) => error(AppError::AuthFailed),
|
||||||
Err(err) => fatal(err),
|
Err(err) => fatal(err),
|
||||||
});
|
|
||||||
|
|
||||||
match user_info.state {
|
|
||||||
AccountState::Normal => result_as_fatal(state.db.create_session(&user_info.id).await)
|
|
||||||
.map(|session_id| AuthResponse::Success(session_id)),
|
|
||||||
|
|
||||||
AccountState::PasswordReset(exp) => {
|
|
||||||
if exp < now {
|
|
||||||
error(AppError::AuthFailed)
|
|
||||||
} else {
|
|
||||||
result_as_fatal(state.db.create_session(&user_info.id).await)
|
|
||||||
.map(|session_id| AuthResponse::PasswordReset(session_id))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AccountState::Locked => ok(AuthResponse::Locked),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn session(
|
pub async fn session(&self, session_id: &SessionId) -> ResultExt<Option<User>, AppError, FatalError> {
|
||||||
&self,
|
|
||||||
session_id: &SessionId,
|
|
||||||
) -> ResultExt<Option<User>, AppError, FatalError> {
|
|
||||||
let state = self.0.read().await;
|
let state = self.0.read().await;
|
||||||
match state.db.session(session_id).await {
|
match state.db.session(session_id).await {
|
||||||
Ok(Some(user_row)) => ok(Some(User::from(user_row))),
|
Ok(Some(user_row)) => ok(Some(User::from(user_row))),
|
||||||
@ -381,10 +310,6 @@ impl Core {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_expiration_date() -> DateTime<Utc> {
|
|
||||||
Utc::now() + TimeDelta::days(365)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@ -425,17 +350,12 @@ mod test {
|
|||||||
]);
|
]);
|
||||||
let memory_db: Option<PathBuf> = None;
|
let memory_db: Option<PathBuf> = None;
|
||||||
let conn = DbConn::new(memory_db);
|
let conn = DbConn::new(memory_db);
|
||||||
conn.create_user("admin", "aoeu", true, AccountState::Normal)
|
conn.save_user(Some(UserId::from("admin")), "admin", "aoeu", true, true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
conn.save_user(None, "gm_1", "aoeu", false, true)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
conn.create_user(
|
|
||||||
"gm_1",
|
|
||||||
"aoeu",
|
|
||||||
false,
|
|
||||||
AccountState::PasswordReset(Utc::now()),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
Core::new(assets, conn)
|
Core::new(assets, conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -503,7 +423,7 @@ mod test {
|
|||||||
async fn it_creates_a_sessionid_on_successful_auth() {
|
async fn it_creates_a_sessionid_on_successful_auth() {
|
||||||
let core = test_core().await;
|
let core = test_core().await;
|
||||||
match core.auth("admin", "aoeu").await {
|
match core.auth("admin", "aoeu").await {
|
||||||
ResultExt::Ok(AuthResponse::Success(session_id)) => {
|
ResultExt::Ok(session_id) => {
|
||||||
let st = core.0.read().await;
|
let st = core.0.read().await;
|
||||||
match st.db.session(&session_id).await {
|
match st.db.session(&session_id).await {
|
||||||
Ok(Some(user_row)) => assert_eq!(user_row.name, "admin"),
|
Ok(Some(user_row)) => assert_eq!(user_row.name, "admin"),
|
||||||
@ -511,8 +431,6 @@ mod test {
|
|||||||
Err(err) => panic!("{}", err),
|
Err(err) => panic!("{}", err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ResultExt::Ok(AuthResponse::PasswordReset(_)) => panic!("user is in password reset state"),
|
|
||||||
ResultExt::Ok(AuthResponse::Locked) => panic!("user has been locked"),
|
|
||||||
ResultExt::Err(err) => panic!("{}", err),
|
ResultExt::Err(err) => panic!("{}", err),
|
||||||
ResultExt::Fatal(err) => panic!("{}", err),
|
ResultExt::Fatal(err) => panic!("{}", err),
|
||||||
}
|
}
|
||||||
|
@ -8,10 +8,12 @@ use rusqlite_migration::Migrations;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{DatabaseResponse, Request},
|
database::{DatabaseResponse, Request},
|
||||||
types::{AccountState, FatalError, Game, User},
|
types::FatalError,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{types::GameId, CharacterId, CharsheetRow, DatabaseRequest, SessionId, UserId};
|
use super::{
|
||||||
|
types::GameId, CharacterId, CharsheetRow, DatabaseRequest, GameRow, SessionId, UserId, UserRow
|
||||||
|
};
|
||||||
|
|
||||||
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
|
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
|
||||||
|
|
||||||
@ -38,26 +40,28 @@ impl DiskDb {
|
|||||||
.to_latest(&mut conn)
|
.to_latest(&mut conn)
|
||||||
.map_err(|err| FatalError::DatabaseMigrationFailure(format!("{}", err)))?;
|
.map_err(|err| FatalError::DatabaseMigrationFailure(format!("{}", err)))?;
|
||||||
|
|
||||||
|
// setup_test_database(&conn)?;
|
||||||
|
|
||||||
Ok(DiskDb { conn })
|
Ok(DiskDb { conn })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user(&self, id: &UserId) -> Result<Option<User>, FatalError> {
|
pub fn user(&self, id: &UserId) -> Result<Option<UserRow>, FatalError> {
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.conn
|
||||||
.prepare("SELECT * FROM users WHERE uuid=?")
|
.prepare("SELECT uuid, name, password, admin, enabled FROM users WHERE uuid=?")
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
let items: Vec<User> = stmt
|
let items: Vec<UserRow> = stmt
|
||||||
.query_map([id.as_str()], |row| {
|
.query_map([id.as_str()], |row| {
|
||||||
Ok(User {
|
Ok(UserRow {
|
||||||
id: row.get(0).unwrap(),
|
id: row.get(0).unwrap(),
|
||||||
name: row.get(1).unwrap(),
|
name: row.get(1).unwrap(),
|
||||||
password: row.get(2).unwrap(),
|
password: row.get(2).unwrap(),
|
||||||
admin: row.get(3).unwrap(),
|
admin: row.get(3).unwrap(),
|
||||||
state: row.get(4).unwrap(),
|
enabled: row.get(4).unwrap(),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect::<Result<Vec<User>, rusqlite::Error>>()
|
.collect::<Result<Vec<UserRow>, rusqlite::Error>>()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
match &items[..] {
|
match &items[..] {
|
||||||
[] => Ok(None),
|
[] => Ok(None),
|
||||||
@ -66,23 +70,23 @@ impl DiskDb {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user_by_username(&self, username: &str) -> Result<Option<User>, FatalError> {
|
pub fn user_by_username(&self, username: &str) -> Result<Option<UserRow>, FatalError> {
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.conn
|
||||||
.prepare("SELECT * FROM users WHERE name=?")
|
.prepare("SELECT uuid, name, password, admin, enabled FROM users WHERE name=?")
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
let items: Vec<User> = stmt
|
let items: Vec<UserRow> = stmt
|
||||||
.query_map([username], |row| {
|
.query_map([username], |row| {
|
||||||
Ok(User {
|
Ok(UserRow {
|
||||||
id: row.get(0).unwrap(),
|
id: row.get(0).unwrap(),
|
||||||
name: row.get(1).unwrap(),
|
name: row.get(1).unwrap(),
|
||||||
password: row.get(2).unwrap(),
|
password: row.get(2).unwrap(),
|
||||||
admin: row.get(3).unwrap(),
|
admin: row.get(3).unwrap(),
|
||||||
state: row.get(4).unwrap(),
|
enabled: row.get(4).unwrap(),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect::<Result<Vec<User>, rusqlite::Error>>()
|
.collect::<Result<Vec<UserRow>, rusqlite::Error>>()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
match &items[..] {
|
match &items[..] {
|
||||||
[] => Ok(None),
|
[] => Ok(None),
|
||||||
@ -91,124 +95,125 @@ impl DiskDb {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_user(
|
pub fn save_user(
|
||||||
&self,
|
&self,
|
||||||
|
user_id: Option<UserId>,
|
||||||
name: &str,
|
name: &str,
|
||||||
password: &str,
|
password: &str,
|
||||||
admin: bool,
|
admin: bool,
|
||||||
state: AccountState,
|
enabled: bool,
|
||||||
) -> Result<UserId, FatalError> {
|
) -> Result<UserId, FatalError> {
|
||||||
let user_id = UserId::default();
|
match user_id {
|
||||||
let mut stmt = self
|
None => {
|
||||||
.conn
|
let user_id = UserId::default();
|
||||||
.prepare("INSERT INTO users VALUES (?, ?, ?, ?, ?)")
|
let mut stmt = self
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.conn
|
||||||
stmt.execute((user_id.as_str(), name, password, admin, state))
|
.prepare("INSERT INTO users VALUES (?, ?, ?, ?, ?)")
|
||||||
.unwrap();
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
Ok(user_id)
|
stmt.execute((user_id.as_str(), name, password, admin, enabled))
|
||||||
|
.unwrap();
|
||||||
|
Ok(user_id)
|
||||||
|
}
|
||||||
|
Some(user_id) => {
|
||||||
|
let mut stmt = self
|
||||||
|
.conn
|
||||||
|
.prepare("UPDATE users SET name=?, password=?, admin=?, enabled=? WHERE uuid=?")
|
||||||
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
|
stmt.execute((name, password, admin, enabled, user_id.as_str()))
|
||||||
|
.unwrap();
|
||||||
|
Ok(user_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save_user(&self, user: User) -> Result<UserId, FatalError> {
|
pub fn users(&self) -> Result<Vec<UserRow>, FatalError> {
|
||||||
let mut stmt = self
|
|
||||||
.conn
|
|
||||||
.prepare("UPDATE users SET name=?, password=?, admin=?, state=? WHERE uuid=?")
|
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
|
||||||
stmt.execute((
|
|
||||||
user.name,
|
|
||||||
user.password,
|
|
||||||
user.admin,
|
|
||||||
user.state,
|
|
||||||
user.id.as_str(),
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
Ok(user.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn users(&self) -> Result<Vec<User>, FatalError> {
|
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.conn
|
||||||
.prepare("SELECT * FROM users")
|
.prepare("SELECT * FROM users")
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
let items = stmt
|
let items = stmt
|
||||||
.query_map([], |row| {
|
.query_map([], |row| {
|
||||||
Ok(User {
|
Ok(UserRow {
|
||||||
id: row.get(0).unwrap(),
|
id: row.get(0).unwrap(),
|
||||||
name: row.get(1).unwrap(),
|
name: row.get(1).unwrap(),
|
||||||
password: row.get(2).unwrap(),
|
password: row.get(2).unwrap(),
|
||||||
admin: row.get(3).unwrap(),
|
admin: row.get(3).unwrap(),
|
||||||
state: row.get(4).unwrap(),
|
enabled: row.get(4).unwrap(),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect::<Result<Vec<User>, rusqlite::Error>>()
|
.collect::<Result<Vec<UserRow>, rusqlite::Error>>()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
Ok(items)
|
Ok(items)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_game(
|
pub fn save_game(
|
||||||
&self,
|
&self,
|
||||||
|
game_id: Option<GameId>,
|
||||||
gm: &UserId,
|
gm: &UserId,
|
||||||
game_type: &str,
|
game_type: &str,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<GameId, FatalError> {
|
) -> Result<GameId, FatalError> {
|
||||||
let game_id = GameId::new();
|
match game_id {
|
||||||
let mut stmt = self
|
None => {
|
||||||
.conn
|
let game_id = GameId::new();
|
||||||
.prepare("INSERT INTO games VALUES (?, ?, ?, ?)")
|
let mut stmt = self
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.conn
|
||||||
stmt.execute((game_id.as_str(), game_type, gm.as_str(), name))
|
.prepare("INSERT INTO games VALUES (?, ?, ?, ?)")
|
||||||
.unwrap();
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
Ok(game_id)
|
stmt.execute((game_id.as_str(), gm.as_str(), game_type, name))
|
||||||
|
.unwrap();
|
||||||
|
Ok(game_id)
|
||||||
|
}
|
||||||
|
Some(game_id) => {
|
||||||
|
let mut stmt = self
|
||||||
|
.conn
|
||||||
|
.prepare("UPDATE games SET gm=? game_type=? name=? WHERE uuid=?")
|
||||||
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
|
stmt.execute((gm.as_str(), game_type, name, game_id.as_str()))
|
||||||
|
.unwrap();
|
||||||
|
Ok(game_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save_game(&self, game: Game) -> Result<(), FatalError> {
|
pub fn games(&self) -> Result<Vec<GameRow>, FatalError> {
|
||||||
let mut stmt = self
|
|
||||||
.conn
|
|
||||||
.prepare("UPDATE games SET gm=? type_=? name=? WHERE id=?")
|
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
|
||||||
stmt.execute((game.gm.as_str(), game.type_, game.name, game.id.as_str()))
|
|
||||||
.unwrap();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn games(&self) -> Result<Vec<Game>, FatalError> {
|
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.conn
|
||||||
.prepare("SELECT * FROM games")
|
.prepare("SELECT * FROM games")
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
let items = stmt
|
let items = stmt
|
||||||
.query_map([], |row| {
|
.query_map([], |row| {
|
||||||
Ok(Game {
|
Ok(GameRow {
|
||||||
id: row.get(0).unwrap(),
|
id: row.get(0).unwrap(),
|
||||||
type_: row.get(1).unwrap(),
|
gm: row.get(1).unwrap(),
|
||||||
gm: row.get(2).unwrap(),
|
game_type: row.get(2).unwrap(),
|
||||||
name: row.get(3).unwrap(),
|
name: row.get(3).unwrap(),
|
||||||
players: vec![],
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect::<Result<Vec<Game>, rusqlite::Error>>()
|
.collect::<Result<Vec<GameRow>, rusqlite::Error>>()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
Ok(items)
|
Ok(items)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn session(&self, session_id: &SessionId) -> Result<Option<User>, FatalError> {
|
pub fn session(&self, session_id: &SessionId) -> Result<Option<UserRow>, FatalError> {
|
||||||
let mut stmt = self.conn
|
let mut stmt = self.conn
|
||||||
.prepare("SELECT u.uuid, u.name, u.password, u.admin, u.state FROM sessions s INNER JOIN users u ON u.uuid = s.user_id WHERE s.id = ?")
|
.prepare("SELECT u.uuid, u.name, u.password, u.admin, u.enabled FROM sessions s INNER JOIN users u ON u.uuid = s.user_id WHERE s.id = ?")
|
||||||
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
.map_err(|err| FatalError::ConstructQueryFailure(format!("{}", err)))?;
|
||||||
|
|
||||||
let items: Vec<User> = stmt
|
let items: Vec<UserRow> = stmt
|
||||||
.query_map([session_id.as_str()], |row| {
|
.query_map([session_id.as_str()], |row| {
|
||||||
Ok(User {
|
Ok(UserRow {
|
||||||
id: row.get(0).unwrap(),
|
id: row.get(0).unwrap(),
|
||||||
name: row.get(1).unwrap(),
|
name: row.get(1).unwrap(),
|
||||||
password: row.get(2).unwrap(),
|
password: row.get(2).unwrap(),
|
||||||
admin: row.get(3).unwrap(),
|
admin: row.get(3).unwrap(),
|
||||||
state: row.get(4).unwrap(),
|
enabled: row.get(4).unwrap(),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect::<Result<Vec<User>, rusqlite::Error>>()
|
.collect::<Result<Vec<UserRow>, rusqlite::Error>>()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
match &items[..] {
|
match &items[..] {
|
||||||
[] => Ok(None),
|
[] => Ok(None),
|
||||||
@ -305,30 +310,26 @@ pub async fn db_handler(db: DiskDb, requestor: Receiver<DatabaseRequest>) {
|
|||||||
_ => unimplemented!("errors for Charsheet"),
|
_ => unimplemented!("errors for Charsheet"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Request::CreateUser(username, password, admin, state) => {
|
|
||||||
let user_id = db.create_user(&username, &password, admin, state).unwrap();
|
|
||||||
tx.send(DatabaseResponse::SaveUser(user_id)).await.unwrap();
|
|
||||||
}
|
|
||||||
Request::CreateGame(_, _, _) => {}
|
|
||||||
Request::CreateSession(id) => {
|
Request::CreateSession(id) => {
|
||||||
let session_id = db.create_session(&id).unwrap();
|
let session_id = db.create_session(&id).unwrap();
|
||||||
tx.send(DatabaseResponse::CreateSession(session_id))
|
tx.send(DatabaseResponse::CreateSession(session_id))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
Request::Games => match db.games() {
|
Request::Games => {
|
||||||
Ok(games) => tx.send(DatabaseResponse::Games(games)).await.unwrap(),
|
match db.games() {
|
||||||
_ => unimplemented!("errors for Request::Games"),
|
Ok(games) => tx.send(DatabaseResponse::Games(games)).await.unwrap(),
|
||||||
},
|
_ => unimplemented!("errors for Request::Games"),
|
||||||
|
}
|
||||||
|
}
|
||||||
Request::Game(_game_id) => {
|
Request::Game(_game_id) => {
|
||||||
unimplemented!("Request::Game handler");
|
unimplemented!("Request::Game handler");
|
||||||
}
|
}
|
||||||
Request::SaveGame(game) => {
|
Request::SaveGame(game_id, user_id, game_type, game_name) => {
|
||||||
let id = game.id.clone();
|
let game_id = db.save_game(game_id, &user_id, &game_type, &game_name);
|
||||||
let save_result = db.save_game(game);
|
match game_id {
|
||||||
match save_result {
|
Ok(game_id) => {
|
||||||
Ok(_) => {
|
tx.send(DatabaseResponse::SaveGame(game_id)).await.unwrap();
|
||||||
tx.send(DatabaseResponse::SaveGame(id)).await.unwrap();
|
|
||||||
}
|
}
|
||||||
err => panic!("{:?}", err),
|
err => panic!("{:?}", err),
|
||||||
}
|
}
|
||||||
@ -349,8 +350,14 @@ pub async fn db_handler(db: DiskDb, requestor: Receiver<DatabaseRequest>) {
|
|||||||
err => panic!("{:?}", err),
|
err => panic!("{:?}", err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Request::SaveUser(user) => {
|
Request::SaveUser(user_id, username, password, admin, enabled) => {
|
||||||
let user_id = db.save_user(user);
|
let user_id = db.save_user(
|
||||||
|
user_id,
|
||||||
|
username.as_ref(),
|
||||||
|
password.as_ref(),
|
||||||
|
admin,
|
||||||
|
enabled,
|
||||||
|
);
|
||||||
match user_id {
|
match user_id {
|
||||||
Ok(user_id) => {
|
Ok(user_id) => {
|
||||||
tx.send(DatabaseResponse::SaveUser(user_id)).await.unwrap();
|
tx.send(DatabaseResponse::SaveUser(user_id)).await.unwrap();
|
||||||
@ -371,7 +378,7 @@ pub async fn db_handler(db: DiskDb, requestor: Receiver<DatabaseRequest>) {
|
|||||||
Ok(users) => {
|
Ok(users) => {
|
||||||
tx.send(DatabaseResponse::Users(users)).await.unwrap();
|
tx.send(DatabaseResponse::Users(users)).await.unwrap();
|
||||||
}
|
}
|
||||||
_ => unimplemented!("request::Users"),
|
_ => unimplemented!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,20 +6,18 @@ use std::path::Path;
|
|||||||
use async_std::channel::{bounded, Sender};
|
use async_std::channel::{bounded, Sender};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use disk_db::{db_handler, DiskDb};
|
use disk_db::{db_handler, DiskDb};
|
||||||
pub use types::{CharacterId, CharsheetRow, GameId, SessionId, UserId};
|
pub use types::{CharacterId, CharsheetRow, GameId, GameRow, SessionId, UserId, UserRow};
|
||||||
|
|
||||||
use crate::types::{AccountState, FatalError, Game, User};
|
use crate::types::FatalError;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum Request {
|
enum Request {
|
||||||
Charsheet(CharacterId),
|
Charsheet(CharacterId),
|
||||||
CreateGame(UserId, String, String),
|
|
||||||
CreateSession(UserId),
|
CreateSession(UserId),
|
||||||
CreateUser(String, String, bool, AccountState),
|
|
||||||
Game(GameId),
|
|
||||||
Games,
|
Games,
|
||||||
SaveGame(Game),
|
Game(GameId),
|
||||||
SaveUser(User),
|
SaveGame(Option<GameId>, UserId, String, String),
|
||||||
|
SaveUser(Option<UserId>, String, String, bool, bool),
|
||||||
Session(SessionId),
|
Session(SessionId),
|
||||||
User(UserId),
|
User(UserId),
|
||||||
UserByUsername(String),
|
UserByUsername(String),
|
||||||
@ -36,43 +34,49 @@ struct DatabaseRequest {
|
|||||||
enum DatabaseResponse {
|
enum DatabaseResponse {
|
||||||
Charsheet(Option<CharsheetRow>),
|
Charsheet(Option<CharsheetRow>),
|
||||||
CreateSession(SessionId),
|
CreateSession(SessionId),
|
||||||
Games(Vec<Game>),
|
Games(Vec<GameRow>),
|
||||||
Game(Option<Game>),
|
Game(Option<GameRow>),
|
||||||
SaveGame(GameId),
|
SaveGame(GameId),
|
||||||
SaveUser(UserId),
|
SaveUser(UserId),
|
||||||
Session(Option<User>),
|
Session(Option<UserRow>),
|
||||||
User(Option<User>),
|
User(Option<UserRow>),
|
||||||
Users(Vec<User>),
|
Users(Vec<UserRow>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait Database: Send + Sync {
|
pub trait Database: Send + Sync {
|
||||||
async fn create_session(&self, id: &UserId) -> Result<SessionId, FatalError>;
|
async fn users(&self) -> Result<Vec<UserRow>, FatalError>;
|
||||||
async fn session(&self, id: &SessionId) -> Result<Option<User>, FatalError>;
|
|
||||||
|
|
||||||
async fn character(&self, id: &CharacterId) -> Result<Option<CharsheetRow>, FatalError>;
|
async fn user(&self, _: &UserId) -> Result<Option<UserRow>, FatalError>;
|
||||||
|
|
||||||
async fn create_game(
|
async fn user_by_username(&self, _: &str) -> Result<Option<UserRow>, FatalError>;
|
||||||
&self,
|
|
||||||
gm: &UserId,
|
async fn save_user(
|
||||||
game_type: &str,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<GameId, FatalError>;
|
|
||||||
async fn save_game(&self, game: Game) -> Result<GameId, FatalError>;
|
|
||||||
async fn game(&self, _: &GameId) -> Result<Option<Game>, FatalError>;
|
|
||||||
async fn games(&self) -> Result<Vec<Game>, FatalError>;
|
|
||||||
|
|
||||||
async fn create_user(
|
|
||||||
&self,
|
&self,
|
||||||
|
user_id: Option<UserId>,
|
||||||
name: &str,
|
name: &str,
|
||||||
password: &str,
|
password: &str,
|
||||||
admin: bool,
|
admin: bool,
|
||||||
state: AccountState,
|
enabled: bool,
|
||||||
) -> Result<UserId, FatalError>;
|
) -> Result<UserId, FatalError>;
|
||||||
async fn save_user(&self, user: User) -> Result<UserId, FatalError>;
|
|
||||||
async fn user(&self, _: &UserId) -> Result<Option<User>, FatalError>;
|
async fn games(&self) -> Result<Vec<GameRow>, FatalError>;
|
||||||
async fn user_by_username(&self, _: &str) -> Result<Option<User>, FatalError>;
|
|
||||||
async fn users(&self) -> Result<Vec<User>, FatalError>;
|
async fn game(&self, _: &GameId) -> Result<Option<GameRow>, FatalError>;
|
||||||
|
|
||||||
|
async fn save_game(
|
||||||
|
&self,
|
||||||
|
game_id: Option<GameId>,
|
||||||
|
gm: &UserId,
|
||||||
|
game_type: &str,
|
||||||
|
game_name: &str,
|
||||||
|
) -> Result<GameId, FatalError>;
|
||||||
|
|
||||||
|
async fn character(&self, id: &CharacterId) -> Result<Option<CharsheetRow>, FatalError>;
|
||||||
|
|
||||||
|
async fn session(&self, id: &SessionId) -> Result<Option<UserRow>, FatalError>;
|
||||||
|
|
||||||
|
async fn create_session(&self, id: &UserId) -> Result<SessionId, FatalError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct DbConn {
|
pub struct DbConn {
|
||||||
@ -119,58 +123,65 @@ macro_rules! send_request {
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Database for DbConn {
|
impl Database for DbConn {
|
||||||
async fn create_session(&self, id: &UserId) -> Result<SessionId, FatalError> {
|
async fn users(&self) -> Result<Vec<UserRow>, FatalError> {
|
||||||
send_request!(self, Request::CreateSession(id.to_owned()), DatabaseResponse::CreateSession(session_id) => Ok(session_id))
|
send_request!(self, Request::Users, DatabaseResponse::Users(lst) => Ok(lst))
|
||||||
}
|
|
||||||
async fn session(&self, id: &SessionId) -> Result<Option<User>, FatalError> {
|
|
||||||
send_request!(self, Request::Session(id.to_owned()), DatabaseResponse::Session(row) => Ok(row))
|
|
||||||
}
|
|
||||||
async fn character(&self, id: &CharacterId) -> Result<Option<CharsheetRow>, FatalError> {
|
|
||||||
send_request!(self, Request::Charsheet(id.to_owned()), DatabaseResponse::Charsheet(row) => Ok(row))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_game(
|
async fn user(&self, uid: &UserId) -> Result<Option<UserRow>, FatalError> {
|
||||||
|
send_request!(self, Request::User(uid.clone()), DatabaseResponse::User(user) => Ok(user))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn user_by_username(&self, username: &str) -> Result<Option<UserRow>, FatalError> {
|
||||||
|
send_request!(self, Request::UserByUsername(username.to_owned()), DatabaseResponse::User(user) => Ok(user))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save_user(
|
||||||
&self,
|
&self,
|
||||||
|
user_id: Option<UserId>,
|
||||||
|
name: &str,
|
||||||
|
password: &str,
|
||||||
|
admin: bool,
|
||||||
|
enabled: bool,
|
||||||
|
) -> Result<UserId, FatalError> {
|
||||||
|
send_request!(self,
|
||||||
|
Request::SaveUser(
|
||||||
|
user_id,
|
||||||
|
name.to_owned(),
|
||||||
|
password.to_owned(),
|
||||||
|
admin,
|
||||||
|
enabled,
|
||||||
|
),
|
||||||
|
DatabaseResponse::SaveUser(user_id) => Ok(user_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn games(&self) -> Result<Vec<GameRow>, FatalError> {
|
||||||
|
send_request!(self, Request::Games, DatabaseResponse::Games(lst) => Ok(lst))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn game(&self, game_id: &GameId) -> Result<Option<GameRow>, FatalError> {
|
||||||
|
send_request!(self, Request::Game(game_id.clone()), DatabaseResponse::Game(game) => Ok(game))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save_game(
|
||||||
|
&self,
|
||||||
|
game_id: Option<GameId>,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
game_type: &str,
|
game_type: &str,
|
||||||
game_name: &str,
|
game_name: &str,
|
||||||
) -> Result<GameId, FatalError> {
|
) -> Result<GameId, FatalError> {
|
||||||
send_request!(self, Request::CreateGame(user_id.to_owned(), game_type.to_owned(), game_name.to_owned()), DatabaseResponse::SaveGame(game_id) => Ok(game_id))
|
send_request!(self, Request::SaveGame(game_id, user_id.to_owned(), game_type.to_owned(), game_name.to_owned()), DatabaseResponse::SaveGame(game_id) => Ok(game_id))
|
||||||
}
|
|
||||||
async fn save_game(&self, game: Game) -> Result<GameId, FatalError> {
|
|
||||||
send_request!(self, Request::SaveGame(game), DatabaseResponse::SaveGame(game_id) => Ok(game_id))
|
|
||||||
}
|
|
||||||
async fn game(&self, game_id: &GameId) -> Result<Option<Game>, FatalError> {
|
|
||||||
send_request!(self, Request::Game(game_id.clone()), DatabaseResponse::Game(game) => Ok(game))
|
|
||||||
}
|
|
||||||
async fn games(&self) -> Result<Vec<Game>, FatalError> {
|
|
||||||
send_request!(self, Request::Games, DatabaseResponse::Games(lst) => Ok(lst))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_user(
|
async fn character(&self, id: &CharacterId) -> Result<Option<CharsheetRow>, FatalError> {
|
||||||
&self,
|
send_request!(self, Request::Charsheet(id.to_owned()), DatabaseResponse::Charsheet(row) => Ok(row))
|
||||||
name: &str,
|
|
||||||
password: &str,
|
|
||||||
admin: bool,
|
|
||||||
state: AccountState,
|
|
||||||
) -> Result<UserId, FatalError> {
|
|
||||||
send_request!(self,
|
|
||||||
Request::CreateUser(name.to_owned(), password.to_owned(), admin, state),
|
|
||||||
DatabaseResponse::SaveUser(user_id) => Ok(user_id))
|
|
||||||
}
|
}
|
||||||
async fn save_user(&self, user: User) -> Result<UserId, FatalError> {
|
|
||||||
send_request!(self,
|
async fn session(&self, id: &SessionId) -> Result<Option<UserRow>, FatalError> {
|
||||||
Request::SaveUser(user),
|
send_request!(self, Request::Session(id.to_owned()), DatabaseResponse::Session(row) => Ok(row))
|
||||||
DatabaseResponse::SaveUser(user_id) => Ok(user_id))
|
|
||||||
}
|
}
|
||||||
async fn user(&self, uid: &UserId) -> Result<Option<User>, FatalError> {
|
|
||||||
send_request!(self, Request::User(uid.clone()), DatabaseResponse::User(user) => Ok(user))
|
async fn create_session(&self, id: &UserId) -> Result<SessionId, FatalError> {
|
||||||
}
|
send_request!(self, Request::CreateSession(id.to_owned()), DatabaseResponse::CreateSession(session_id) => Ok(session_id))
|
||||||
async fn user_by_username(&self, username: &str) -> Result<Option<User>, FatalError> {
|
|
||||||
send_request!(self, Request::UserByUsername(username.to_owned()), DatabaseResponse::User(user) => Ok(user))
|
|
||||||
}
|
|
||||||
async fn users(&self) -> Result<Vec<User>, FatalError> {
|
|
||||||
send_request!(self, Request::Users, DatabaseResponse::Users(lst) => Ok(lst))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -190,19 +201,12 @@ mod test {
|
|||||||
let no_path: Option<PathBuf> = None;
|
let no_path: Option<PathBuf> = None;
|
||||||
let db = DiskDb::new(no_path).unwrap();
|
let db = DiskDb::new(no_path).unwrap();
|
||||||
|
|
||||||
db.create_user("admin", "abcdefg", true, AccountState::Normal)
|
db.save_user(Some(UserId::from("admin")), "admin", "abcdefg", true, true)
|
||||||
.unwrap();
|
|
||||||
let game_id = db
|
|
||||||
.create_game(
|
|
||||||
&UserId::from("admin"),
|
|
||||||
"Candela",
|
|
||||||
"Circle of the Winter Solstice",
|
|
||||||
)
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
let game_id = db.save_game(None, &UserId::from("admin"), "Candela", "Circle of the Winter Solstice").unwrap();
|
||||||
(db, game_id)
|
(db, game_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[ignore]
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_can_retrieve_a_character() {
|
fn it_can_retrieve_a_character() {
|
||||||
let (db, game_id) = setup_db();
|
let (db, game_id) = setup_db();
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use chrono::{NaiveDateTime, Utc};
|
use rusqlite::types::{FromSql, FromSqlResult, ValueRef};
|
||||||
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ValueRef};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use typeshare::typeshare;
|
use typeshare::typeshare;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
@ -160,6 +159,15 @@ impl FromSql for CharacterId {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct UserRow {
|
||||||
|
pub id: UserId,
|
||||||
|
pub name: String,
|
||||||
|
pub password: String,
|
||||||
|
pub admin: bool,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Role {
|
pub struct Role {
|
||||||
userid: UserId,
|
userid: UserId,
|
||||||
@ -167,7 +175,6 @@ pub struct Role {
|
|||||||
role: String,
|
role: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct GameRow {
|
pub struct GameRow {
|
||||||
pub id: GameId,
|
pub id: GameId,
|
||||||
@ -175,7 +182,6 @@ pub struct GameRow {
|
|||||||
pub game_type: String,
|
pub game_type: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct CharsheetRow {
|
pub struct CharsheetRow {
|
||||||
@ -190,20 +196,5 @@ pub struct SessionRow {
|
|||||||
user_id: SessionId,
|
user_id: SessionId,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct DateTime(pub chrono::DateTime<Utc>);
|
|
||||||
|
|
||||||
impl FromSql for DateTime {
|
|
||||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
|
||||||
match value {
|
|
||||||
ValueRef::Text(text) => String::from_utf8(text.to_vec())
|
|
||||||
.map_err(|_err| FromSqlError::InvalidType)
|
|
||||||
.and_then(|s| {
|
|
||||||
NaiveDateTime::parse_from_str(&s, "%Y-%m-%d %H:%M:%S")
|
|
||||||
.map_err(|_err| FromSqlError::InvalidType)
|
|
||||||
})
|
|
||||||
.and_then(|dt| Ok(DateTime(dt.and_utc()))),
|
|
||||||
_ => Err(FromSqlError::InvalidType),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,20 +1,23 @@
|
|||||||
mod game_management;
|
mod game_management;
|
||||||
mod user_management;
|
mod user_management;
|
||||||
mod types;
|
|
||||||
|
|
||||||
use axum::{http::StatusCode, Json};
|
use axum::{http::StatusCode, Json};
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
pub use game_management::*;
|
pub use game_management::*;
|
||||||
pub use user_management::*;
|
pub use user_management::*;
|
||||||
pub use types::*;
|
|
||||||
|
|
||||||
use result_extended::ResultExt;
|
use result_extended::ResultExt;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
core::Core,
|
core::Core,
|
||||||
types::{AppError, FatalError},
|
types::{AppError, FatalError},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||||
|
pub struct HealthCheck {
|
||||||
|
pub ok: bool,
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn wrap_handler<F, A, Fut>(f: F) -> (StatusCode, Json<Option<A>>)
|
pub async fn wrap_handler<F, A, Fut>(f: F) -> (StatusCode, Json<Option<A>>)
|
||||||
where
|
where
|
||||||
F: FnOnce() -> Fut,
|
F: FnOnce() -> Fut,
|
||||||
@ -42,7 +45,7 @@ where
|
|||||||
pub async fn healthcheck(core: Core) -> Vec<u8> {
|
pub async fn healthcheck(core: Core) -> Vec<u8> {
|
||||||
match core.status().await {
|
match core.status().await {
|
||||||
ResultExt::Ok(s) => serde_json::to_vec(&HealthCheck {
|
ResultExt::Ok(s) => serde_json::to_vec(&HealthCheck {
|
||||||
ok: s.ok,
|
ok: s.admin_enabled,
|
||||||
})
|
})
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
ResultExt::Err(_) => serde_json::to_vec(&HealthCheck { ok: false }).unwrap(),
|
ResultExt::Err(_) => serde_json::to_vec(&HealthCheck { ok: false }).unwrap(),
|
||||||
|
@ -1,83 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use typeshare::typeshare;
|
|
||||||
|
|
||||||
use crate::database::UserId;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
|
||||||
pub struct HealthCheck {
|
|
||||||
pub ok: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
||||||
#[serde(tag = "type", content = "content")]
|
|
||||||
#[typeshare]
|
|
||||||
pub enum AccountState {
|
|
||||||
Normal,
|
|
||||||
PasswordReset(String),
|
|
||||||
Locked,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<crate::types::AccountState> for AccountState {
|
|
||||||
fn from(s: crate::types::AccountState) -> Self {
|
|
||||||
match s {
|
|
||||||
crate::types::AccountState::Normal => Self::Normal,
|
|
||||||
crate::types::AccountState::PasswordReset(r) => {
|
|
||||||
Self::PasswordReset(format!("{}", r.format("%Y-%m-%d %H:%M:%S")))
|
|
||||||
}
|
|
||||||
crate::types::AccountState::Locked => Self::Locked,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[typeshare]
|
|
||||||
pub struct User {
|
|
||||||
pub id: UserId,
|
|
||||||
pub name: String,
|
|
||||||
pub password: String,
|
|
||||||
pub admin: bool,
|
|
||||||
pub state: AccountState,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<crate::types::User> for User {
|
|
||||||
fn from(u: crate::types::User) -> Self {
|
|
||||||
Self {
|
|
||||||
id: u.id,
|
|
||||||
name: u.name,
|
|
||||||
password: u.password,
|
|
||||||
admin: u.admin,
|
|
||||||
state: AccountState::from(u.state),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
#[derive(Deserialize, Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[typeshare]
|
|
||||||
pub struct UserOverview {
|
|
||||||
pub id: UserId,
|
|
||||||
pub name: String,
|
|
||||||
pub is_admin: bool,
|
|
||||||
pub games: Vec<crate::types::GameOverview>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UserOverview {
|
|
||||||
pub fn new(user: crate::types::UserOverview, games: Vec<crate::types::GameOverview>) -> Self {
|
|
||||||
let s = Self::from(user);
|
|
||||||
Self{ games, ..s }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<crate::types::UserOverview> for UserOverview {
|
|
||||||
fn from(input: crate::types::UserOverview) -> Self {
|
|
||||||
Self {
|
|
||||||
id: input.id,
|
|
||||||
name: input.name,
|
|
||||||
is_admin: input.is_admin,
|
|
||||||
games: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
@ -1,13 +1,16 @@
|
|||||||
use axum::{http::HeaderMap, Json};
|
use axum::{
|
||||||
|
http::HeaderMap,
|
||||||
|
Json,
|
||||||
|
};
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
use result_extended::{error, ok, return_error, ResultExt};
|
use result_extended::{error, ok, return_error, ResultExt};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use typeshare::typeshare;
|
use typeshare::typeshare;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
core::{AuthResponse, Core},
|
core::Core,
|
||||||
database::{SessionId, UserId},
|
database::{SessionId, UserId},
|
||||||
types::{AppError, FatalError, User},
|
types::{AppError, FatalError, User, UserProfile},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
@ -30,19 +33,12 @@ pub struct SetPasswordRequest {
|
|||||||
pub password_2: String,
|
pub password_2: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
|
||||||
#[typeshare]
|
|
||||||
pub struct SetAdminPasswordRequest {
|
|
||||||
pub password: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn check_session(
|
async fn check_session(
|
||||||
core: &Core,
|
core: &Core,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> ResultExt<Option<User>, AppError, FatalError> {
|
) -> ResultExt<Option<User>, AppError, FatalError> {
|
||||||
match headers.get("Authorization") {
|
match headers.get("Authorization") {
|
||||||
Some(token) => {
|
Some(token) => {
|
||||||
println!("check_session: {:?}", token);
|
|
||||||
match token
|
match token
|
||||||
.to_str()
|
.to_str()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@ -97,7 +93,7 @@ where
|
|||||||
pub async fn check_password(
|
pub async fn check_password(
|
||||||
core: Core,
|
core: Core,
|
||||||
req: Json<AuthRequest>,
|
req: Json<AuthRequest>,
|
||||||
) -> ResultExt<AuthResponse, AppError, FatalError> {
|
) -> ResultExt<SessionId, AppError, FatalError> {
|
||||||
let Json(AuthRequest { username, password }) = req;
|
let Json(AuthRequest { username, password }) = req;
|
||||||
core.auth(&username, &password).await
|
core.auth(&username, &password).await
|
||||||
}
|
}
|
||||||
@ -106,7 +102,7 @@ pub async fn get_user(
|
|||||||
core: Core,
|
core: Core,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
user_id: Option<UserId>,
|
user_id: Option<UserId>,
|
||||||
) -> ResultExt<Option<crate::types::UserOverview>, AppError, FatalError> {
|
) -> ResultExt<Option<UserProfile>, AppError, FatalError> {
|
||||||
auth_required(core.clone(), headers, |user| async move {
|
auth_required(core.clone(), headers, |user| async move {
|
||||||
match user_id {
|
match user_id {
|
||||||
Some(user_id) => core.user(user_id).await,
|
Some(user_id) => core.user(user_id).await,
|
||||||
@ -115,16 +111,6 @@ pub async fn get_user(
|
|||||||
}).await
|
}).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_users(
|
|
||||||
core: Core,
|
|
||||||
headers: HeaderMap,
|
|
||||||
) -> ResultExt<Vec<crate::types::UserOverview>, AppError, FatalError> {
|
|
||||||
auth_required(core.clone(), headers, |_user| async move {
|
|
||||||
core.list_users().await
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn create_user(
|
pub async fn create_user(
|
||||||
core: Core,
|
core: Core,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
@ -132,8 +118,7 @@ pub async fn create_user(
|
|||||||
) -> ResultExt<UserId, AppError, FatalError> {
|
) -> ResultExt<UserId, AppError, FatalError> {
|
||||||
admin_required(core.clone(), headers, |_admin| async {
|
admin_required(core.clone(), headers, |_admin| async {
|
||||||
core.create_user(&req.username).await
|
core.create_user(&req.username).await
|
||||||
})
|
}).await
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_password(
|
pub async fn set_password(
|
||||||
@ -147,6 +132,5 @@ pub async fn set_password(
|
|||||||
} else {
|
} else {
|
||||||
error(AppError::BadRequest)
|
error(AppError::BadRequest)
|
||||||
}
|
}
|
||||||
})
|
}).await
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,6 @@
|
|||||||
use axum::{
|
use axum::{
|
||||||
extract::Path,
|
extract::Path,
|
||||||
http::{
|
http::{header::{AUTHORIZATION, CONTENT_TYPE}, HeaderMap, Method},
|
||||||
header::{AUTHORIZATION, CONTENT_TYPE},
|
|
||||||
HeaderMap, Method,
|
|
||||||
},
|
|
||||||
routing::{get, post, put},
|
routing::{get, post, put},
|
||||||
Json, Router,
|
Json, Router,
|
||||||
};
|
};
|
||||||
@ -13,7 +10,7 @@ use crate::{
|
|||||||
core::Core,
|
core::Core,
|
||||||
database::UserId,
|
database::UserId,
|
||||||
handlers::{
|
handlers::{
|
||||||
check_password, create_game, create_user, get_user, get_users, healthcheck, set_password,
|
check_password, create_game, create_user, get_user, healthcheck, set_password,
|
||||||
wrap_handler, AuthRequest, CreateGameRequest, CreateUserRequest, SetPasswordRequest,
|
wrap_handler, AuthRequest, CreateGameRequest, CreateUserRequest, SetPasswordRequest,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@ -66,19 +63,6 @@ pub fn routes(core: Core) -> Router {
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
|
||||||
"/api/v1/users",
|
|
||||||
get({
|
|
||||||
let core = core.clone();
|
|
||||||
move |headers: HeaderMap| wrap_handler(|| get_users(core, headers))
|
|
||||||
})
|
|
||||||
.layer(
|
|
||||||
CorsLayer::new()
|
|
||||||
.allow_methods([Method::GET])
|
|
||||||
.allow_headers([AUTHORIZATION])
|
|
||||||
.allow_origin(Any),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/user/password",
|
"/api/v1/user/password",
|
||||||
put({
|
put({
|
||||||
@ -113,34 +97,35 @@ pub fn routes(core: Core) -> Router {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use std::{path::PathBuf, time::Duration};
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use axum::http::StatusCode;
|
use axum::http::StatusCode;
|
||||||
use axum_test::TestServer;
|
use axum_test::TestServer;
|
||||||
use chrono::Utc;
|
|
||||||
use cool_asserts::assert_matches;
|
use cool_asserts::assert_matches;
|
||||||
use result_extended::ResultExt;
|
use result_extended::ResultExt;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::{
|
use crate::{
|
||||||
asset_db::FsAssets,
|
asset_db::FsAssets,
|
||||||
core::{AuthResponse, Core},
|
core::Core,
|
||||||
database::{Database, DbConn, GameId, SessionId, UserId},
|
database::{Database, DbConn, GameId, SessionId, UserId},
|
||||||
handlers::CreateGameRequest,
|
handlers::CreateGameRequest,
|
||||||
types::UserOverview,
|
types::UserProfile,
|
||||||
};
|
};
|
||||||
|
|
||||||
async fn initialize_test_server() -> (Core, TestServer) {
|
fn setup_without_admin() -> (Core, TestServer) {
|
||||||
let password_exp = Utc::now() + Duration::from_secs(5);
|
|
||||||
let memory_db: Option<PathBuf> = None;
|
let memory_db: Option<PathBuf> = None;
|
||||||
let conn = DbConn::new(memory_db);
|
let conn = DbConn::new(memory_db);
|
||||||
let _admin_id = conn
|
let core = Core::new(FsAssets::new(PathBuf::from("/home/savanni/Pictures")), conn);
|
||||||
.create_user(
|
let app = routes(core.clone());
|
||||||
"admin",
|
let server = TestServer::new(app).unwrap();
|
||||||
"aoeu",
|
(core, server)
|
||||||
true,
|
}
|
||||||
crate::types::AccountState::PasswordReset(password_exp),
|
|
||||||
)
|
async fn setup_admin_enabled() -> (Core, TestServer) {
|
||||||
|
let memory_db: Option<PathBuf> = None;
|
||||||
|
let conn = DbConn::new(memory_db);
|
||||||
|
conn.save_user(Some(UserId::from("admin")), "admin", "aoeu", true, true)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let core = Core::new(FsAssets::new(PathBuf::from("/home/savanni/Pictures")), conn);
|
let core = Core::new(FsAssets::new(PathBuf::from("/home/savanni/Pictures")), conn);
|
||||||
@ -149,26 +134,8 @@ mod test {
|
|||||||
(core, server)
|
(core, server)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn setup_with_admin() -> (Core, TestServer) {
|
|
||||||
let (core, server) = initialize_test_server().await;
|
|
||||||
core.set_password(UserId::from("admin"), "aoeu".to_owned())
|
|
||||||
.await;
|
|
||||||
(core, server)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn setup_with_disabled_user() -> (Core, TestServer) {
|
|
||||||
let (core, server) = setup_with_admin().await;
|
|
||||||
let uuid = match core.create_user("shephard").await {
|
|
||||||
ResultExt::Ok(uuid) => uuid,
|
|
||||||
ResultExt::Err(err) => panic!("{}", err),
|
|
||||||
ResultExt::Fatal(err) => panic!("{}", err),
|
|
||||||
};
|
|
||||||
core.disable_user(uuid).await;
|
|
||||||
(core, server)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn setup_with_user() -> (Core, TestServer) {
|
async fn setup_with_user() -> (Core, TestServer) {
|
||||||
let (core, server) = setup_with_admin().await;
|
let (core, server) = setup_admin_enabled().await;
|
||||||
let response = server
|
let response = server
|
||||||
.post("/api/v1/auth")
|
.post("/api/v1/auth")
|
||||||
.json(&AuthRequest {
|
.json(&AuthRequest {
|
||||||
@ -203,7 +170,18 @@ mod test {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn it_returns_a_healthcheck() {
|
async fn it_returns_a_healthcheck() {
|
||||||
let (_core, server) = initialize_test_server().await;
|
let (core, server) = setup_without_admin();
|
||||||
|
|
||||||
|
let response = server.get("/api/v1/health").await;
|
||||||
|
response.assert_status_ok();
|
||||||
|
let b: crate::handlers::HealthCheck = response.json();
|
||||||
|
assert_eq!(b, crate::handlers::HealthCheck { ok: false });
|
||||||
|
|
||||||
|
assert_matches!(
|
||||||
|
core.save_user(Some(UserId::from("admin")), "admin", "aoeu", true, true)
|
||||||
|
.await,
|
||||||
|
ResultExt::Ok(_)
|
||||||
|
);
|
||||||
|
|
||||||
let response = server.get("/api/v1/health").await;
|
let response = server.get("/api/v1/health").await;
|
||||||
response.assert_status_ok();
|
response.assert_status_ok();
|
||||||
@ -211,65 +189,9 @@ mod test {
|
|||||||
assert_eq!(b, crate::handlers::HealthCheck { ok: true });
|
assert_eq!(b, crate::handlers::HealthCheck { ok: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
#[ignore]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_new_user_has_an_expired_password() {
|
|
||||||
let (_core, server) = setup_with_admin().await;
|
|
||||||
|
|
||||||
let response = server
|
|
||||||
.post("/api/v1/auth")
|
|
||||||
.add_header("Content-Type", "application/json")
|
|
||||||
.json(&AuthRequest {
|
|
||||||
username: "admin".to_owned(),
|
|
||||||
password: "aoeu".to_owned(),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
response.assert_status_ok();
|
|
||||||
let session_id = response.json::<Option<AuthResponse>>().unwrap();
|
|
||||||
|
|
||||||
let session_id = match session_id {
|
|
||||||
AuthResponse::PasswordReset(session_id) => session_id,
|
|
||||||
AuthResponse::Success(_) => panic!("admin user password has already been set"),
|
|
||||||
AuthResponse::Locked => panic!("admin user is already expired"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = server
|
|
||||||
.put("/api/v1/user")
|
|
||||||
.add_header("Authorization", format!("Bearer {}", session_id))
|
|
||||||
.json("savanni")
|
|
||||||
.await;
|
|
||||||
response.assert_status_ok();
|
|
||||||
|
|
||||||
let response = server
|
|
||||||
.post("/api/v1/auth")
|
|
||||||
.add_header("Content-Type", "application/json")
|
|
||||||
.json(&AuthRequest {
|
|
||||||
username: "savanni".to_owned(),
|
|
||||||
password: "".to_owned(),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
response.assert_status_ok();
|
|
||||||
let session = response.json::<Option<AuthResponse>>().unwrap();
|
|
||||||
assert_matches!(session, AuthResponse::PasswordReset(_));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[ignore]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn it_refuses_to_authenticate_a_disabled_user() {
|
|
||||||
let (_core, _server) = setup_with_disabled_user().await;
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[ignore]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn it_forces_changing_expired_password() {
|
|
||||||
let (_core, _server) = setup_with_user().await;
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn it_authenticates_a_user() {
|
async fn it_authenticates_a_user() {
|
||||||
let (_core, server) = setup_with_admin().await;
|
let (_core, server) = setup_admin_enabled().await;
|
||||||
|
|
||||||
let response = server
|
let response = server
|
||||||
.post("/api/v1/auth")
|
.post("/api/v1/auth")
|
||||||
@ -297,12 +219,13 @@ mod test {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
response.assert_status_ok();
|
response.assert_status_ok();
|
||||||
assert_matches!(response.json(), Some(AuthResponse::PasswordReset(_)));
|
let session_id: Option<SessionId> = response.json();
|
||||||
|
assert!(session_id.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn it_returns_user_profile() {
|
async fn it_returns_user_profile() {
|
||||||
let (_core, server) = setup_with_admin().await;
|
let (_core, server) = setup_admin_enabled().await;
|
||||||
|
|
||||||
let response = server.get("/api/v1/user").await;
|
let response = server.get("/api/v1/user").await;
|
||||||
response.assert_status(StatusCode::UNAUTHORIZED);
|
response.assert_status(StatusCode::UNAUTHORIZED);
|
||||||
@ -315,19 +238,27 @@ mod test {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
response.assert_status_ok();
|
response.assert_status_ok();
|
||||||
let session_id = assert_matches!(response.json(), Some(AuthResponse::PasswordReset(session_id)) => session_id);
|
let session_id: Option<SessionId> = response.json();
|
||||||
|
let session_id = session_id.unwrap();
|
||||||
|
|
||||||
let response = server
|
let response = server
|
||||||
.get("/api/v1/user")
|
.get("/api/v1/user")
|
||||||
.add_header("Authorization", format!("Bearer {}", session_id))
|
.add_header("Authorization", format!("Bearer {}", session_id))
|
||||||
.await;
|
.await;
|
||||||
response.assert_status_ok();
|
response.assert_status_ok();
|
||||||
let profile: Option<UserOverview> = response.json();
|
let profile: Option<UserProfile> = response.json();
|
||||||
let profile = profile.unwrap();
|
let profile = profile.unwrap();
|
||||||
|
assert_eq!(profile.id, UserId::from("admin"));
|
||||||
assert_eq!(profile.name, "admin");
|
assert_eq!(profile.name, "admin");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[ignore]
|
#[tokio::test]
|
||||||
|
async fn an_admin_can_create_a_user() {
|
||||||
|
// All of the contents of this test are basically required for any test on individual
|
||||||
|
// users, so I moved it all into the setup code.
|
||||||
|
let (_core, _server) = setup_with_user().await;
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_user_can_get_any_user_profile() {
|
async fn a_user_can_get_any_user_profile() {
|
||||||
let (core, server) = setup_with_user().await;
|
let (core, server) = setup_with_user().await;
|
||||||
@ -354,7 +285,7 @@ mod test {
|
|||||||
.add_header("Authorization", format!("Bearer {}", session_id))
|
.add_header("Authorization", format!("Bearer {}", session_id))
|
||||||
.await;
|
.await;
|
||||||
response.assert_status_ok();
|
response.assert_status_ok();
|
||||||
let profile: Option<UserOverview> = response.json();
|
let profile: Option<UserProfile> = response.json();
|
||||||
let profile = profile.unwrap();
|
let profile = profile.unwrap();
|
||||||
assert_eq!(profile.name, "savanni");
|
assert_eq!(profile.name, "savanni");
|
||||||
|
|
||||||
@ -363,12 +294,11 @@ mod test {
|
|||||||
.add_header("Authorization", format!("Bearer {}", session_id))
|
.add_header("Authorization", format!("Bearer {}", session_id))
|
||||||
.await;
|
.await;
|
||||||
response.assert_status_ok();
|
response.assert_status_ok();
|
||||||
let profile: Option<UserOverview> = response.json();
|
let profile: Option<UserProfile> = response.json();
|
||||||
let profile = profile.unwrap();
|
let profile = profile.unwrap();
|
||||||
assert_eq!(profile.name, "admin");
|
assert_eq!(profile.name, "admin");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[ignore]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_user_can_change_their_password() {
|
async fn a_user_can_change_their_password() {
|
||||||
let (_core, server) = setup_with_user().await;
|
let (_core, server) = setup_with_user().await;
|
||||||
@ -387,7 +317,7 @@ mod test {
|
|||||||
.get("/api/v1/user")
|
.get("/api/v1/user")
|
||||||
.add_header("Authorization", format!("Bearer {}", session_id))
|
.add_header("Authorization", format!("Bearer {}", session_id))
|
||||||
.await;
|
.await;
|
||||||
let profile = response.json::<Option<UserOverview>>().unwrap();
|
let profile = response.json::<Option<UserProfile>>().unwrap();
|
||||||
assert_eq!(profile.name, "savanni");
|
assert_eq!(profile.name, "savanni");
|
||||||
|
|
||||||
let response = server
|
let response = server
|
||||||
@ -420,7 +350,6 @@ mod test {
|
|||||||
response.assert_status(StatusCode::OK);
|
response.assert_status(StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[ignore]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_user_can_create_a_game() {
|
async fn a_user_can_create_a_game() {
|
||||||
let (_core, server) = setup_with_user().await;
|
let (_core, server) = setup_with_user().await;
|
||||||
|
@ -1,8 +1,3 @@
|
|||||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
|
||||||
use rusqlite::{
|
|
||||||
types::{FromSql, FromSqlError, ToSqlOutput, Value, ValueRef},
|
|
||||||
ToSql,
|
|
||||||
};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
@ -10,7 +5,7 @@ use typeshare::typeshare;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
asset_db::AssetId,
|
asset_db::AssetId,
|
||||||
database::{GameId, UserId},
|
database::{GameId, GameRow, UserId, UserRow},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
@ -75,55 +70,27 @@ pub struct Rgb {
|
|||||||
pub blue: u32,
|
pub blue: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
pub enum AccountState {
|
#[serde(rename_all = "camelCase")]
|
||||||
Normal,
|
#[typeshare]
|
||||||
PasswordReset(DateTime<Utc>),
|
|
||||||
Locked,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromSql for AccountState {
|
|
||||||
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
|
|
||||||
if let ValueRef::Text(text) = value {
|
|
||||||
let text = String::from_utf8(text.to_vec()).unwrap();
|
|
||||||
if text.starts_with("Normal") {
|
|
||||||
Ok(AccountState::Normal)
|
|
||||||
} else if text.starts_with("PasswordReset") {
|
|
||||||
let exp_str = text.strip_prefix("PasswordReset ").unwrap();
|
|
||||||
let exp = NaiveDateTime::parse_from_str(exp_str, "%Y-%m-%d %H:%M:%S")
|
|
||||||
.unwrap()
|
|
||||||
.and_utc();
|
|
||||||
Ok(AccountState::PasswordReset(exp))
|
|
||||||
} else if text.starts_with("Locked") {
|
|
||||||
Ok(AccountState::Locked)
|
|
||||||
} else {
|
|
||||||
Err(FromSqlError::InvalidType)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Err(FromSqlError::InvalidType)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql for AccountState {
|
|
||||||
fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
|
|
||||||
match self {
|
|
||||||
AccountState::Normal => Ok(ToSqlOutput::Borrowed(ValueRef::Text("Normal".as_bytes()))),
|
|
||||||
AccountState::PasswordReset(expiration) => Ok(ToSqlOutput::Owned(Value::Text(
|
|
||||||
format!("PasswordReset {}", expiration.format("%Y-%m-%d %H:%M:%S")),
|
|
||||||
))),
|
|
||||||
AccountState::Locked => Ok(ToSqlOutput::Borrowed(ValueRef::Text("Locked".as_bytes()))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: UserId,
|
pub id: UserId,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
pub admin: bool,
|
pub admin: bool,
|
||||||
pub state: AccountState,
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<UserRow> for User {
|
||||||
|
fn from(row: UserRow) -> Self {
|
||||||
|
Self {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name.to_owned(),
|
||||||
|
password: row.password.to_owned(),
|
||||||
|
admin: row.admin,
|
||||||
|
enabled: row.enabled,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
@ -145,8 +112,7 @@ pub struct Player {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[typeshare]
|
#[typeshare]
|
||||||
pub struct Game {
|
pub struct Game {
|
||||||
pub id: GameId,
|
pub id: String,
|
||||||
pub type_: String,
|
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub gm: UserId,
|
pub gm: UserId,
|
||||||
pub players: Vec<UserId>,
|
pub players: Vec<UserId>,
|
||||||
@ -167,27 +133,25 @@ pub enum Message {
|
|||||||
UpdateTabletop(Tabletop),
|
UpdateTabletop(Tabletop),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[typeshare]
|
#[typeshare]
|
||||||
pub struct UserOverview {
|
pub struct UserProfile {
|
||||||
pub id: UserId,
|
pub id: UserId,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub games: Vec<GameOverview>,
|
||||||
pub is_admin: bool,
|
pub is_admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[typeshare]
|
#[typeshare]
|
||||||
pub struct GameOverview {
|
pub struct GameOverview {
|
||||||
pub id: GameId,
|
pub id: GameId,
|
||||||
pub type_: String,
|
pub game_type: String,
|
||||||
pub name: String,
|
pub game_name: String,
|
||||||
pub gm: UserId,
|
pub gm: UserId,
|
||||||
pub players: Vec<UserId>,
|
pub players: Vec<UserId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
impl From<GameRow> for GameOverview {
|
impl From<GameRow> for GameOverview {
|
||||||
fn from(row: GameRow) -> Self {
|
fn from(row: GameRow) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@ -199,4 +163,3 @@ impl From<GameRow> for GameOverview {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
2
visions/ui/package-lock.json
generated
2
visions/ui/package-lock.json
generated
@ -33,7 +33,7 @@
|
|||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"typescript": "^5.7.3"
|
"typescript": "^5.7.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@adobe/css-tools": {
|
"node_modules/@adobe/css-tools": {
|
||||||
|
@ -32,8 +32,8 @@ interface AuthedViewProps {
|
|||||||
const AuthedView = ({ client, children }: PropsWithChildren<AuthedViewProps>) => {
|
const AuthedView = ({ client, children }: PropsWithChildren<AuthedViewProps>) => {
|
||||||
const [state, manager] = useContext(StateContext)
|
const [state, manager] = useContext(StateContext)
|
||||||
return (
|
return (
|
||||||
<Authentication onSetPassword={(password1, password2) => {
|
<Authentication onAdminPassword={(password) => {
|
||||||
manager.setPassword(password1, password2)
|
manager.setAdminPassword(password)
|
||||||
}} onAuth={(username, password) => manager.auth(username, password)}>
|
}} onAuth={(username, password) => manager.auth(username, password)}>
|
||||||
{children}
|
{children}
|
||||||
</Authentication>
|
</Authentication>
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { AuthResponse, SessionId, UserId, UserOverview } from "visions-types";
|
import { SessionId, UserId, UserProfile } from "visions-types";
|
||||||
|
|
||||||
export type PlayingField = {
|
export type PlayingField = {
|
||||||
backgroundImage: string;
|
backgroundImage: string;
|
||||||
@ -48,13 +48,10 @@ export class Client {
|
|||||||
return fetch(url, { method: 'PUT', headers: [['Content-Type', 'application/json']], body: JSON.stringify(name) });
|
return fetch(url, { method: 'PUT', headers: [['Content-Type', 'application/json']], body: JSON.stringify(name) });
|
||||||
}
|
}
|
||||||
|
|
||||||
async users(sessionId: string) {
|
async users() {
|
||||||
const url = new URL(this.base);
|
const url = new URL(this.base);
|
||||||
url.pathname = '/api/v1/users/';
|
url.pathname = '/api/v1/users/';
|
||||||
return fetch(url, {
|
return fetch(url).then((response) => response.json());
|
||||||
method: 'GET',
|
|
||||||
headers: [['Authorization', `Bearer ${sessionId}`]]
|
|
||||||
}).then((response) => response.json());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async charsheet(id: string) {
|
async charsheet(id: string) {
|
||||||
@ -63,18 +60,14 @@ export class Client {
|
|||||||
return fetch(url).then((response) => response.json());
|
return fetch(url).then((response) => response.json());
|
||||||
}
|
}
|
||||||
|
|
||||||
async setPassword(password_1: string, password_2: string) {
|
async setAdminPassword(password: string) {
|
||||||
const url = new URL(this.base);
|
const url = new URL(this.base);
|
||||||
url.pathname = `/api/v1/user/password`;
|
url.pathname = `/api/v1/admin_password`;
|
||||||
|
console.log("setting the admin password to: ", password);
|
||||||
return fetch(url, {
|
return fetch(url, { method: 'PUT', headers: [['Content-Type', 'application/json']], body: JSON.stringify(password) });
|
||||||
method: 'PUT', headers: [['Content-Type', 'application/json']], body: JSON.stringify({
|
|
||||||
password_1, password_2,
|
|
||||||
})
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async auth(username: string, password: string): Promise<AuthResponse> {
|
async auth(username: string, password: string): Promise<SessionId | undefined> {
|
||||||
const url = new URL(this.base);
|
const url = new URL(this.base);
|
||||||
url.pathname = `/api/v1/auth`
|
url.pathname = `/api/v1/auth`
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
@ -82,10 +75,11 @@ export class Client {
|
|||||||
headers: [['Content-Type', 'application/json']],
|
headers: [['Content-Type', 'application/json']],
|
||||||
body: JSON.stringify({ 'username': username, 'password': password })
|
body: JSON.stringify({ 'username': username, 'password': password })
|
||||||
});
|
});
|
||||||
return await response.json();
|
const session_id: SessionId = await response.json();
|
||||||
|
return session_id;
|
||||||
}
|
}
|
||||||
|
|
||||||
async profile(sessionId: SessionId, userId: UserId | undefined): Promise<UserOverview | undefined> {
|
async profile(sessionId: SessionId, userId: UserId | undefined): Promise<UserProfile | undefined> {
|
||||||
const url = new URL(this.base);
|
const url = new URL(this.base);
|
||||||
if (userId) {
|
if (userId) {
|
||||||
url.pathname = `/api/v1/user${userId}`
|
url.pathname = `/api/v1/user${userId}`
|
||||||
@ -102,10 +96,7 @@ export class Client {
|
|||||||
async health() {
|
async health() {
|
||||||
const url = new URL(this.base);
|
const url = new URL(this.base);
|
||||||
url.pathname = `/api/v1/health`;
|
url.pathname = `/api/v1/health`;
|
||||||
return fetch(url).then((response) => response.json()).then((response) => {
|
return fetch(url).then((response) => response.json());
|
||||||
console.log("health response: ", response);
|
|
||||||
return response;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,8 +0,0 @@
|
|||||||
.card {
|
|
||||||
border: var(--border-standard);
|
|
||||||
border-radius: var(--border-radius-standard);
|
|
||||||
box-shadow: var(--border-shadow-shallow);
|
|
||||||
padding: var(--padding-m);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
|||||||
import { PropsWithChildren } from 'react';
|
|
||||||
import './Card.css';
|
|
||||||
|
|
||||||
interface CardElementProps {
|
|
||||||
name?: string,
|
|
||||||
}
|
|
||||||
|
|
||||||
export const CardElement = ({ name, children }: PropsWithChildren<CardElementProps>) => (
|
|
||||||
<div className="card">
|
|
||||||
{name && <h1 className="card__title">{name}</h1> }
|
|
||||||
<div className="card__body">
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
|||||||
import { GameOverview } from "visions-types"
|
|
||||||
import { CardElement } from '../Card/Card';
|
|
||||||
|
|
||||||
|
|
||||||
export const GameOverviewElement = ({ name, gm, players }: GameOverview) => {
|
|
||||||
return (<CardElement name={name}>
|
|
||||||
<p><i>GM</i> {gm}</p>
|
|
||||||
<ul>
|
|
||||||
{players.map((player) => player)}
|
|
||||||
</ul>
|
|
||||||
</CardElement>)
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
.profile {
|
|
||||||
margin: var(--margin-s);
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile_columns {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile_columns > div {
|
|
||||||
width: 45%;
|
|
||||||
}
|
|
@ -1,21 +1,12 @@
|
|||||||
import { GameOverview, UserOverview } from 'visions-types';
|
import { UserProfile } from 'visions-types';
|
||||||
import { CardElement, GameOverviewElement, UserManagementElement } from '..';
|
|
||||||
import './Profile.css';
|
|
||||||
|
|
||||||
interface ProfileProps {
|
export const ProfileElement = ({ name, games, is_admin }: UserProfile) => {
|
||||||
profile: UserOverview,
|
const adminNote = is_admin ? <div> <i>Note: this user is an admin</i> </div> : <></>;
|
||||||
games: GameOverview[],
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ProfileElement = ({ profile, games }: ProfileProps) => {
|
return (
|
||||||
const adminNote = profile.isAdmin ? <div> <i>Note: this user is an admin</i> </div> : <></>;
|
<div className="card">
|
||||||
|
<h1>{name}</h1>
|
||||||
return (<div className="profile">
|
<div>Games: {games.map((game) => <>{game.game_name} ({game.game_type})</>).join(', ')}</div>
|
||||||
<CardElement name={profile.name}>
|
|
||||||
<div>Games: {games.map((game) => {
|
|
||||||
return <span key={game.id}>{game.name} ({game.type})</span>;
|
|
||||||
}) }</div>
|
|
||||||
{adminNote}
|
{adminNote}
|
||||||
</CardElement>
|
</div>)
|
||||||
</div>)
|
|
||||||
}
|
}
|
||||||
|
@ -1,16 +0,0 @@
|
|||||||
import { UserOverview } from "visions-types"
|
|
||||||
import { CardElement } from ".."
|
|
||||||
|
|
||||||
interface UserManagementProps {
|
|
||||||
users: UserOverview[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export const UserManagementElement = ({ users }: UserManagementProps ) => {
|
|
||||||
return (
|
|
||||||
<CardElement>
|
|
||||||
<ul>
|
|
||||||
{users.map((user) => <li key={user.id}>{user.name}</li>)}
|
|
||||||
</ul>
|
|
||||||
</CardElement>
|
|
||||||
)
|
|
||||||
}
|
|
@ -1,9 +1,6 @@
|
|||||||
import { CardElement } from './Card/Card'
|
|
||||||
import { GameOverviewElement } from './GameOverview/GameOverview'
|
|
||||||
import { ProfileElement } from './Profile/Profile'
|
import { ProfileElement } from './Profile/Profile'
|
||||||
import { SimpleGuage } from './Guages/SimpleGuage'
|
import { SimpleGuage } from './Guages/SimpleGuage'
|
||||||
import { ThumbnailElement } from './Thumbnail/Thumbnail'
|
import { ThumbnailElement } from './Thumbnail/Thumbnail'
|
||||||
import { TabletopElement } from './Tabletop/Tabletop'
|
import { TabletopElement } from './Tabletop/Tabletop'
|
||||||
import { UserManagementElement } from './UserManagement/UserManagement'
|
|
||||||
|
|
||||||
export { CardElement, GameOverviewElement, UserManagementElement, ProfileElement, ThumbnailElement, TabletopElement, SimpleGuage }
|
export { ProfileElement, ThumbnailElement, TabletopElement, SimpleGuage }
|
||||||
|
@ -6,3 +6,10 @@
|
|||||||
--margin-s: 4px;
|
--margin-s: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
border: var(--border-standard);
|
||||||
|
border-radius: var(--border-radius-standard);
|
||||||
|
box-shadow: var(--border-shadow-shallow);
|
||||||
|
padding: var(--padding-m);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@ import { SessionId, Status, Tabletop } from "visions-types";
|
|||||||
import { Client } from "../../client";
|
import { Client } from "../../client";
|
||||||
import { assertNever } from "../../utils";
|
import { assertNever } from "../../utils";
|
||||||
|
|
||||||
type AuthState = { type: "Unauthed" } | { type: "Authed", sessionId: string } | { type: "PasswordReset", sessionId: string };
|
type AuthState = { type: "NoAdmin" } | { type: "Unauthed" } | { type: "Authed", sessionId: string };
|
||||||
|
|
||||||
export enum LoadingState {
|
export enum LoadingState {
|
||||||
Loading,
|
Loading,
|
||||||
@ -21,7 +21,7 @@ type Action = { type: "SetAuthState", content: AuthState };
|
|||||||
const initialState = (): AppState => {
|
const initialState = (): AppState => {
|
||||||
let state: AppState = {
|
let state: AppState = {
|
||||||
state: LoadingState.Ready,
|
state: LoadingState.Ready,
|
||||||
auth: { type: "Unauthed" },
|
auth: { type: "NoAdmin" },
|
||||||
tabletop: { backgroundColor: { red: 0, green: 0, blue: 0 }, backgroundImage: undefined },
|
tabletop: { backgroundColor: { red: 0, green: 0, blue: 0 }, backgroundImage: undefined },
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,7 +36,6 @@ const initialState = (): AppState => {
|
|||||||
const stateReducer = (state: AppState, action: Action): AppState => {
|
const stateReducer = (state: AppState, action: Action): AppState => {
|
||||||
switch (action.type) {
|
switch (action.type) {
|
||||||
case "SetAuthState": {
|
case "SetAuthState": {
|
||||||
console.log("setReducer: ", action);
|
|
||||||
return { ...state, auth: action.content }
|
return { ...state, auth: action.content }
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
@ -48,13 +47,11 @@ const stateReducer = (state: AppState, action: Action): AppState => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const authState = (state: AppState): AuthState => state.auth
|
|
||||||
|
|
||||||
export const getSessionId = (state: AppState): SessionId | undefined => {
|
export const getSessionId = (state: AppState): SessionId | undefined => {
|
||||||
switch (state.auth.type) {
|
switch (state.auth.type) {
|
||||||
|
case "NoAdmin": return undefined
|
||||||
case "Unauthed": return undefined
|
case "Unauthed": return undefined
|
||||||
case "Authed": return state.auth.sessionId
|
case "Authed": return state.auth.sessionId
|
||||||
case "PasswordReset": return state.auth.sessionId
|
|
||||||
default: {
|
default: {
|
||||||
assertNever(state.auth)
|
assertNever(state.auth)
|
||||||
return undefined
|
return undefined
|
||||||
@ -71,38 +68,30 @@ class StateManager {
|
|||||||
this.dispatch = dispatch;
|
this.dispatch = dispatch;
|
||||||
}
|
}
|
||||||
|
|
||||||
async setPassword(password1: string, password2: string) {
|
async status() {
|
||||||
if (!this.client || !this.dispatch) return;
|
if (!this.client || !this.dispatch) return;
|
||||||
|
|
||||||
await this.client.setPassword(password1, password2);
|
const { admin_enabled } = await this.client.health();
|
||||||
|
if (!admin_enabled) {
|
||||||
|
this.dispatch({ type: "SetAuthState", content: { type: "NoAdmin" } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async setAdminPassword(password: string) {
|
||||||
|
if (!this.client || !this.dispatch) return;
|
||||||
|
|
||||||
|
await this.client.setAdminPassword(password);
|
||||||
|
await this.status();
|
||||||
}
|
}
|
||||||
|
|
||||||
async auth(username: string, password: string) {
|
async auth(username: string, password: string) {
|
||||||
if (!this.client || !this.dispatch) return;
|
if (!this.client || !this.dispatch) return;
|
||||||
|
|
||||||
let authResponse = await this.client.auth(username, password);
|
let sessionId = await this.client.auth(username, password);
|
||||||
switch (authResponse.type) {
|
|
||||||
case "Success": {
|
|
||||||
window.localStorage.setItem("sessionId", authResponse.content);
|
|
||||||
this.dispatch({ type: "SetAuthState", content: { type: "Authed", sessionId: authResponse.content } });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "PasswordReset": {
|
|
||||||
window.localStorage.setItem("sessionId", authResponse.content);
|
|
||||||
this.dispatch({ type: "SetAuthState", content: { type: "PasswordReset", sessionId: authResponse.content } });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "Locked": {
|
|
||||||
this.dispatch({ type: "SetAuthState", content: { type: "Unauthed" } });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/*
|
|
||||||
if (sessionId) {
|
if (sessionId) {
|
||||||
window.localStorage.setItem("sessionId", sessionId);
|
window.localStorage.setItem("sessionId", sessionId);
|
||||||
this.dispatch({ type: "SetAuthState", content: { type: "Authed", sessionId } });
|
this.dispatch({ type: "SetAuthState", content: { type: "Authed", sessionId } });
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,6 +104,10 @@ export const StateProvider = ({ client, children }: PropsWithChildren<StateProvi
|
|||||||
|
|
||||||
const stateManager = useRef(new StateManager(client, dispatch));
|
const stateManager = useRef(new StateManager(client, dispatch));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
stateManager.current.status();
|
||||||
|
}, [stateManager]);
|
||||||
|
|
||||||
return <StateContext.Provider value={[state, stateManager.current]}>
|
return <StateContext.Provider value={[state, stateManager.current]}>
|
||||||
{children}
|
{children}
|
||||||
</StateContext.Provider>;
|
</StateContext.Provider>;
|
||||||
|
@ -7,27 +7,10 @@ interface UserRowProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const UserRow = ({ user }: UserRowProps) => {
|
const UserRow = ({ user }: UserRowProps) => {
|
||||||
let accountState = "Normal";
|
|
||||||
|
|
||||||
switch (user.state.type) {
|
|
||||||
case "Normal": {
|
|
||||||
accountState = "Normal";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "PasswordReset": {
|
|
||||||
accountState = `PasswordReset until ${user.state.content}`;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "Locked": {
|
|
||||||
accountState = "Locked";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (<tr>
|
return (<tr>
|
||||||
<td> {user.name} </td>
|
<td> {user.name} </td>
|
||||||
<td> {user.admin && "admin"} </td>
|
<td> {user.admin && "admin"} </td>
|
||||||
<td> {accountState} </td>
|
<td> {user.enabled && "enabled"} </td>
|
||||||
</tr>);
|
</tr>);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -49,7 +32,7 @@ export const Admin = ({ client }: AdminProps) => {
|
|||||||
const [users, setUsers] = useState<Array<User>>([]);
|
const [users, setUsers] = useState<Array<User>>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
client.users("aoeu").then((u) => {
|
client.users().then((u) => {
|
||||||
console.log(u);
|
console.log(u);
|
||||||
setUsers(u);
|
setUsers(u);
|
||||||
});
|
});
|
||||||
|
@ -4,36 +4,43 @@ import { assertNever } from '../../utils';
|
|||||||
import './Authentication.css';
|
import './Authentication.css';
|
||||||
|
|
||||||
interface AuthenticationProps {
|
interface AuthenticationProps {
|
||||||
onSetPassword: (password1: string, password2: string) => void;
|
onAdminPassword: (password: string) => void;
|
||||||
onAuth: (username: string, password: string) => void;
|
onAuth: (username: string, password: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Authentication = ({ onSetPassword, onAuth, children }: PropsWithChildren<AuthenticationProps>) => {
|
export const Authentication = ({ onAdminPassword, onAuth, children }: PropsWithChildren<AuthenticationProps>) => {
|
||||||
// No admin password set: prompt for the admin password
|
// No admin password set: prompt for the admin password
|
||||||
// Password set, nobody logged in: prompt for login
|
// Password set, nobody logged in: prompt for login
|
||||||
// User logged in: show the children
|
// User logged in: show the children
|
||||||
|
|
||||||
let [userField, setUserField] = useState<string>("");
|
let [userField, setUserField] = useState<string>("");
|
||||||
let [pwField1, setPwField1] = useState<string>("");
|
let [pwField, setPwField] = useState<string>("");
|
||||||
let [pwField2, setPwField2] = useState<string>("");
|
|
||||||
let [state, _] = useContext(StateContext);
|
let [state, _] = useContext(StateContext);
|
||||||
|
|
||||||
console.log("Authentication component", state.state);
|
|
||||||
|
|
||||||
switch (state.state) {
|
switch (state.state) {
|
||||||
case LoadingState.Loading: {
|
case LoadingState.Loading: {
|
||||||
return <div>Loading</div>
|
return <div>Loading</div>
|
||||||
}
|
}
|
||||||
case LoadingState.Ready: {
|
case LoadingState.Ready: {
|
||||||
switch (state.auth.type) {
|
switch (state.auth.type) {
|
||||||
|
case "NoAdmin": {
|
||||||
|
return <div className="auth">
|
||||||
|
<div className="card">
|
||||||
|
<h1> Welcome to your new Visions VTT Instance </h1>
|
||||||
|
<p> Set your admin password: </p>
|
||||||
|
<input type="password" placeholder="Password" onChange={(evt) => setPwField(evt.target.value)} />
|
||||||
|
<input type="submit" value="Submit" onClick={() => onAdminPassword(pwField)} />
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
case "Unauthed": {
|
case "Unauthed": {
|
||||||
return <div className="auth card">
|
return <div className="auth card">
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<h1> Welcome to Visions VTT </h1>
|
<h1> Welcome to Visions VTT </h1>
|
||||||
<div className="auth__input-line">
|
<div className="auth__input-line">
|
||||||
<input type="text" placeholder="Username" onChange={(evt) => setUserField(evt.target.value)} />
|
<input type="text" placeholder="Username" onChange={(evt) => setUserField(evt.target.value)} />
|
||||||
<input type="password" placeholder="Password" onChange={(evt) => setPwField1(evt.target.value)} />
|
<input type="password" placeholder="Password" onChange={(evt) => setPwField(evt.target.value)} />
|
||||||
<input type="submit" value="Sign in" onClick={() => onAuth(userField, pwField1)} />
|
<input type="submit" value="Sign in" onClick={() => onAuth(userField, pwField)} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>;
|
</div>;
|
||||||
@ -41,17 +48,6 @@ export const Authentication = ({ onSetPassword, onAuth, children }: PropsWithChi
|
|||||||
case "Authed": {
|
case "Authed": {
|
||||||
return <div> {children} </div>;
|
return <div> {children} </div>;
|
||||||
}
|
}
|
||||||
case "PasswordReset": {
|
|
||||||
return <div className="auth">
|
|
||||||
<div className="card">
|
|
||||||
<h1> Password Reset </h1>
|
|
||||||
<p> Your password currently requires a reset. </p>
|
|
||||||
<input type="password" placeholder="Password" onChange={(evt) => setPwField1(evt.target.value)} />
|
|
||||||
<input type="password" placeholder="Retype your Password" onChange={(evt) => setPwField2(evt.target.value)} />
|
|
||||||
<input type="submit" value="Submit" onClick={() => onSetPassword(pwField1, pwField2)} />
|
|
||||||
</div>
|
|
||||||
</div>;
|
|
||||||
}
|
|
||||||
default: {
|
default: {
|
||||||
assertNever(state.auth);
|
assertNever(state.auth);
|
||||||
return <div></div>;
|
return <div></div>;
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { useContext, useEffect, useState } from 'react';
|
import { useContext, useEffect, useState } from 'react';
|
||||||
import { UserOverview } from 'visions-types';
|
import { UserProfile } from 'visions-types';
|
||||||
import { Client } from '../../client';
|
import { Client } from '../../client';
|
||||||
import { ProfileElement } from '../../components';
|
import { ProfileElement } from '../../components';
|
||||||
import { getSessionId, StateContext, StateProvider } from '../../providers/StateProvider/StateProvider';
|
import { getSessionId, StateContext, StateProvider } from '../../providers/StateProvider/StateProvider';
|
||||||
@ -10,20 +10,19 @@ interface MainProps {
|
|||||||
|
|
||||||
export const MainView = ({ client }: MainProps) => {
|
export const MainView = ({ client }: MainProps) => {
|
||||||
const [state, _manager] = useContext(StateContext)
|
const [state, _manager] = useContext(StateContext)
|
||||||
const [profile, setProfile] = useState<UserOverview | undefined>(undefined)
|
const [profile, setProfile] = useState<UserProfile | undefined>(undefined)
|
||||||
const [users, setUsers] = useState<UserOverview[]>([])
|
|
||||||
|
|
||||||
const sessionId = getSessionId(state)
|
const sessionId = getSessionId(state)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (sessionId) {
|
if (sessionId) {
|
||||||
client.profile(sessionId, undefined).then((profile) => setProfile(profile))
|
client.profile(sessionId, undefined).then((profile) => setProfile(profile))
|
||||||
client.users(sessionId).then((users) => setUsers(users))
|
|
||||||
}
|
}
|
||||||
}, [sessionId, client])
|
}, [sessionId, client])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{profile && <ProfileElement profile={profile} games={[]} />}
|
<div>Session ID: {sessionId}</div>
|
||||||
|
{profile && <ProfileElement {...profile} />}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
8
visions/visions-types/package-lock.json
generated
8
visions/visions-types/package-lock.json
generated
@ -9,13 +9,13 @@
|
|||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"typescript": "^5.7.3"
|
"typescript": "^5.7.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/typescript": {
|
"node_modules/typescript": {
|
||||||
"version": "5.7.3",
|
"version": "5.7.2",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz",
|
||||||
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
|
"integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==",
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
|
@ -9,6 +9,6 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"typescript": "^5.7.3"
|
"typescript": "^5.7.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user