Deleted the old Rust backend based on rocket.

This commit is contained in:
Dennis Brentjes 2025-05-02 23:06:38 +02:00
parent 6699dcf392
commit fce0ebd76b
30 changed files with 0 additions and 3887 deletions

4
backend/.gitignore vendored
View File

@ -1,4 +0,0 @@
/target
.vscode
App.toml
*.sqlite

View File

@ -1,8 +0,0 @@
#Copy this file over to Rocket.toml after changing all relevant values.
[default]
jwt_secret = "some really good secret"
[global.databases]
gamenight_database = { url = "gamenight.sqlite" }

2466
backend/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +0,0 @@
[package]
name = "gamenight"
version = "0.1.0"
authors = ["Dennis Brentjes <d.brentjes@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = { version = "0.5.0-rc.2", features = ["default", "json"] }
rocket_sync_db_pools = { version = "0.1.0-rc.2", features = ["diesel_postgres_pool"] }
rocket_dyn_templates = { version = "0.1.0-rc.2", features = ["handlebars"] }
diesel = {version = "1.4.8", features = ["uuidv07", "r2d2", "postgres", "chrono"]}
diesel_migrations = "1.4.0"
diesel-derive-enum = { version = "1.1", features = ["postgres"] }
chrono = {version = "0.4.19", features = ["serde"] }
serde = "1.0.136"
password-hash = "0.4"
argon2 = "0.4"
rand_core = { version = "0.6", features = ["std"] }
jsonwebtoken = "8.1"
validator = { version = "0.15", features = ["derive"] }
uuid = { version = "0.8.2", features = ["v4", "serde"] }
futures = "0.3.21"
rand = "0.8.5"
base64 = "0.13.0"

View File

@ -1,4 +0,0 @@
-- This file should undo anything in `up.sql`
drop table gamenight;
drop table known_games;

View File

@ -1,12 +0,0 @@
-- Your SQL goes here
CREATE TABLE gamenight (
id UUID NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL,
datetime VARCHAR NOT NULL
);
CREATE TABLE known_games (
id UUID NOT NULL PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL
);

View File

@ -1,4 +0,0 @@
-- This file should undo anything in `up.sql`
drop table pwd;
drop table users;

View File

@ -1,26 +0,0 @@
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 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!"
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 $$;

View File

@ -1,4 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE gamenight
DROP COLUMN owner_id;

View File

@ -1,19 +0,0 @@
ALTER TABLE gamenight RENAME TO _gamenight_old;
CREATE TABLE gamenight (
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
);
SET session_replication_role = 'replica';
INSERT INTO gamenight (id, name, datetime, owner_id)
select id, name, datetime, '00000000-0000-0000-0000-000000000000'
FROM _gamenight_old;
drop table _gamenight_old;
SET session_replication_role = 'origin';

View File

@ -1,3 +0,0 @@
-- This file should undo anything in `up.sql`
drop table gamenight_gamelist;

View File

@ -1,9 +0,0 @@
-- 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)
);

View File

@ -1,3 +0,0 @@
-- This file should undo anything in `up.sql`
drop table gamenight_participants;

View File

@ -1,9 +0,0 @@
-- Your SQL goes here
create table gamenight_participants (
gamenight_id UUID NOT NULL,
user_id UUID NOT NULL,
CONSTRAINT FK_gamenight_id FOREIGN KEY (gamenight_id) REFERENCES gamenight(id) ON DELETE CASCADE,
CONSTRAINT FK_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY(gamenight_id, user_id)
)

View File

@ -1,6 +0,0 @@
-- This file should undo anything in `up.sql`
drop table registration_tokens;
ALTER TABLE gamenight
ALTER datetime TYPE VARCHAR;

View File

@ -1,11 +0,0 @@
-- Your SQL goes here
create table registration_tokens (
id UUID PRIMARY KEY,
token CHARACTER(32) NOT NULL,
single_use BOOLEAN NOT NULL,
expires TIMESTAMPTZ
);
ALTER TABLE gamenight
ALTER datetime TYPE TIMESTAMPTZ using datetime::timestamp;

View File

@ -1,3 +0,0 @@
echo $JWT
curl -X GET -H "Authorization: Bearer ${JWT}" localhost:8000/api/gamenights

View File

@ -1 +0,0 @@
curl -X POST -H "Content-Type: application/json" -d '{"username": "a", "password": "c"}' localhost:8000/api/login

View File

@ -1 +0,0 @@
curl -X POST -H "Content-Type: application/json" -d '{"username": "roflin", "email": "user@example.com", "password": "oreokoekje123", "password_repeat": "oreokoekje123"}' localhost:8000/api/register

View File

@ -1,573 +0,0 @@
use crate::schema;
use crate::schema::admin::RegistrationToken;
use crate::schema::gamenight::*;
use crate::schema::users::*;
use crate::schema::DatabaseError;
use crate::schema::DbConn;
use crate::AppConfig;
use chrono::DateTime;
use chrono::Utc;
use futures::future::join_all;
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome, Request};
use rocket::serde::json::{json, Json, Value};
use rocket::State;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use uuid::Uuid;
use validator::ValidateArgs;
#[derive(Debug, Responder)]
pub enum ApiResponseVariant {
Status(Status),
Value(Value),
}
#[derive(Serialize, Deserialize, Debug)]
pub enum ApiData {
#[serde(rename = "user")]
User(UserWithToken),
#[serde(rename = "gamenights")]
Gamenights(Vec<GamenightOutput>),
#[serde(rename = "gamenight")]
Gamenight(GamenightOutput),
#[serde(rename = "games")]
Games(Vec<Game>),
#[serde(rename = "registration_tokens")]
RegistrationTokens(Vec<RegistrationToken>),
}
#[derive(Serialize, Deserialize, Debug)]
struct ApiResponse {
result: Cow<'static, str>,
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<Cow<'static, str>>,
#[serde(flatten, skip_serializing_if = "Option::is_none")]
data: Option<ApiData>,
}
impl ApiResponse {
const SUCCES_RESULT: Cow<'static, str> = Cow::Borrowed("Ok");
const FAILURE_RESULT: Cow<'static, str> = Cow::Borrowed("Failure");
const SUCCES: Self = Self {
result: Self::SUCCES_RESULT,
message: None,
data: None,
};
fn error(message: String) -> Self {
Self {
result: Self::FAILURE_RESULT,
message: Some(Cow::Owned(message)),
data: None,
}
}
fn login_response(user: User, jwt: String) -> Self {
Self {
result: Self::SUCCES_RESULT,
message: None,
data: Some(ApiData::User(UserWithToken {
user: user,
jwt: jwt,
})),
}
}
fn gamenights_response(gamenights: Vec<GamenightOutput>) -> Self {
Self {
result: Self::SUCCES_RESULT,
message: None,
data: Some(ApiData::Gamenights(gamenights)),
}
}
fn gamenight_response(gamenight: GamenightOutput) -> Self {
Self {
result: Self::SUCCES_RESULT,
message: None,
data: Some(ApiData::Gamenight(gamenight)),
}
}
fn games_response(games: Vec<Game>) -> Self {
Self {
result: Self::SUCCES_RESULT,
message: None,
data: Some(ApiData::Games(games)),
}
}
fn registration_tokens_response(tokens: Vec<RegistrationToken>) -> Self {
Self {
result: Self::SUCCES_RESULT,
message: None,
data: Some(ApiData::RegistrationTokens(tokens)),
}
}
}
#[derive(Debug)]
pub enum ApiError {
RequestError(String),
}
const AUTH_HEADER: &str = "Authorization";
const BEARER: &str = "Bearer ";
#[rocket::async_trait]
impl<'r> FromRequest<'r> for User {
type Error = ApiError;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let header = match req.headers().get_one(AUTH_HEADER) {
Some(header) => header,
None => return Outcome::Forward(()),
};
if !header.starts_with(BEARER) {
return Outcome::Forward(());
};
let app_config = req.guard::<&State<AppConfig>>().await.unwrap().inner();
let jwt = header.trim_start_matches(BEARER).to_owned();
let token = match decode::<Claims>(
&jwt,
&DecodingKey::from_secret(app_config.jwt_secret.as_bytes()),
&Validation::default(),
) {
Ok(token) => token,
Err(_) => return Outcome::Forward(()),
};
let id = token.claims.uid;
let conn = req.guard::<DbConn>().await.unwrap();
return match get_user(conn, id).await {
Ok(o) => Outcome::Success(o),
Err(_) => Outcome::Forward(()),
};
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GamenightOutput {
#[serde(flatten)]
gamenight: Gamenight,
game_list: Vec<Game>,
participants: Vec<User>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GamenightUpdate {
action: String,
}
#[patch(
"/gamenights/<gamenight_id>",
format = "application/json",
data = "<patch_json>"
)]
pub async fn patch_gamenight(
conn: DbConn,
user: User,
gamenight_id: String,
patch_json: Json<GamenightUpdate>,
) -> ApiResponseVariant {
let uuid = Uuid::parse_str(&gamenight_id).unwrap();
let patch = patch_json.into_inner();
match patch.action.as_str() {
"RemoveParticipant" => {
let entry = GamenightParticipantsEntry {
gamenight_id: uuid,
user_id: user.id,
};
match remove_participant(&conn, entry).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
"AddParticipant" => {
let entry = GamenightParticipantsEntry {
gamenight_id: uuid,
user_id: user.id,
};
match add_participant(&conn, entry).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
_ => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
}
}
#[get("/gamenights/<gamenight_id>")]
pub async fn gamenight(conn: DbConn, _user: User, gamenight_id: String) -> ApiResponseVariant {
let uuid = Uuid::parse_str(&gamenight_id).unwrap();
let gamenight = match get_gamenight(&conn, uuid).await {
Ok(result) => result,
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
};
let games = match get_games_of_gamenight(&conn, uuid).await {
Ok(result) => result,
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
};
let participants = match load_participants(&conn, uuid).await {
Ok(result) => result,
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
};
let gamenight_output = GamenightOutput {
gamenight: gamenight,
game_list: games,
participants: participants,
};
return ApiResponseVariant::Value(json!(ApiResponse::gamenight_response(gamenight_output)));
}
#[get("/gamenights")]
pub async fn gamenights(conn: DbConn, _user: User) -> ApiResponseVariant {
let gamenights = match get_all_gamenights(&conn).await {
Ok(result) => result,
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
};
let conn_ref = &conn;
let game_results: Result<Vec<GamenightOutput>, DatabaseError> =
join_all(gamenights.iter().map(|gn| async move {
let games = get_games_of_gamenight(conn_ref, gn.id).await?;
let participants = load_participants(conn_ref, gn.id).await?;
Ok(GamenightOutput {
gamenight: gn.clone(),
game_list: games,
participants: participants,
})
}))
.await
.into_iter()
.collect();
match game_results {
Ok(result) => ApiResponseVariant::Value(json!(ApiResponse::gamenights_response(result))),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
#[get("/gamenights", rank = 2)]
pub async fn gamenights_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GamenightInput {
pub name: String,
pub datetime: DateTime<Utc>,
pub owner_id: Option<Uuid>,
pub game_list: Vec<Game>,
}
impl Into<Gamenight> for GamenightInput {
fn into(self) -> Gamenight {
Gamenight {
id: Uuid::new_v4(),
name: self.name,
datetime: self.datetime,
owner_id: self.owner_id.unwrap(),
}
}
}
#[post("/gamenights", format = "application/json", data = "<gamenight_json>")]
pub async fn gamenights_post_json(
conn: DbConn,
user: 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 add_unknown_games(&conn, &mut mutable_game_list).await {
Ok(_) => (),
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
};
let gamenight_id = match insert_gamenight(&conn, gamenight.clone().into(), mutable_game_list)
.await
{
Ok(id) => id,
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
};
let participant = GamenightParticipantsEntry {
gamenight_id: gamenight_id,
user_id: user.id,
};
match add_participant(&conn, participant).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(
"/gamenights",
format = "application/json",
data = "<delete_gamenight_json>"
)]
pub async fn gamenights_delete_json(
conn: DbConn,
user: User,
delete_gamenight_json: Json<DeleteGamenight>,
) -> ApiResponseVariant {
if user.role == Role::Admin {
if let Err(error) = delete_gamenight(&conn, delete_gamenight_json.game_id).await {
return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())));
}
return ApiResponseVariant::Value(json!(ApiResponse::SUCCES));
}
match get_gamenight(&conn, delete_gamenight_json.game_id).await {
Ok(gamenight) => {
if user.id == gamenight.owner_id {
if let Err(error) = delete_gamenight(&conn, delete_gamenight_json.game_id).await {
return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())));
}
return ApiResponseVariant::Value(json!(ApiResponse::SUCCES));
}
}
Err(error) => {
return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
}
}
ApiResponseVariant::Status(Status::Unauthorized)
}
#[delete("/gamenights", rank = 2)]
pub async fn gamenights_delete_json_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[post("/register", format = "application/json", data = "<register_json>")]
pub async fn register_post_json(conn: DbConn, register_json: Json<Register>) -> ApiResponseVariant {
let register = register_json.into_inner();
let register_clone = register.clone();
match conn
.run(move |c| register_clone.validate_args((c, c)))
.await
{
Ok(()) => (),
Err(error) => {
return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
}
}
match insert_user(conn, register).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
exp: i64,
uid: Uuid,
role: Role,
}
#[post("/login", format = "application/json", data = "<login_json>")]
pub async fn login_post_json(
conn: DbConn,
config: &State<AppConfig>,
login_json: Json<Login>,
) -> ApiResponseVariant {
match login(conn, login_json.into_inner()).await {
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
Ok(login_result) => {
if !login_result.result {
return ApiResponseVariant::Value(json!(ApiResponse::error(String::from(
"username and password didn't match"
))));
}
let user = login_result.user.unwrap();
let my_claims = Claims {
exp: Utc::now().timestamp() + chrono::Duration::days(7).num_seconds(),
uid: user.id,
role: user.role,
};
let secret = &config.inner().jwt_secret;
match encode(
&Header::default(),
&my_claims,
&EncodingKey::from_secret(secret.as_bytes()),
) {
Ok(token) => {
ApiResponseVariant::Value(json!(ApiResponse::login_response(user, token)))
}
Err(error) => {
ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
}
}
}
}
}
#[get("/games")]
pub async fn games(conn: DbConn, _user: User) -> ApiResponseVariant {
match 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)
}
#[get(
"/participants",
format = "application/json",
data = "<gamenight_id_json>"
)]
pub async fn get_participants(
conn: DbConn,
_user: User,
gamenight_id_json: Json<GamenightId>,
) -> ApiResponseVariant {
match load_participants(&conn, gamenight_id_json.into_inner().gamenight_id).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string()))),
}
}
#[get("/participants", rank = 2)]
pub async fn get_participants_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[post("/participants", format = "application/json", data = "<entry_json>")]
pub async fn post_participants(
conn: DbConn,
_user: User,
entry_json: Json<GamenightParticipantsEntry>,
) -> ApiResponseVariant {
match add_participant(&conn, entry_json.into_inner()).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string()))),
}
}
#[post("/participants", rank = 2)]
pub async fn post_participants_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[delete("/participants", format = "application/json", data = "<entry_json>")]
pub async fn delete_participants(
conn: DbConn,
_user: User,
entry_json: Json<GamenightParticipantsEntry>,
) -> ApiResponseVariant {
match remove_participant(&conn, entry_json.into_inner()).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string()))),
}
}
#[delete("/participants", rank = 2)]
pub async fn delete_participants_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[derive(Deserialize)]
pub struct RegistrationTokenData {
single_use: bool,
expires: Option<DateTime<Utc>>,
}
impl Into<RegistrationToken> for RegistrationTokenData {
fn into(self) -> RegistrationToken {
use rand::Rng;
let random_bytes = rand::thread_rng().gen::<[u8; 24]>();
RegistrationToken {
id: Uuid::new_v4(),
token: base64::encode_config(random_bytes, base64::URL_SAFE),
single_use: self.single_use,
expires: self.expires,
}
}
}
#[post(
"/admin/registration_tokens",
format = "application/json",
data = "<token_json>"
)]
pub async fn add_registration_token(
conn: DbConn,
user: User,
token_json: Json<RegistrationTokenData>,
) -> ApiResponseVariant {
if user.role != Role::Admin {
return ApiResponseVariant::Status(Status::Unauthorized);
}
match schema::admin::add_registration_token(&conn, token_json.into_inner().into()).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
#[post("/admin/registration_tokens", rank = 2)]
pub async fn add_registration_token_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[get("/admin/registration_tokens")]
pub async fn get_registration_tokens(conn: DbConn, user: User) -> ApiResponseVariant {
if user.role != Role::Admin {
return ApiResponseVariant::Status(Status::Unauthorized);
}
match schema::admin::get_all_registration_tokens(&conn).await {
Ok(results) => {
ApiResponseVariant::Value(json!(ApiResponse::registration_tokens_response(results)))
}
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
#[get("/admin/registration_tokens", rank = 2)]
pub async fn get_registration_tokens_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}
#[delete("/admin/registration_tokens/<gamenight_id>")]
pub async fn delete_registration_tokens(
conn: DbConn,
user: User,
gamenight_id: String,
) -> ApiResponseVariant {
if user.role != Role::Admin {
return ApiResponseVariant::Status(Status::Unauthorized);
}
let uuid = Uuid::parse_str(&gamenight_id).unwrap();
match schema::admin::delete_registration_token(&conn, uuid).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
#[delete("/admin/registration_tokens", rank = 2)]
pub async fn delete_registration_tokens_unauthorized() -> ApiResponseVariant {
ApiResponseVariant::Status(Status::Unauthorized)
}

View File

@ -1,81 +0,0 @@
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate diesel;
use rocket::{
fairing::AdHoc,
figment::{
providers::{Env, Format, Serialized, Toml},
Figment, Profile,
},
};
use rocket_dyn_templates::Template;
use serde::{Deserialize, Serialize};
mod api;
pub mod schema;
mod site;
#[derive(Debug, Deserialize, Serialize)]
pub struct AppConfig {
jwt_secret: String,
}
impl Default for AppConfig {
fn default() -> AppConfig {
AppConfig {
jwt_secret: String::from("secret"),
}
}
}
#[launch]
async fn rocket() -> _ {
let figment = Figment::from(rocket::Config::default())
.merge(Serialized::defaults(AppConfig::default()))
.merge(Toml::file("App.toml").nested())
.merge(Env::prefixed("APP_").global())
.select(Profile::from_env_or("APP_PROFILE", "default"));
let rocket = rocket::custom(figment)
.attach(schema::DbConn::fairing())
.attach(Template::fairing())
.attach(site::CORS)
.attach(AdHoc::on_ignite("Run Migrations", schema::run_migrations))
.attach(AdHoc::config::<AppConfig>())
.mount("/", routes![site::index, site::files])
.mount(
"/api",
routes![
api::gamenight,
api::patch_gamenight,
api::gamenights,
api::gamenights_unauthorized,
api::gamenights_post_json,
api::gamenights_post_json_unauthorized,
api::register_post_json,
api::login_post_json,
api::gamenights_delete_json,
api::gamenights_delete_json_unauthorized,
api::games,
api::games_unauthorized,
api::get_participants,
api::get_participants_unauthorized,
api::post_participants,
api::post_participants_unauthorized,
api::delete_participants,
api::delete_participants_unauthorized,
api::add_registration_token,
api::add_registration_token_unauthorized,
api::get_registration_tokens,
api::get_registration_tokens_unauthorized,
api::delete_registration_tokens,
api::delete_registration_tokens_unauthorized,
],
);
rocket
}

View File

@ -1,54 +0,0 @@
use crate::schema::{DatabaseError, DbConn};
use chrono::DateTime;
use chrono::Utc;
use diesel::{QueryDsl, RunQueryDsl, ExpressionMethods};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
table! {
registration_tokens (id) {
id -> diesel::sql_types::Uuid,
token -> Char,
single_use -> Bool,
expires -> Nullable<Timestamptz>,
}
}
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
#[table_name = "registration_tokens"]
pub struct RegistrationToken {
pub id: Uuid,
pub token: String,
pub single_use: bool,
pub expires: Option<DateTime<Utc>>,
}
pub async fn get_all_registration_tokens(
conn: &DbConn,
) -> Result<Vec<RegistrationToken>, DatabaseError> {
Ok(conn
.run(|c| registration_tokens::table.load::<RegistrationToken>(c))
.await?)
}
pub async fn add_registration_token(
conn: &DbConn,
token: RegistrationToken,
) -> Result<usize, DatabaseError> {
Ok(conn
.run(|c| {
diesel::insert_into(registration_tokens::table)
.values(token)
.execute(c)
})
.await?)
}
pub async fn delete_registration_token(conn: &DbConn, id: Uuid) -> Result<usize, DatabaseError> {
Ok(conn
.run(move |c| {
diesel::delete(registration_tokens::table.filter(registration_tokens::id.eq(id)))
.execute(c)
})
.await?)
}

View File

@ -1,215 +0,0 @@
use crate::schema::users::{users, User};
use crate::schema::{DatabaseError, DbConn};
use chrono::{DateTime, Utc};
use diesel::{Connection, ExpressionMethods, QueryDsl, RunQueryDsl};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
table! {
gamenight (id) {
id -> diesel::sql_types::Uuid,
name -> VarChar,
datetime -> Timestamptz,
owner_id -> Uuid,
}
}
table! {
known_games (id) {
id -> diesel::sql_types::Uuid,
name -> VarChar,
}
}
table! {
gamenight_gamelist(gamenight_id, game_id) {
gamenight_id -> diesel::sql_types::Uuid,
game_id -> diesel::sql_types::Uuid,
}
}
table! {
gamenight_participants(gamenight_id, user_id) {
gamenight_id -> diesel::sql_types::Uuid,
user_id -> diesel::sql_types::Uuid,
}
}
#[derive(Serialize, Deserialize, Debug, Queryable, Clone, Insertable)]
#[table_name = "known_games"]
pub struct Game {
pub id: Uuid,
pub name: String,
}
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable, Clone)]
#[table_name = "gamenight"]
pub struct Gamenight {
pub id: Uuid,
pub name: String,
pub datetime: DateTime<Utc>,
pub owner_id: Uuid,
}
#[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, Insertable, Identifiable)]
#[table_name = "gamenight_participants"]
#[primary_key(gamenight_id, user_id)]
pub struct GamenightParticipantsEntry {
pub gamenight_id: Uuid,
pub user_id: Uuid,
}
#[derive(Serialize, Deserialize, Debug, Queryable)]
pub struct DeleteGamenight {
pub game_id: Uuid,
}
#[derive(Serialize, Deserialize, Debug, Queryable)]
pub struct GamenightId {
pub gamenight_id: Uuid,
}
pub async fn get_all_gamenights(conn: &DbConn) -> Result<Vec<Gamenight>, DatabaseError> {
Ok(conn.run(|c| gamenight::table.load::<Gamenight>(c)).await?)
}
pub async fn insert_gamenight(
conn: &DbConn,
new_gamenight: Gamenight,
game_list: Vec<Game>,
) -> Result<Uuid, DatabaseError> {
Ok(conn
.run(move |c| {
c.transaction::<_, DatabaseError, _>(|| {
let id: Uuid = diesel::insert_into(gamenight::table)
.values(&new_gamenight)
.returning(gamenight::id)
.get_result(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)?;
Ok(id)
})
})
.await?)
}
pub async fn get_gamenight(conn: &DbConn, gamenight_id: Uuid) -> Result<Gamenight, DatabaseError> {
Ok(conn
.run(move |c| gamenight::table.find(gamenight_id).first(c))
.await?)
}
pub async fn delete_gamenight(conn: &DbConn, game_id: Uuid) -> Result<usize, DatabaseError> {
Ok(conn
.run(move |c| diesel::delete(gamenight::table.filter(gamenight::id.eq(game_id))).execute(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 get_games_of_gamenight(
conn: &DbConn,
gamenight_id: Uuid,
) -> Result<Vec<Game>, DatabaseError> {
Ok(conn
.run::<_, Result<Vec<Game>, _>>(move |c| {
let linked_game_ids: Vec<GamenightGameListEntry> = gamenight_gamelist::table
.filter(gamenight_gamelist::gamenight_id.eq(gamenight_id))
.load::<GamenightGameListEntry>(c)?;
linked_game_ids
.iter()
.map(|l| {
known_games::table
.filter(known_games::id.eq(l.game_id))
.first::<Game>(c)
})
.collect()
})
.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 async fn load_participants(
conn: &DbConn,
gamenight_id: Uuid,
) -> Result<Vec<User>, DatabaseError> {
Ok(conn
.run::<_, Result<Vec<User>, _>>(move |c| {
let linked_participants = gamenight_participants::table
.filter(gamenight_participants::gamenight_id.eq(gamenight_id))
.load::<GamenightParticipantsEntry>(c)?;
linked_participants
.iter()
.map(|l| {
users::table
.filter(users::id.eq(l.user_id))
.first::<User>(c)
})
.collect()
})
.await?)
}
pub async fn add_participant(
conn: &DbConn,
participant: GamenightParticipantsEntry,
) -> Result<usize, DatabaseError> {
Ok(conn
.run(move |c| {
diesel::insert_into(gamenight_participants::table)
.values(&participant)
.on_conflict_do_nothing()
.execute(c)
})
.await?)
}
pub async fn remove_participant(
conn: &DbConn,
participant: GamenightParticipantsEntry,
) -> Result<usize, DatabaseError> {
Ok(conn
.run(move |c| diesel::delete(&participant).execute(c))
.await?)
}

View File

@ -1,58 +0,0 @@
pub mod admin;
pub mod gamenight;
pub mod users;
use rocket::{Build, Rocket};
use rocket_sync_db_pools::database;
use std::ops::Deref;
#[database("gamenight_database")]
pub struct DbConn(diesel::PgConnection);
impl Deref for DbConn {
type Target = rocket_sync_db_pools::Connection<DbConn, diesel::PgConnection>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub enum DatabaseError {
Hash(password_hash::Error),
Query(String),
}
pub async fn run_migrations(rocket: Rocket<Build>) -> Rocket<Build> {
// This macro from `diesel_migrations` defines an `embedded_migrations`
// module containing a function named `run`. This allows the example to be
// run and tested without any outside setup of the database.
embed_migrations!();
let conn = DbConn::get_one(&rocket).await.expect("database connection");
conn.run(|c| embedded_migrations::run(c))
.await
.expect("can run migrations");
rocket
}
impl From<diesel::result::Error> for DatabaseError {
fn from(error: diesel::result::Error) -> Self {
Self::Query(error.to_string())
}
}
impl From<password_hash::Error> for DatabaseError {
fn from(error: password_hash::Error) -> Self {
Self::Hash(error)
}
}
impl std::fmt::Display for DatabaseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
match self {
DatabaseError::Hash(err) => write!(f, "{}", err),
DatabaseError::Query(err) => write!(f, "{}", err),
}
}
}

View File

@ -1,191 +0,0 @@
use crate::schema::{DatabaseError, DbConn};
use argon2::password_hash::SaltString;
use argon2::PasswordHash;
use argon2::PasswordVerifier;
use argon2::{
password_hash::{rand_core::OsRng, PasswordHasher},
Argon2,
};
use diesel::{Connection, ExpressionMethods, QueryDsl, RunQueryDsl};
use diesel_derive_enum::DbEnum;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use validator::{Validate, ValidationError};
#[derive(Debug, Serialize, Deserialize, DbEnum, Clone, Copy, PartialEq)]
pub enum Role {
Admin,
User,
}
table! {
users(id) {
id -> diesel::sql_types::Uuid,
username -> VarChar,
email -> VarChar,
role -> crate::schema::users::RoleMapping,
}
}
table! {
pwd(user_id) {
user_id -> diesel::sql_types::Uuid,
password -> VarChar,
}
}
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
#[table_name = "pwd"]
struct Pwd {
user_id: Uuid,
password: String,
}
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
#[table_name = "users"]
pub struct User {
pub id: Uuid,
pub username: String,
pub email: String,
pub role: Role,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UserWithToken {
#[serde(flatten)]
pub user: User,
pub jwt: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Login {
pub username: String,
pub password: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct LoginResult {
pub result: bool,
pub user: Option<User>,
}
#[derive(Serialize, Deserialize, Debug, Validate, Clone)]
pub struct Register {
#[validate(
length(min = 1),
custom(function = "unique_username", arg = "&'v_a diesel::PgConnection")
)]
pub username: String,
#[validate(
email,
custom(function = "unique_email", arg = "&'v_a diesel::PgConnection")
)]
pub email: String,
#[validate(length(min = 10), must_match = "password_repeat")]
pub password: String,
pub password_repeat: String,
}
pub async fn insert_user(conn: DbConn, new_user: Register) -> Result<usize, DatabaseError> {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(new_user.password.as_bytes(), &salt)?
.to_string();
Ok(conn
.run(move |c| {
c.transaction(|| {
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)?;
diesel::insert_into(pwd::table)
.values(Pwd {
user_id: id,
password: password_hash,
})
.execute(c)
})
})
.await?)
}
pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseError> {
conn.run(move |c| -> Result<LoginResult, DatabaseError> {
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
.filter(pwd::user_id.eq(id))
.select(pwd::password)
.first(c)?;
let parsed_hash = PasswordHash::new(&pwd)?;
if Argon2::default()
.verify_password(&login.password.as_bytes(), &parsed_hash)
.is_ok()
{
let user: User = users::table.find(id).first(c)?;
Ok(LoginResult {
result: true,
user: Some(user),
})
} else {
Ok(LoginResult {
result: false,
user: None,
})
}
})
.await
}
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 fn unique_username(
username: &String,
conn: &diesel::PgConnection,
) -> Result<(), ValidationError> {
match users::table
.count()
.filter(users::username.eq(username))
.get_result(conn)
{
Ok(0) => Ok(()),
Ok(_) => Err(ValidationError::new("User already exists")),
Err(_) => Err(ValidationError::new("Database error while validating user")),
}
}
pub fn unique_email(email: &String, conn: &diesel::PgConnection) -> Result<(), ValidationError> {
match users::table
.count()
.filter(users::email.eq(email))
.get_result(conn)
{
Ok(0) => Ok(()),
Ok(_) => Err(ValidationError::new("email already exists")),
Err(_) => Err(ValidationError::new(
"Database error while validating email",
)),
}
}

View File

@ -1,42 +0,0 @@
use rocket::fs::NamedFile;
use rocket::{
fairing::{Fairing, Info, Kind},
http::Header,
Request, Response,
};
use std::io;
use std::path::{Path, PathBuf};
pub struct CORS;
#[rocket::async_trait]
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Attaching CORS headers to responses",
kind: Kind::Response,
}
}
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, OPTIONS",
));
response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
}
#[get("/<file..>", rank = 10)]
pub async fn files(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("../frontend/build/").join(file))
.await
.ok()
}
#[get("/")]
pub async fn index() -> io::Result<NamedFile> {
NamedFile::open("../frontend/build/index.html").await
}

View File

@ -1,5 +0,0 @@
{{#if has_data}}
<div>
<p>{{kind}}: {{message}}</p>
</div>
{{/if}}

View File

@ -1,16 +0,0 @@
<html>
<head>
</head>
<body>
{{> flash flash }}
<form action="{{post_url}}" method="post">
<label for="game">Game:</label><br>
<input type="text" id="game" name="game"><br>
<label for="datetime">Wanneer:</label><br>
<input type="text" id="datetime" name="datetime">
<input type="submit" value="Submit">
</form>
</body>
</html>

View File

@ -1,14 +0,0 @@
<html>
<head>
</head>
<body>
{{> flash flash }}
{{#each gamenights}}
<div>
<span>game: {{this.game}}</span>
<span>when: {{this.datetime}}</span>
</div>
{{/each}}
</body>
</html>

View File

@ -1,19 +0,0 @@
<html>
<head>
</head>
<body>
{{> flash flash }}
<form action="/api/register" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br>
<label for="password_repeat">Repeat password:</label><br>
<input type="password" id="password_repeat" name="password_repeat" required><br>
<input type="submit">
</form>
</body>
</html>