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,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NewPlayer {
name : String,
wealth : f64,
}
/// A generic response for all queries
#[derive(Serialize, Debug, Default)]
pub struct ApiResponse {
@@ -86,7 +92,7 @@ pub enum ApiActions {
AddLoot(NewGroupLoot),
// Admin level
RefreshShopInventory(ItemList),
//AddPlayer(String, f64),
AddPlayer(NewPlayer),
//AddInventoryItem(pub String, pub i32),
//ResolveClaims,
//SetClaimsTimeout(pub i32),
@@ -289,6 +295,12 @@ pub fn execute(
// Admin actions
ApiActions::RefreshShopInventory(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
}
};

View File

@@ -11,9 +11,8 @@ use futures::{
future::{ok, Either, FutureResult},
Future,
};
use std::env;
use serde_json;
use std::env;
use crate::api;
use lootalot_db as db;
@@ -110,7 +109,12 @@ fn configure_api(config: &mut web::ServiceConfig) {
web::scope("/players")
.service(
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
.service(
web::scope("/{player_id}")
@@ -135,7 +139,7 @@ fn configure_api(config: &mut web::ServiceConfig) {
|pool, (player, data): (PlayerId, IdList)| {
db_call(pool, Q::ClaimItems(*player, data.into_inner()))
},
))
)),
)
.service(
web::resource("/wealth")
@@ -210,10 +214,10 @@ struct AuthRequest {
key: String,
}
#[derive(Debug,Copy,Clone, Serialize, Deserialize)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
enum SessionKind {
Player(i32),
Admin
Admin,
}
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 {
if let Some(session_kind) =
check_key(
&key.key.to_string(),
[("0", SessionKind::Player(0)),
("1", SessionKind::Player(1)),
("2", SessionKind::Player(2)),
("admin", SessionKind::Admin),
].iter().cloned().collect::<HashMap<&str, SessionKind>>()
)
{
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
.header(header::LOCATION, "/")
.finish()
if let Some(session_kind) = check_key(
&key.key.to_string(),
[
("0", SessionKind::Player(0)),
("1", SessionKind::Player(1)),
("2", SessionKind::Player(2)),
("admin", SessionKind::Admin),
]
.iter()
.cloned()
.collect::<HashMap<&str, SessionKind>>(),
) {
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
.header(header::LOCATION, "/")
.finish()
} else {
HttpResponse::Forbidden().finish()
}
}
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
.unwrap_or(SessionKind::Player(-1));
web::block(move || api::execute(&conn, match logged {
SessionKind::Player(id) => api::ApiActions::FetchPlayer(id),
SessionKind::Admin => api::ApiActions::FetchPlayers
}
)).then(
|res| match res {
Ok(r) => HttpResponse::Ok().json(r.value),
Err(e) => {
dbg!(&e);
HttpResponse::Forbidden().finish()
}
},
)
web::block(move || {
api::execute(
&conn,
match logged {
SessionKind::Player(id) => api::ApiActions::FetchPlayer(id),
SessionKind::Admin => api::ApiActions::FetchPlayers,
},
)
})
.then(|res| match res {
Ok(r) => HttpResponse::Ok().json(r.value),
Err(e) => {
dbg!(&e);
HttpResponse::Forbidden().finish()
}
})
}
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("/login", web::get().to(login))
.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")?
.run()