Adds the ability to add games with suggestions from known games.

This commit is contained in:
2022-05-27 20:53:12 +02:00
parent cc26aed9a5
commit 1a6ead4760
18 changed files with 1240 additions and 168 deletions

View File

@@ -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)
}

View File

@@ -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,
],
);

View File

@@ -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")]