adds AddPlayer endpoint

This commit is contained in:
2019-12-18 15:22:20 +01:00
parent 2c87713818
commit a47646bd5f
2 changed files with 56 additions and 36 deletions

View File

@@ -20,6 +20,12 @@ pub struct NewGroupLoot {
pub items: ItemList, pub items: ItemList,
} }
#[derive(Serialize, Deserialize, Debug)]
pub struct NewPlayer {
name : String,
wealth : f64,
}
/// A generic response for all queries /// A generic response for all queries
#[derive(Serialize, Debug, Default)] #[derive(Serialize, Debug, Default)]
pub struct ApiResponse { pub struct ApiResponse {
@@ -86,7 +92,7 @@ pub enum ApiActions {
AddLoot(NewGroupLoot), AddLoot(NewGroupLoot),
// Admin level // Admin level
RefreshShopInventory(ItemList), RefreshShopInventory(ItemList),
//AddPlayer(String, f64), AddPlayer(NewPlayer),
//AddInventoryItem(pub String, pub i32), //AddInventoryItem(pub String, pub i32),
//ResolveClaims, //ResolveClaims,
//SetClaimsTimeout(pub i32), //SetClaimsTimeout(pub i32),
@@ -289,6 +295,12 @@ pub fn execute(
// Admin actions // Admin actions
ApiActions::RefreshShopInventory(items) => { ApiActions::RefreshShopInventory(items) => {
db::Shop(conn).replace_list(items)?; db::Shop(conn).replace_list(items)?;
response.notify("Inventaire du marchand renouvelé !");
None
}
ApiActions::AddPlayer(data) => {
db::Players(conn).add(&data.name, data.wealth)?;
response.notify("Joueur ajouté !");
None None
} }
}; };

View File

@@ -11,9 +11,8 @@ use futures::{
future::{ok, Either, FutureResult}, future::{ok, Either, FutureResult},
Future, Future,
}; };
use std::env;
use serde_json; use serde_json;
use std::env;
use crate::api; use crate::api;
use lootalot_db as db; use lootalot_db as db;
@@ -110,7 +109,12 @@ fn configure_api(config: &mut web::ServiceConfig) {
web::scope("/players") web::scope("/players")
.service( .service(
web::resource("/") web::resource("/")
.route(web::get().to_async(|pool| db_call(pool, Q::FetchPlayers))), //.route(web::post().to_async(endpoints::new_player)) .route(web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)))
.route(web::post().to_async(
|pool, player: web::Json<api::NewPlayer>| {
db_call(pool, Q::AddPlayer(player.into_inner()))
},
)),
) // List of players ) // List of players
.service( .service(
web::scope("/{player_id}") web::scope("/{player_id}")
@@ -135,7 +139,7 @@ fn configure_api(config: &mut web::ServiceConfig) {
|pool, (player, data): (PlayerId, IdList)| { |pool, (player, data): (PlayerId, IdList)| {
db_call(pool, Q::ClaimItems(*player, data.into_inner())) db_call(pool, Q::ClaimItems(*player, data.into_inner()))
}, },
)) )),
) )
.service( .service(
web::resource("/wealth") web::resource("/wealth")
@@ -213,7 +217,7 @@ struct AuthRequest {
#[derive(Debug, Copy, Clone, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, Serialize, Deserialize)]
enum SessionKind { enum SessionKind {
Player(i32), Player(i32),
Admin Admin,
} }
use std::collections::HashMap; use std::collections::HashMap;
@@ -223,16 +227,18 @@ fn check_key(key: &str, db: HashMap<&str, SessionKind>) -> Option<SessionKind> {
} }
fn login(id: Identity, key: web::Query<AuthRequest>) -> HttpResponse { fn login(id: Identity, key: web::Query<AuthRequest>) -> HttpResponse {
if let Some(session_kind) = if let Some(session_kind) = check_key(
check_key(
&key.key.to_string(), &key.key.to_string(),
[("0", SessionKind::Player(0)), [
("0", SessionKind::Player(0)),
("1", SessionKind::Player(1)), ("1", SessionKind::Player(1)),
("2", SessionKind::Player(2)), ("2", SessionKind::Player(2)),
("admin", SessionKind::Admin), ("admin", SessionKind::Admin),
].iter().cloned().collect::<HashMap<&str, SessionKind>>() ]
) .iter()
{ .cloned()
.collect::<HashMap<&str, SessionKind>>(),
) {
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error")); id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT) HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
.header(header::LOCATION, "/") .header(header::LOCATION, "/")
@@ -240,7 +246,6 @@ fn login(id: Identity, key: web::Query<AuthRequest>) -> HttpResponse {
} else { } else {
HttpResponse::Forbidden().finish() HttpResponse::Forbidden().finish()
} }
} }
fn logout(id: Identity) -> HttpResponse { fn logout(id: Identity) -> HttpResponse {
@@ -268,19 +273,22 @@ fn enter_session(id: Identity, pool: AppPool) -> impl Future<Item = HttpResponse
// unlogged case with web::block below // unlogged case with web::block below
.unwrap_or(SessionKind::Player(-1)); .unwrap_or(SessionKind::Player(-1));
web::block(move || api::execute(&conn, match logged { web::block(move || {
api::execute(
&conn,
match logged {
SessionKind::Player(id) => api::ApiActions::FetchPlayer(id), SessionKind::Player(id) => api::ApiActions::FetchPlayer(id),
SessionKind::Admin => api::ApiActions::FetchPlayers SessionKind::Admin => api::ApiActions::FetchPlayers,
} },
)).then( )
|res| match res { })
.then(|res| match res {
Ok(r) => HttpResponse::Ok().json(r.value), Ok(r) => HttpResponse::Ok().json(r.value),
Err(e) => { Err(e) => {
dbg!(&e); dbg!(&e);
HttpResponse::Forbidden().finish() HttpResponse::Forbidden().finish()
} }
}, })
)
} }
pub fn serve() -> std::io::Result<()> { pub fn serve() -> std::io::Result<()> {