Formatting commit.
This commit is contained in:
parent
5c27be0191
commit
836a4ab59f
@ -1,21 +1,16 @@
|
|||||||
use crate::schema::users::*;
|
|
||||||
use crate::schema::gamenight::*;
|
use crate::schema::gamenight::*;
|
||||||
|
use crate::schema::users::*;
|
||||||
use crate::schema::DbConn;
|
use crate::schema::DbConn;
|
||||||
use crate::AppConfig;
|
use crate::AppConfig;
|
||||||
use uuid::Uuid;
|
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use jsonwebtoken::decode;
|
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||||
use jsonwebtoken::encode;
|
|
||||||
use jsonwebtoken::DecodingKey;
|
|
||||||
use jsonwebtoken::Validation;
|
|
||||||
use jsonwebtoken::{EncodingKey, Header};
|
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::request::Outcome;
|
use rocket::request::{FromRequest, Outcome, Request};
|
||||||
use rocket::request::{FromRequest, Request};
|
|
||||||
use rocket::serde::json::{json, Json, Value};
|
use rocket::serde::json::{json, Json, Value};
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
|
use uuid::Uuid;
|
||||||
use validator::ValidateArgs;
|
use validator::ValidateArgs;
|
||||||
|
|
||||||
#[derive(Debug, Responder)]
|
#[derive(Debug, Responder)]
|
||||||
@ -65,7 +60,7 @@ impl ApiResponse {
|
|||||||
message: None,
|
message: None,
|
||||||
user: Some(UserWithToken {
|
user: Some(UserWithToken {
|
||||||
user: user,
|
user: user,
|
||||||
jwt: jwt
|
jwt: jwt,
|
||||||
}),
|
}),
|
||||||
gamenights: None,
|
gamenights: None,
|
||||||
games: None,
|
games: None,
|
||||||
@ -108,9 +103,7 @@ impl<'r> FromRequest<'r> for User {
|
|||||||
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||||
let header = match req.headers().get_one(AUTH_HEADER) {
|
let header = match req.headers().get_one(AUTH_HEADER) {
|
||||||
Some(header) => header,
|
Some(header) => header,
|
||||||
None => {
|
None => return Outcome::Forward(()),
|
||||||
return Outcome::Forward(())
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if !header.starts_with(BEARER) {
|
if !header.starts_with(BEARER) {
|
||||||
@ -125,25 +118,25 @@ impl<'r> FromRequest<'r> for User {
|
|||||||
&Validation::default(),
|
&Validation::default(),
|
||||||
) {
|
) {
|
||||||
Ok(token) => token,
|
Ok(token) => token,
|
||||||
Err(_) => {
|
Err(_) => return Outcome::Forward(()),
|
||||||
return Outcome::Forward(())
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let id = token.claims.uid;
|
let id = token.claims.uid;
|
||||||
|
|
||||||
let conn = req.guard::<DbConn>().await.unwrap();
|
let conn = req.guard::<DbConn>().await.unwrap();
|
||||||
return match get_user(conn, id).await {
|
return match get_user(conn, id).await {
|
||||||
Ok(o) => Outcome::Success(o),
|
Ok(o) => Outcome::Success(o),
|
||||||
Err(_) => Outcome::Forward(())
|
Err(_) => Outcome::Forward(()),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/gamenights")]
|
#[get("/gamenights")]
|
||||||
pub async fn gamenights(conn: DbConn, _user: User) -> ApiResponseVariant {
|
pub async fn gamenights(conn: DbConn, _user: User) -> ApiResponseVariant {
|
||||||
match get_all_gamenights(conn).await {
|
match get_all_gamenights(conn).await {
|
||||||
Ok(gamenights) => ApiResponseVariant::Value(json!(ApiResponse::gamenight_response(gamenights))),
|
Ok(gamenights) => {
|
||||||
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
ApiResponseVariant::Value(json!(ApiResponse::gamenight_response(gamenights)))
|
||||||
|
}
|
||||||
|
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string()))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -161,13 +154,12 @@ pub struct GameNightInput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Into<GameNight> for GameNightInput {
|
impl Into<GameNight> for GameNightInput {
|
||||||
|
fn into(self) -> GameNight {
|
||||||
fn into(self) -> GameNight {
|
|
||||||
GameNight {
|
GameNight {
|
||||||
id: Uuid::new_v4(),
|
id: Uuid::new_v4(),
|
||||||
name: self.name,
|
name: self.name,
|
||||||
datetime: self.datetime,
|
datetime: self.datetime,
|
||||||
owner_id: self.owner_id.unwrap()
|
owner_id: self.owner_id.unwrap(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -185,12 +177,12 @@ pub async fn gamenights_post_json(
|
|||||||
|
|
||||||
match add_unknown_games(&conn, &mut mutable_game_list).await {
|
match add_unknown_games(&conn, &mut mutable_game_list).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string())))
|
Err(err) => return ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
|
||||||
};
|
};
|
||||||
|
|
||||||
match insert_gamenight(conn, gamenight.clone().into(), mutable_game_list).await {
|
match insert_gamenight(conn, gamenight.clone().into(), mutable_game_list).await {
|
||||||
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
|
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
|
||||||
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string())))
|
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,44 +191,46 @@ pub async fn gamenights_post_json_unauthorized() -> ApiResponseVariant {
|
|||||||
ApiResponseVariant::Status(Status::Unauthorized)
|
ApiResponseVariant::Status(Status::Unauthorized)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[delete("/gamenights", format = "application/json", data = "<delete_gamenight_json>")]
|
#[delete(
|
||||||
|
"/gamenights",
|
||||||
|
format = "application/json",
|
||||||
|
data = "<delete_gamenight_json>"
|
||||||
|
)]
|
||||||
pub async fn gamenights_delete_json(
|
pub async fn gamenights_delete_json(
|
||||||
conn: DbConn,
|
conn: DbConn,
|
||||||
user: User,
|
user: User,
|
||||||
delete_gamenight_json: Json<DeleteGameNight>
|
delete_gamenight_json: Json<DeleteGameNight>,
|
||||||
) -> ApiResponseVariant {
|
) -> ApiResponseVariant {
|
||||||
if user.role == Role::Admin {
|
if user.role == Role::Admin {
|
||||||
if let Err(error) = delete_gamenight(&conn, delete_gamenight_json.game_id).await {
|
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::error(error.to_string())));
|
||||||
}
|
}
|
||||||
return ApiResponseVariant::Value(json!(ApiResponse::SUCCES))
|
return ApiResponseVariant::Value(json!(ApiResponse::SUCCES));
|
||||||
}
|
}
|
||||||
|
|
||||||
match get_gamenight(&conn, delete_gamenight_json.game_id).await {
|
match get_gamenight(&conn, delete_gamenight_json.game_id).await {
|
||||||
Ok(gamenight) => {
|
Ok(gamenight) => {
|
||||||
if user.id == gamenight.owner_id {
|
if user.id == gamenight.owner_id {
|
||||||
if let Err(error) = delete_gamenight(&conn, delete_gamenight_json.game_id).await {
|
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::error(error.to_string())));
|
||||||
}
|
}
|
||||||
return ApiResponseVariant::Value(json!(ApiResponse::SUCCES))
|
return ApiResponseVariant::Value(json!(ApiResponse::SUCCES));
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
Err(error) => return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
Err(error) => {
|
||||||
|
return ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ApiResponseVariant::Status(Status::Unauthorized)
|
ApiResponseVariant::Status(Status::Unauthorized)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[delete("/gamenights", rank = 2)]
|
#[delete("/gamenights", rank = 2)]
|
||||||
pub async fn gamenights_delete_json_unauthorized() -> ApiResponseVariant {
|
pub async fn gamenights_delete_json_unauthorized() -> ApiResponseVariant {
|
||||||
ApiResponseVariant::Status(Status::Unauthorized)
|
ApiResponseVariant::Status(Status::Unauthorized)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/register", format = "application/json", data = "<register_json>")]
|
#[post("/register", format = "application/json", data = "<register_json>")]
|
||||||
pub async fn register_post_json(
|
pub async fn register_post_json(conn: DbConn, register_json: Json<Register>) -> ApiResponseVariant {
|
||||||
conn: DbConn,
|
|
||||||
register_json: Json<Register>,
|
|
||||||
) -> ApiResponseVariant {
|
|
||||||
let register = register_json.into_inner();
|
let register = register_json.into_inner();
|
||||||
let register_clone = register.clone();
|
let register_clone = register.clone();
|
||||||
match conn
|
match conn
|
||||||
@ -290,7 +284,9 @@ pub async fn login_post_json(
|
|||||||
&my_claims,
|
&my_claims,
|
||||||
&EncodingKey::from_secret(secret.as_bytes()),
|
&EncodingKey::from_secret(secret.as_bytes()),
|
||||||
) {
|
) {
|
||||||
Ok(token) => ApiResponseVariant::Value(json!(ApiResponse::login_response(user, token))),
|
Ok(token) => {
|
||||||
|
ApiResponseVariant::Value(json!(ApiResponse::login_response(user, token)))
|
||||||
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
||||||
}
|
}
|
||||||
@ -303,7 +299,7 @@ pub async fn login_post_json(
|
|||||||
pub async fn games(conn: DbConn, _user: User) -> ApiResponseVariant {
|
pub async fn games(conn: DbConn, _user: User) -> ApiResponseVariant {
|
||||||
match get_all_known_games(&conn).await {
|
match get_all_known_games(&conn).await {
|
||||||
Ok(games) => ApiResponseVariant::Value(json!(ApiResponse::games_response(games))),
|
Ok(games) => ApiResponseVariant::Value(json!(ApiResponse::games_response(games))),
|
||||||
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string())))
|
Err(error) => ApiResponseVariant::Value(json!(ApiResponse::error(error.to_string()))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -311,4 +307,3 @@ pub async fn games(conn: DbConn, _user: User) -> ApiResponseVariant {
|
|||||||
pub async fn games_unauthorized() -> ApiResponseVariant {
|
pub async fn games_unauthorized() -> ApiResponseVariant {
|
||||||
ApiResponseVariant::Status(Status::Unauthorized)
|
ApiResponseVariant::Status(Status::Unauthorized)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -46,13 +46,7 @@ async fn rocket() -> _ {
|
|||||||
.attach(AdHoc::on_ignite("Run Migrations", schema::run_migrations))
|
.attach(AdHoc::on_ignite("Run Migrations", schema::run_migrations))
|
||||||
.attach(AdHoc::config::<AppConfig>())
|
.attach(AdHoc::config::<AppConfig>())
|
||||||
.attach(site::make_cors())
|
.attach(site::make_cors())
|
||||||
.mount(
|
.mount("/", routes![site::index, site::files])
|
||||||
"/",
|
|
||||||
routes![
|
|
||||||
site::index,
|
|
||||||
site::files
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.mount(
|
.mount(
|
||||||
"/api",
|
"/api",
|
||||||
routes![
|
routes![
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use crate::schema::{DatabaseError, DbConn};
|
use crate::schema::{DatabaseError, DbConn};
|
||||||
|
use diesel::{Connection, ExpressionMethods, QueryDsl, RunQueryDsl};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use diesel::{QueryDsl, RunQueryDsl, Connection, ExpressionMethods};
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
table! {
|
table! {
|
||||||
@ -50,18 +50,18 @@ pub struct GameNight {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable)]
|
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable)]
|
||||||
#[table_name="gamenight_gamelist"]
|
#[table_name = "gamenight_gamelist"]
|
||||||
pub struct GamenightGameListEntry {
|
pub struct GamenightGameListEntry {
|
||||||
pub gamenight_id: Uuid,
|
pub gamenight_id: Uuid,
|
||||||
pub game_id: Uuid
|
pub game_id: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable, Identifiable)]
|
#[derive(Serialize, Deserialize, Debug, Queryable, Insertable, Identifiable)]
|
||||||
#[table_name="gamenight_participants"]
|
#[table_name = "gamenight_participants"]
|
||||||
#[primary_key(gamenight_id, user_id)]
|
#[primary_key(gamenight_id, user_id)]
|
||||||
pub struct GamenightParticipantsEntry {
|
pub struct GamenightParticipantsEntry {
|
||||||
pub gamenight_id: Uuid,
|
pub gamenight_id: Uuid,
|
||||||
pub user_id: Uuid
|
pub user_id: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Queryable)]
|
#[derive(Serialize, Deserialize, Debug, Queryable)]
|
||||||
@ -69,62 +69,62 @@ pub struct DeleteGameNight {
|
|||||||
pub game_id: Uuid,
|
pub game_id: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub async fn get_all_gamenights(conn: DbConn) -> Result<Vec<GameNight>, DatabaseError> {
|
pub async fn get_all_gamenights(conn: DbConn) -> Result<Vec<GameNight>, DatabaseError> {
|
||||||
Ok(conn.run(|c|
|
Ok(conn.run(|c| gamenight::table.load::<GameNight>(c)).await?)
|
||||||
gamenight::table.load::<GameNight>(c)
|
|
||||||
).await?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn insert_gamenight(conn: DbConn, new_gamenight: GameNight, game_list: Vec<Game>) -> Result<usize, DatabaseError> {
|
pub async fn insert_gamenight(
|
||||||
Ok(conn.run(move |c|
|
conn: DbConn,
|
||||||
c.transaction(|| {
|
new_gamenight: GameNight,
|
||||||
diesel::insert_into(gamenight::table)
|
game_list: Vec<Game>,
|
||||||
.values(&new_gamenight)
|
) -> Result<usize, DatabaseError> {
|
||||||
.execute(c)?;
|
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(
|
let entries: Vec<GamenightGameListEntry> = game_list
|
||||||
|g| GamenightGameListEntry { gamenight_id: new_gamenight.id.clone(), game_id: g.id.clone() }
|
.iter()
|
||||||
).collect();
|
.map(|g| GamenightGameListEntry {
|
||||||
|
gamenight_id: new_gamenight.id.clone(),
|
||||||
|
game_id: g.id.clone(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
diesel::insert_into(gamenight_gamelist::table)
|
diesel::insert_into(gamenight_gamelist::table)
|
||||||
.values(entries)
|
.values(entries)
|
||||||
.execute(c)
|
.execute(c)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
).await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_gamenight(conn: &DbConn, game_id: Uuid) -> Result<GameNight, DatabaseError> {
|
pub async fn get_gamenight(conn: &DbConn, game_id: Uuid) -> Result<GameNight, DatabaseError> {
|
||||||
Ok(conn.run(move |c|
|
Ok(conn
|
||||||
gamenight::table.find(game_id).first(c)
|
.run(move |c| gamenight::table.find(game_id).first(c))
|
||||||
).await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_gamenight(conn: &DbConn, game_id: Uuid) -> Result<usize, DatabaseError> {
|
pub async fn delete_gamenight(conn: &DbConn, game_id: Uuid) -> Result<usize, DatabaseError> {
|
||||||
Ok(conn.run(move |c|
|
Ok(conn
|
||||||
diesel::delete(
|
.run(move |c| diesel::delete(gamenight::table.filter(gamenight::id.eq(game_id))).execute(c))
|
||||||
gamenight::table.filter(
|
.await?)
|
||||||
gamenight::id.eq(game_id)
|
|
||||||
)
|
|
||||||
).execute(c)
|
|
||||||
).await?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
pub async fn get_all_known_games(conn: &DbConn) -> Result<Vec<Game>, DatabaseError> {
|
pub async fn get_all_known_games(conn: &DbConn) -> Result<Vec<Game>, DatabaseError> {
|
||||||
Ok(conn.run(|c|
|
Ok(conn.run(|c| known_games::table.load::<Game>(c)).await?)
|
||||||
known_games::table.load::<Game>(c)
|
|
||||||
).await?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn add_game(conn: &DbConn, game: Game) -> Result<usize, DatabaseError> {
|
pub async fn add_game(conn: &DbConn, game: Game) -> Result<usize, DatabaseError> {
|
||||||
Ok(conn.run(|c|
|
Ok(conn
|
||||||
diesel::insert_into(known_games::table)
|
.run(|c| {
|
||||||
.values(game)
|
diesel::insert_into(known_games::table)
|
||||||
.execute(c)
|
.values(game)
|
||||||
|
.execute(c)
|
||||||
).await?)
|
})
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn add_unknown_games(conn: &DbConn, games: &mut Vec<Game>) -> Result<(), DatabaseError> {
|
pub async fn add_unknown_games(conn: &DbConn, games: &mut Vec<Game>) -> Result<(), DatabaseError> {
|
||||||
@ -138,24 +138,30 @@ pub async fn add_unknown_games(conn: &DbConn, games: &mut Vec<Game>) -> Result<(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn insert_participant(conn: &DbConn, participant: GamenightParticipantsEntry) -> Result<usize, DatabaseError> {
|
pub async fn insert_participant(
|
||||||
Ok(conn.run(move |c|
|
conn: &DbConn,
|
||||||
diesel::insert_into(gamenight_participants::table)
|
participant: GamenightParticipantsEntry,
|
||||||
.values(&participant)
|
) -> Result<usize, DatabaseError> {
|
||||||
.execute(c)
|
Ok(conn
|
||||||
).await?)
|
.run(move |c| {
|
||||||
|
diesel::insert_into(gamenight_participants::table)
|
||||||
|
.values(&participant)
|
||||||
|
.execute(c)
|
||||||
|
})
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<GamenightParticipantsEntry> for (Uuid, Uuid) {
|
impl From<GamenightParticipantsEntry> for (Uuid, Uuid) {
|
||||||
|
|
||||||
fn from(entry: GamenightParticipantsEntry) -> Self {
|
fn from(entry: GamenightParticipantsEntry) -> Self {
|
||||||
(entry.gamenight_id, entry.user_id)
|
(entry.gamenight_id, entry.user_id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn remove_participant(conn: &DbConn, participant: GamenightParticipantsEntry) -> Result<usize, DatabaseError> {
|
pub async fn remove_participant(
|
||||||
Ok(conn.run(move |c|
|
conn: &DbConn,
|
||||||
diesel::delete(&participant)
|
participant: GamenightParticipantsEntry,
|
||||||
.execute(c)
|
) -> Result<usize, DatabaseError> {
|
||||||
).await?)
|
Ok(conn
|
||||||
}
|
.run(move |c| diesel::delete(&participant).execute(c))
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
pub mod users;
|
|
||||||
pub mod gamenight;
|
pub mod gamenight;
|
||||||
|
pub mod users;
|
||||||
|
|
||||||
use rocket::{Build, Rocket};
|
use rocket::{Build, Rocket};
|
||||||
use rocket_sync_db_pools::database;
|
use rocket_sync_db_pools::database;
|
||||||
@ -36,7 +36,7 @@ pub async fn run_migrations(rocket: Rocket<Build>) -> Rocket<Build> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<diesel::result::Error> for DatabaseError {
|
impl From<diesel::result::Error> for DatabaseError {
|
||||||
fn from(error: diesel::result::Error) -> Self {
|
fn from(error: diesel::result::Error) -> Self {
|
||||||
Self::Query(error.to_string())
|
Self::Query(error.to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -55,6 +55,3 @@ impl std::fmt::Display for DatabaseError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,6 +1,4 @@
|
|||||||
use validator::{Validate, ValidationError};
|
use crate::schema::{DatabaseError, DbConn};
|
||||||
use uuid::Uuid;
|
|
||||||
use diesel::{QueryDsl, RunQueryDsl, Connection, ExpressionMethods};
|
|
||||||
use argon2::password_hash::SaltString;
|
use argon2::password_hash::SaltString;
|
||||||
use argon2::PasswordHash;
|
use argon2::PasswordHash;
|
||||||
use argon2::PasswordVerifier;
|
use argon2::PasswordVerifier;
|
||||||
@ -8,9 +6,11 @@ use argon2::{
|
|||||||
password_hash::{rand_core::OsRng, PasswordHasher},
|
password_hash::{rand_core::OsRng, PasswordHasher},
|
||||||
Argon2,
|
Argon2,
|
||||||
};
|
};
|
||||||
|
use diesel::{Connection, ExpressionMethods, QueryDsl, RunQueryDsl};
|
||||||
use diesel_derive_enum::DbEnum;
|
use diesel_derive_enum::DbEnum;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use crate::schema::{DbConn, DatabaseError};
|
use uuid::Uuid;
|
||||||
|
use validator::{Validate, ValidationError};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, DbEnum, Clone, Copy, PartialEq)]
|
#[derive(Debug, Serialize, Deserialize, DbEnum, Clone, Copy, PartialEq)]
|
||||||
pub enum Role {
|
pub enum Role {
|
||||||
@ -41,7 +41,6 @@ struct Pwd {
|
|||||||
password: String,
|
password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
|
#[derive(Serialize, Deserialize, Debug, Insertable, Queryable)]
|
||||||
#[table_name = "users"]
|
#[table_name = "users"]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
@ -92,30 +91,33 @@ pub async fn insert_user(conn: DbConn, new_user: Register) -> Result<usize, Data
|
|||||||
|
|
||||||
let argon2 = Argon2::default();
|
let argon2 = Argon2::default();
|
||||||
|
|
||||||
let password_hash = argon2.hash_password(new_user.password.as_bytes(), &salt)?.to_string();
|
let password_hash = argon2
|
||||||
|
.hash_password(new_user.password.as_bytes(), &salt)?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
Ok(conn.run(move |c| {
|
Ok(conn
|
||||||
c.transaction(|| {
|
.run(move |c| {
|
||||||
let id = Uuid::new_v4();
|
c.transaction(|| {
|
||||||
|
let id = Uuid::new_v4();
|
||||||
|
|
||||||
diesel::insert_into(users::table)
|
diesel::insert_into(users::table)
|
||||||
.values(User {
|
.values(User {
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
username: new_user.username,
|
username: new_user.username,
|
||||||
email: new_user.email,
|
email: new_user.email,
|
||||||
role: Role::User
|
role: Role::User,
|
||||||
})
|
})
|
||||||
.execute(c)?;
|
.execute(c)?;
|
||||||
|
|
||||||
diesel::insert_into(pwd::table)
|
diesel::insert_into(pwd::table)
|
||||||
.values(Pwd {
|
.values(Pwd {
|
||||||
user_id: id,
|
user_id: id,
|
||||||
password: password_hash
|
password: password_hash,
|
||||||
})
|
})
|
||||||
.execute(c)
|
.execute(c)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
.await?)
|
||||||
.await?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseError> {
|
pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseError> {
|
||||||
@ -141,12 +143,12 @@ pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseEr
|
|||||||
|
|
||||||
Ok(LoginResult {
|
Ok(LoginResult {
|
||||||
result: true,
|
result: true,
|
||||||
user : Some(user)
|
user: Some(user),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
Ok(LoginResult {
|
Ok(LoginResult {
|
||||||
result: false,
|
result: false,
|
||||||
user: None
|
user: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -154,7 +156,8 @@ pub async fn login(conn: DbConn, login: Login) -> Result<LoginResult, DatabaseEr
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_user(conn: DbConn, id: Uuid) -> Result<User, DatabaseError> {
|
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))
|
Ok(conn
|
||||||
|
.run(move |c| users::table.filter(users::id.eq(id)).first(c))
|
||||||
.await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -173,10 +176,7 @@ pub fn unique_username(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn unique_email(
|
pub fn unique_email(email: &String, conn: &diesel::PgConnection) -> Result<(), ValidationError> {
|
||||||
email: &String,
|
|
||||||
conn: &diesel::PgConnection,
|
|
||||||
) -> Result<(), ValidationError> {
|
|
||||||
match users::table
|
match users::table
|
||||||
.count()
|
.count()
|
||||||
.filter(users::email.eq(email))
|
.filter(users::email.eq(email))
|
||||||
@ -188,4 +188,4 @@ pub fn unique_email(
|
|||||||
"Database error while validating email",
|
"Database error while validating email",
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,19 @@
|
|||||||
|
use local_ip_address::local_ip;
|
||||||
use rocket::fs::NamedFile;
|
use rocket::fs::NamedFile;
|
||||||
use rocket::http::Method;
|
use rocket::http::Method;
|
||||||
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions};
|
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions};
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use local_ip_address::local_ip;
|
|
||||||
|
|
||||||
|
|
||||||
pub fn make_cors() -> Cors {
|
pub fn make_cors() -> Cors {
|
||||||
let allowed_origins = AllowedOrigins::some_exact(&[
|
let allowed_origins = AllowedOrigins::some_exact(&[
|
||||||
"http://localhost:3000",
|
"http://localhost:3000",
|
||||||
"http://127.0.0.1:3000",
|
"http://127.0.0.1:3000",
|
||||||
&format!("http://{}:8000",local_ip().unwrap())[..],
|
&format!("http://{}:8000", local_ip().unwrap())[..],
|
||||||
"http://localhost:8000",
|
"http://localhost:8000",
|
||||||
"http://0.0.0.0:8000",
|
"http://0.0.0.0:8000",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
CorsOptions {
|
CorsOptions {
|
||||||
allowed_origins,
|
allowed_origins,
|
||||||
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(), // 1.
|
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(), // 1.
|
||||||
|
Loading…
Reference in New Issue
Block a user