1 Commits

Author SHA1 Message Date
a47646bd5f adds AddPlayer endpoint 2019-12-18 15:22:20 +01:00
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")
@@ -210,10 +214,10 @@ struct AuthRequest {
key: String, key: String,
} }
#[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,24 +227,25 @@ 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()
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error")); .collect::<HashMap<&str, SessionKind>>(),
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT) ) {
.header(header::LOCATION, "/") id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
.finish() HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
.header(header::LOCATION, "/")
.finish()
} 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 || {
SessionKind::Player(id) => api::ApiActions::FetchPlayer(id), api::execute(
SessionKind::Admin => api::ApiActions::FetchPlayers &conn,
} match logged {
)).then( SessionKind::Player(id) => api::ApiActions::FetchPlayer(id),
|res| match res { SessionKind::Admin => api::ApiActions::FetchPlayers,
Ok(r) => HttpResponse::Ok().json(r.value), },
Err(e) => { )
dbg!(&e); })
HttpResponse::Forbidden().finish() .then(|res| match res {
} Ok(r) => HttpResponse::Ok().json(r.value),
}, Err(e) => {
) dbg!(&e);
HttpResponse::Forbidden().finish()
}
})
} }
pub fn serve() -> std::io::Result<()> { pub fn serve() -> std::io::Result<()> {
@@ -310,7 +318,7 @@ pub fn serve() -> std::io::Result<()> {
.route("/session", web::get().to_async(enter_session)) .route("/session", web::get().to_async(enter_session))
.route("/login", web::get().to(login)) .route("/login", web::get().to(login))
.route("/logout", web::get().to(logout)) .route("/logout", web::get().to(logout))
//.service(fs::Files::new("/", www_root.clone()).index_file("index.html")) //.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
}) })
.bind("127.0.0.1:8088")? .bind("127.0.0.1:8088")?
.run() .run()