Adds the ability to add games with suggestions from known games.
This commit is contained in:
42
backend/Cargo.lock
generated
42
backend/Cargo.lock
generated
@@ -342,10 +342,12 @@ version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b28135ecf6b7d446b43e27e225622a038cc4e2930a1022f51cdb97ada19b8e4d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"byteorder",
|
||||
"diesel_derives",
|
||||
"libsqlite3-sys",
|
||||
"pq-sys",
|
||||
"r2d2",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -583,7 +585,6 @@ dependencies = [
|
||||
"diesel-derive-enum",
|
||||
"diesel_migrations",
|
||||
"jsonwebtoken",
|
||||
"libsqlite3-sys",
|
||||
"local-ip-address",
|
||||
"password-hash",
|
||||
"rand_core",
|
||||
@@ -592,6 +593,7 @@ dependencies = [
|
||||
"rocket_dyn_templates",
|
||||
"rocket_sync_db_pools",
|
||||
"serde",
|
||||
"uuid",
|
||||
"validator",
|
||||
]
|
||||
|
||||
@@ -913,17 +915,6 @@ version = "0.2.121"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efaa7b300f3b5fe8eb6bf21ce3895e1751d9665086af2d64b42f19701015ff4f"
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e704a02bcaecd4a08b93a23f6be59d0bd79cd161e0963e9499165a0a35df7bd"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "local-ip-address"
|
||||
version = "0.4.4"
|
||||
@@ -1392,12 +1383,6 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58893f751c9b0412871a09abd62ecd2a00298c6c83befa223ef98c52aef40cbe"
|
||||
|
||||
[[package]]
|
||||
name = "polyval"
|
||||
version = "0.5.3"
|
||||
@@ -1416,6 +1401,15 @@ version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
|
||||
|
||||
[[package]]
|
||||
name = "pq-sys"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ac25eee5a0582f45a67e837e350d784e7003bd29a5f460796772061ca49ffda"
|
||||
dependencies = [
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error"
|
||||
version = "1.0.4"
|
||||
@@ -2274,6 +2268,16 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "validator"
|
||||
version = "0.14.0"
|
||||
|
||||
@@ -8,9 +8,8 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
rocket = { version = "0.5.0-rc.2", features = ["default", "json"] }
|
||||
libsqlite3-sys = { version = ">=0.8.0, <0.19.0", features = ["bundled"] }
|
||||
rocket_sync_db_pools = { version = "0.1.0-rc.2", features = ["diesel_sqlite_pool"] }
|
||||
diesel = { version = "1.4.8", features = ["sqlite"] }
|
||||
rocket_sync_db_pools = { version = "0.1.0-rc.2", features = ["diesel_postgres_pool"] }
|
||||
diesel = {version = "1.4.8", features = ["uuidv07", "r2d2", "postgres"]}
|
||||
diesel_migrations = "1.4.0"
|
||||
rocket_dyn_templates = { version = "0.1.0-rc.2", features = ["handlebars"] }
|
||||
chrono = "0.4.19"
|
||||
@@ -18,8 +17,9 @@ serde = "1.0.136"
|
||||
password-hash = "0.4"
|
||||
argon2 = "0.4"
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
diesel-derive-enum = { version = "1.1", features = ["sqlite"] }
|
||||
diesel-derive-enum = { version = "1.1", features = ["postgres"] }
|
||||
jsonwebtoken = "8.1"
|
||||
validator = { version = "0.14", features = ["derive"] }
|
||||
rocket_cors = "0.6.0-alpha1"
|
||||
local-ip-address = "0.4"
|
||||
uuid = { version = "0.8.2", features = ["v4", "serde"] }
|
||||
@@ -1,12 +1,12 @@
|
||||
-- Your SQL goes here
|
||||
|
||||
CREATE TABLE gamenight (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
game text TEXT NOT NULL,
|
||||
datetime TEXT NOT NULL
|
||||
id UUID NOT NULL PRIMARY KEY,
|
||||
name VARCHAR NOT NULL,
|
||||
datetime VARCHAR NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE known_games (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
game TEXT UNIQUE NOT NULL
|
||||
id UUID NOT NULL PRIMARY KEY,
|
||||
name VARCHAR UNIQUE NOT NULL
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
|
||||
drop table pwd;
|
||||
drop table user;
|
||||
drop table users;
|
||||
@@ -1,19 +1,26 @@
|
||||
CREATE TABLE user (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
email TEXT UNIQUE NOT NULL,
|
||||
role TEXT NOT NULL
|
||||
CREATE TABLE users (
|
||||
id UUID NOT NULL PRIMARY KEY,
|
||||
username VARCHAR UNIQUE NOT NULL,
|
||||
email VARCHAR UNIQUE NOT NULL,
|
||||
role VARCHAR NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE pwd (
|
||||
user_id INTEGER NOT NULL PRIMARY KEY,
|
||||
password TEXT NOT NULL,
|
||||
CONSTRAINT FK_UserId FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE
|
||||
user_id UUID NOT NULL PRIMARY KEY,
|
||||
password VARCHAR NOT NULL,
|
||||
CONSTRAINT FK_UserId FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
--Initialize default admin user, with password "gamenight!"
|
||||
INSERT INTO user (id, username, role)
|
||||
values(-1, 'admin', 'admin');
|
||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||
DO $$
|
||||
DECLARE
|
||||
admin_uuid uuid = uuid_generate_v4();
|
||||
BEGIN
|
||||
INSERT INTO users (id, username, email, role)
|
||||
values(admin_uuid, 'admin', '', 'admin');
|
||||
|
||||
insert INTO pwd (user_id, password)
|
||||
values(admin_uuid, '$argon2id$v=19$m=4096,t=3,p=1$zEdUjCAnZqd8DziYWzlFHw$YBLQhKvYIZBY43B8zM6hyBvLKuqTeh0EM5pKOfbWQSI');
|
||||
END $$;
|
||||
|
||||
insert INTO pwd (id, pwd)
|
||||
values(-1, '$argon2id$v=19$m=4096,t=3,p=1$zEdUjCAnZqd8DziYWzlFHw$YBLQhKvYIZBY43B8zM6hyBvLKuqTeh0EM5pKOfbWQSI');
|
||||
@@ -1,19 +1,19 @@
|
||||
ALTER TABLE gamenight RENAME TO _gamenight_old;
|
||||
|
||||
CREATE TABLE gamenight (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
game text TEXT NOT NULL,
|
||||
datetime TEXT NOT NULL,
|
||||
owner_id INTEGER NOT NULL,
|
||||
CONSTRAINT FK_OwnerId FOREIGN KEY (owner_id) REFERENCES user(id) ON DELETE CASCADE
|
||||
id UUID NOT NULL PRIMARY KEY,
|
||||
name VARCHAR NOT NULL,
|
||||
datetime VARCHAR NOT NULL,
|
||||
owner_id UUID NOT NULL,
|
||||
CONSTRAINT FK_OwnerId FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
PRAGMA foreign_keys=off;
|
||||
SET session_replication_role = 'replica';
|
||||
|
||||
INSERT INTO gamenight (id, game, datetime, owner_id)
|
||||
select id, game, datetime, -1
|
||||
INSERT INTO gamenight (id, name, datetime, owner_id)
|
||||
select id, name, datetime, '00000000-0000-0000-0000-000000000000'
|
||||
FROM _gamenight_old;
|
||||
|
||||
drop table _gamenight_old;
|
||||
|
||||
PRAGMA foreign_keys=on;
|
||||
SET session_replication_role = 'origin';
|
||||
@@ -0,0 +1,3 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
|
||||
drop table gamenight_gamelist;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Your SQL goes here
|
||||
|
||||
create table gamenight_gamelist (
|
||||
gamenight_id UUID NOT NULL,
|
||||
game_id UUID NOT NULL,
|
||||
CONSTRAINT FK_gamenight_id FOREIGN KEY (gamenight_id) REFERENCES gamenight(id) ON DELETE CASCADE,
|
||||
CONSTRAINT FK_game_id FOREIGN KEY (game_id) REFERENCES known_games(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY(gamenight_id, game_id)
|
||||
);
|
||||
@@ -1,3 +1,4 @@
|
||||
use uuid::Uuid;
|
||||
use crate::schema;
|
||||
use crate::schema::DbConn;
|
||||
use crate::AppConfig;
|
||||
@@ -40,6 +41,8 @@ struct ApiResponse {
|
||||
user: Option<UserWithToken>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
gamenights: Option<Vec<schema::GameNight>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
games: Option<Vec<schema::Game>>,
|
||||
}
|
||||
|
||||
impl ApiResponse {
|
||||
@@ -51,6 +54,7 @@ impl ApiResponse {
|
||||
message: None,
|
||||
user: None,
|
||||
gamenights: None,
|
||||
games: None,
|
||||
};
|
||||
|
||||
fn error(message: String) -> Self {
|
||||
@@ -59,6 +63,7 @@ impl ApiResponse {
|
||||
message: Some(Cow::Owned(message)),
|
||||
user: None,
|
||||
gamenights: None,
|
||||
games: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +76,7 @@ impl ApiResponse {
|
||||
jwt: jwt
|
||||
}),
|
||||
gamenights: None,
|
||||
games: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +86,17 @@ impl ApiResponse {
|
||||
message: None,
|
||||
user: None,
|
||||
gamenights: Some(gamenights),
|
||||
games: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn games_response(games: Vec<schema::Game>) -> Self {
|
||||
Self {
|
||||
result: Self::SUCCES_RESULT,
|
||||
message: None,
|
||||
user: None,
|
||||
gamenights: None,
|
||||
games: Some(games),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,27 +160,55 @@ pub async fn gamenights_unauthorized() -> ApiResponseVariant {
|
||||
ApiResponseVariant::Status(Status::Unauthorized)
|
||||
}
|
||||
|
||||
#[post("/gamenight", format = "application/json", data = "<gamenight_json>")]
|
||||
pub async fn gamenight_post_json(
|
||||
conn: DbConn,
|
||||
user: schema::User,
|
||||
gamenight_json: Json<schema::GameNightNoId>,
|
||||
) -> ApiResponseVariant {
|
||||
let mut gamenight = gamenight_json.into_inner();
|
||||
gamenight.owner_id = Some(user.id);
|
||||
match schema::insert_gamenight(conn, gamenight).await {
|
||||
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
|
||||
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct GameNightInput {
|
||||
pub name: String,
|
||||
pub datetime: String,
|
||||
pub owner_id: Option<Uuid>,
|
||||
pub game_list: Vec<schema::Game>,
|
||||
}
|
||||
|
||||
impl Into<schema::GameNight> for GameNightInput {
|
||||
|
||||
fn into(self) -> schema::GameNight {
|
||||
schema::GameNight {
|
||||
id: Uuid::new_v4(),
|
||||
name: self.name,
|
||||
datetime: self.datetime,
|
||||
owner_id: self.owner_id.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/gamenight", rank = 2)]
|
||||
pub async fn gamenight_post_json_unauthorized() -> ApiResponseVariant {
|
||||
#[post("/gamenights", format = "application/json", data = "<gamenight_json>")]
|
||||
pub async fn gamenights_post_json(
|
||||
conn: DbConn,
|
||||
user: schema::User,
|
||||
gamenight_json: Json<GameNightInput>,
|
||||
) -> ApiResponseVariant {
|
||||
let mut gamenight = gamenight_json.into_inner();
|
||||
gamenight.owner_id = Some(user.id);
|
||||
|
||||
let mut mutable_game_list = gamenight.game_list.clone();
|
||||
|
||||
match schema::add_unknown_games(&conn, &mut mutable_game_list).await {
|
||||
Ok(_) => (),
|
||||
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string())))
|
||||
};
|
||||
|
||||
match schema::insert_gamenight(conn, gamenight.clone().into(), mutable_game_list).await {
|
||||
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
|
||||
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string())))
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/gamenights", rank = 2)]
|
||||
pub async fn gamenights_post_json_unauthorized() -> ApiResponseVariant {
|
||||
ApiResponseVariant::Status(Status::Unauthorized)
|
||||
}
|
||||
|
||||
#[delete("/gamenight", format = "application/json", data = "<delete_gamenight_json>")]
|
||||
pub async fn gamenight_delete_json(
|
||||
#[delete("/gamenights", format = "application/json", data = "<delete_gamenight_json>")]
|
||||
pub async fn gamenights_delete_json(
|
||||
conn: DbConn,
|
||||
user: schema::User,
|
||||
delete_gamenight_json: Json<schema::DeleteGameNight>
|
||||
@@ -190,8 +235,8 @@ pub async fn gamenight_delete_json(
|
||||
}
|
||||
|
||||
|
||||
#[delete("/gamenight", rank = 2)]
|
||||
pub async fn gamenight_delete_json_unauthorized() -> ApiResponseVariant {
|
||||
#[delete("/gamenights", rank = 2)]
|
||||
pub async fn gamenights_delete_json_unauthorized() -> ApiResponseVariant {
|
||||
ApiResponseVariant::Status(Status::Unauthorized)
|
||||
}
|
||||
|
||||
@@ -221,7 +266,7 @@ pub async fn register_post_json(
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Claims {
|
||||
exp: i64,
|
||||
uid: i32,
|
||||
uid: Uuid,
|
||||
role: schema::Role,
|
||||
}
|
||||
|
||||
@@ -261,3 +306,17 @@ pub async fn login_post_json(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/games")]
|
||||
pub async fn games(conn: DbConn, _user: schema::User) -> ApiResponseVariant {
|
||||
match schema::get_all_known_games(&conn).await {
|
||||
Ok(games) => ApiResponseVariant::Value(json!(ApiResponse::games_response(games))),
|
||||
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/games", rank = 2)]
|
||||
pub async fn games_unauthorized() -> ApiResponseVariant {
|
||||
ApiResponseVariant::Status(Status::Unauthorized)
|
||||
}
|
||||
|
||||
|
||||
@@ -58,12 +58,14 @@ async fn rocket() -> _ {
|
||||
routes![
|
||||
api::gamenights,
|
||||
api::gamenights_unauthorized,
|
||||
api::gamenight_post_json,
|
||||
api::gamenight_post_json_unauthorized,
|
||||
api::gamenights_post_json,
|
||||
api::gamenights_post_json_unauthorized,
|
||||
api::register_post_json,
|
||||
api::login_post_json,
|
||||
api::gamenight_delete_json,
|
||||
api::gamenight_delete_json_unauthorized
|
||||
api::gamenights_delete_json,
|
||||
api::gamenights_delete_json_unauthorized,
|
||||
api::games,
|
||||
api::games_unauthorized,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::diesel::BoolExpressionMethods;
|
||||
use uuid::Uuid;
|
||||
use crate::diesel::Connection;
|
||||
use crate::diesel::ExpressionMethods;
|
||||
use crate::diesel::QueryDsl;
|
||||
@@ -9,7 +9,6 @@ use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHasher},
|
||||
Argon2,
|
||||
};
|
||||
use diesel::dsl::count;
|
||||
use diesel::RunQueryDsl;
|
||||
use diesel_derive_enum::DbEnum;
|
||||
use rocket::{Build, Rocket};
|
||||
@@ -19,10 +18,10 @@ use std::ops::Deref;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
#[database("gamenight_database")]
|
||||
pub struct DbConn(diesel::SqliteConnection);
|
||||
pub struct DbConn(diesel::PgConnection);
|
||||
|
||||
impl Deref for DbConn {
|
||||
type Target = rocket_sync_db_pools::Connection<DbConn, diesel::SqliteConnection>;
|
||||
type Target = rocket_sync_db_pools::Connection<DbConn, diesel::PgConnection>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
@@ -31,36 +30,40 @@ impl Deref for DbConn {
|
||||
|
||||
table! {
|
||||
gamenight (id) {
|
||||
id -> Integer,
|
||||
game -> Text,
|
||||
datetime -> Text,
|
||||
owner_id -> Integer,
|
||||
id -> diesel::sql_types::Uuid,
|
||||
name -> VarChar,
|
||||
datetime -> VarChar,
|
||||
owner_id -> Uuid,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
known_games (game) {
|
||||
id -> Integer,
|
||||
game -> Text,
|
||||
known_games (id) {
|
||||
id -> diesel::sql_types::Uuid,
|
||||
name -> VarChar,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
use diesel::sql_types::Integer;
|
||||
use diesel::sql_types::Text;
|
||||
use super::RoleMapping;
|
||||
user(id) {
|
||||
id -> Integer,
|
||||
username -> Text,
|
||||
email -> Text,
|
||||
role -> RoleMapping,
|
||||
users(id) {
|
||||
id -> diesel::sql_types::Uuid,
|
||||
username -> VarChar,
|
||||
email -> VarChar,
|
||||
role -> crate::schema::RoleMapping,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
pwd(user_id) {
|
||||
user_id -> Integer,
|
||||
password -> Text,
|
||||
user_id -> diesel::sql_types::Uuid,
|
||||
password -> VarChar,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
gamenight_gamelist(gamenight_id, game_id) {
|
||||
gamenight_id -> diesel::sql_types::Uuid,
|
||||
game_id -> diesel::sql_types::Uuid,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,21 +101,31 @@ pub async fn get_all_gamenights(conn: DbConn) -> Result<Vec<GameNight>, Database
|
||||
).await?)
|
||||
}
|
||||
|
||||
pub async fn insert_gamenight(conn: DbConn, new_gamenight: GameNightNoId) -> Result<usize, DatabaseError> {
|
||||
Ok(conn.run(|c|
|
||||
diesel::insert_into(gamenight::table)
|
||||
.values(new_gamenight)
|
||||
.execute(c)
|
||||
pub async fn insert_gamenight(conn: DbConn, new_gamenight: GameNight, game_list: Vec<Game>) -> Result<usize, DatabaseError> {
|
||||
Ok(conn.run(move |c|
|
||||
c.transaction(|| {
|
||||
diesel::insert_into(gamenight::table)
|
||||
.values(&new_gamenight)
|
||||
.execute(c)?;
|
||||
|
||||
let entries: Vec<GamenightGameListEntry> = game_list.iter().map(
|
||||
|g| GamenightGameListEntry { gamenight_id: new_gamenight.id.clone(), game_id: g.id.clone() }
|
||||
).collect();
|
||||
|
||||
diesel::insert_into(gamenight_gamelist::table)
|
||||
.values(entries)
|
||||
.execute(c)
|
||||
})
|
||||
).await?)
|
||||
}
|
||||
|
||||
pub async fn get_gamenight(conn: &DbConn, game_id: i32) -> Result<GameNight, DatabaseError> {
|
||||
pub async fn get_gamenight(conn: &DbConn, game_id: Uuid) -> Result<GameNight, DatabaseError> {
|
||||
Ok(conn.run(move |c|
|
||||
gamenight::table.find(game_id).first(c)
|
||||
).await?)
|
||||
}
|
||||
|
||||
pub async fn delete_gamenight(conn: &DbConn, game_id: i32) -> Result<usize, DatabaseError> {
|
||||
pub async fn delete_gamenight(conn: &DbConn, game_id: Uuid) -> Result<usize, DatabaseError> {
|
||||
Ok(conn.run(move |c|
|
||||
diesel::delete(
|
||||
gamenight::table.filter(
|
||||
@@ -131,25 +144,22 @@ pub async fn insert_user(conn: DbConn, new_user: Register) -> Result<usize, Data
|
||||
|
||||
Ok(conn.run(move |c| {
|
||||
c.transaction(|| {
|
||||
diesel::insert_into(user::table)
|
||||
.values((
|
||||
user::username.eq(&new_user.username),
|
||||
user::email.eq(&new_user.email),
|
||||
user::role.eq(Role::User),
|
||||
))
|
||||
let id = Uuid::new_v4();
|
||||
|
||||
diesel::insert_into(users::table)
|
||||
.values(User {
|
||||
id: id.clone(),
|
||||
username: new_user.username,
|
||||
email: new_user.email,
|
||||
role: Role::User
|
||||
})
|
||||
.execute(c)?;
|
||||
|
||||
let id: i32 = user::table
|
||||
.filter(
|
||||
user::username
|
||||
.eq(&new_user.username)
|
||||
.and(user::email.eq(&new_user.email)),
|
||||
)
|
||||
.select(user::id)
|
||||
.first(c)?;
|
||||
|
||||
diesel::insert_into(pwd::table)
|
||||
.values((pwd::user_id.eq(id), pwd::password.eq(&password_hash)))
|
||||
.values(Pwd {
|
||||
user_id: id,
|
||||
password: password_hash
|
||||
})
|
||||
.execute(c)
|
||||
})
|
||||
})
|
||||
@@ -158,10 +168,10 @@ pub async fn insert_user(conn: DbConn, new_user: Register) -> Result<usize, Data
|
||||
|
||||
pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseError> {
|
||||
conn.run(move |c| -> Result<LoginResult, DatabaseError> {
|
||||
let id: i32 = user::table
|
||||
.filter(user::username.eq(&login.username))
|
||||
.or_filter(user::email.eq(&login.username))
|
||||
.select(user::id)
|
||||
let id: Uuid = users::table
|
||||
.filter(users::username.eq(&login.username))
|
||||
.or_filter(users::email.eq(&login.username))
|
||||
.select(users::id)
|
||||
.first(c)?;
|
||||
|
||||
let pwd: String = pwd::table
|
||||
@@ -175,7 +185,7 @@ pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseEr
|
||||
.verify_password(&login.password.as_bytes(), &parsed_hash)
|
||||
.is_ok()
|
||||
{
|
||||
let user: User = user::table.find(id).first(c)?;
|
||||
let user: User = users::table.find(id).first(c)?;
|
||||
|
||||
Ok(LoginResult {
|
||||
result: true,
|
||||
@@ -191,19 +201,46 @@ pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseEr
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_user(conn: DbConn, id: i32) -> Result<User, DatabaseError> {
|
||||
Ok(conn.run(move |c| user::table.filter(user::id.eq(id)).first(c))
|
||||
pub async fn get_user(conn: DbConn, id: Uuid) -> Result<User, DatabaseError> {
|
||||
Ok(conn.run(move |c| users::table.filter(users::id.eq(id)).first(c))
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn get_all_known_games(conn: &DbConn) -> Result<Vec<Game>, DatabaseError> {
|
||||
Ok(conn.run(|c|
|
||||
known_games::table.load::<Game>(c)
|
||||
).await?)
|
||||
}
|
||||
|
||||
pub async fn add_game(conn: &DbConn, game: Game) -> Result<usize, DatabaseError> {
|
||||
Ok(conn.run(|c|
|
||||
diesel::insert_into(known_games::table)
|
||||
.values(game)
|
||||
.execute(c)
|
||||
|
||||
).await?)
|
||||
}
|
||||
|
||||
pub async fn add_unknown_games(conn: &DbConn, games: &mut Vec<Game>) -> Result<(), DatabaseError> {
|
||||
let all_games = get_all_known_games(conn).await?;
|
||||
for game in games.iter_mut() {
|
||||
if !all_games.iter().any(|g| g.name == game.name) {
|
||||
game.id = Uuid::new_v4();
|
||||
add_game(conn, game.clone()).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
pub fn unique_username(
|
||||
username: &String,
|
||||
conn: &diesel::SqliteConnection,
|
||||
conn: &diesel::PgConnection,
|
||||
) -> Result<(), ValidationError> {
|
||||
match user::table
|
||||
.select(count(user::username))
|
||||
.filter(user::username.eq(username))
|
||||
.execute(conn)
|
||||
match users::table
|
||||
.count()
|
||||
.filter(users::username.eq(username))
|
||||
.get_result(conn)
|
||||
{
|
||||
Ok(0) => Ok(()),
|
||||
Ok(_) => Err(ValidationError::new("User already exists")),
|
||||
@@ -213,12 +250,12 @@ pub fn unique_username(
|
||||
|
||||
pub fn unique_email(
|
||||
email: &String,
|
||||
conn: &diesel::SqliteConnection,
|
||||
conn: &diesel::PgConnection,
|
||||
) -> Result<(), ValidationError> {
|
||||
match user::table
|
||||
.select(count(user::email))
|
||||
.filter(user::email.eq(email))
|
||||
.execute(conn)
|
||||
match users::table
|
||||
.count()
|
||||
.filter(users::email.eq(email))
|
||||
.get_result(conn)
|
||||
{
|
||||
Ok(0) => Ok(()),
|
||||
Ok(_) => Err(ValidationError::new("email already exists")),
|
||||
@@ -249,57 +286,60 @@ pub enum Role {
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
|
||||
#[table_name = "user"]
|
||||
#[table_name = "users"]
|
||||
pub struct User {
|
||||
pub id: i32,
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub email: String,
|
||||
pub role: Role,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, FromForm, Insertable)]
|
||||
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
|
||||
#[table_name = "pwd"]
|
||||
struct Pwd {
|
||||
user_id: Uuid,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Queryable, Clone, Insertable)]
|
||||
#[table_name = "known_games"]
|
||||
pub struct GameNoId {
|
||||
pub game: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, FromForm, Queryable)]
|
||||
pub struct Game {
|
||||
pub id: i32,
|
||||
pub game: String,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Insertable)]
|
||||
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable)]
|
||||
#[table_name = "gamenight"]
|
||||
pub struct GameNightNoId {
|
||||
pub game: String,
|
||||
pub datetime: String,
|
||||
pub owner_id: Option<i32>
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, FromForm, Queryable)]
|
||||
pub struct GameNight {
|
||||
pub id: i32,
|
||||
pub game: String,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub datetime: String,
|
||||
pub owner_id: i32,
|
||||
pub owner_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, FromForm, Queryable)]
|
||||
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable)]
|
||||
#[table_name="gamenight_gamelist"]
|
||||
pub struct GamenightGameListEntry {
|
||||
pub gamenight_id: Uuid,
|
||||
pub game_id: Uuid
|
||||
}
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Queryable)]
|
||||
pub struct DeleteGameNight {
|
||||
pub game_id: i32,
|
||||
pub game_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Validate, Clone)]
|
||||
pub struct Register {
|
||||
#[validate(
|
||||
length(min = 1),
|
||||
custom(function = "unique_username", arg = "&'v_a diesel::SqliteConnection")
|
||||
custom(function = "unique_username", arg = "&'v_a diesel::PgConnection")
|
||||
)]
|
||||
pub username: String,
|
||||
#[validate(
|
||||
email,
|
||||
custom(function = "unique_email", arg = "&'v_a diesel::SqliteConnection")
|
||||
custom(function = "unique_email", arg = "&'v_a diesel::PgConnection")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(min = 10), must_match = "password_repeat")]
|
||||
|
||||
Reference in New Issue
Block a user