From 01c2b99232c135b2543a276ec691e6597b5d0d5a Mon Sep 17 00:00:00 2001 From: Tomasz Sidoruk Date: Fri, 20 May 2022 16:04:43 +0200 Subject: [PATCH] ok --- backend/Cargo.lock | 162 ++++---- backend/Cargo.toml | 2 +- backend/src/main.rs | 962 ++++++++++++++++++++++++++++++++++++++----- backend/src/main1.rs | 55 --- 4 files changed, 958 insertions(+), 223 deletions(-) delete mode 100644 backend/src/main1.rs diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 9a0fe39..a060ccb 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -339,9 +339,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6988e897c1c9c485f43b47a529cef42fde0547f9d8d41a7062518f1d8fc53f" +checksum = "b39522e96686d38f4bc984b9198e3a0613264abaebaff2c5c918bfa6b6da09af" dependencies = [ "cfg-if", "crc32fast", @@ -508,9 +508,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77" +checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" dependencies = [ "cfg-if", "libc", @@ -525,9 +525,9 @@ checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" [[package]] name = "h2" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62eeb471aa3e3c9197aa4bfeabfe02982f6dc96f750486c0bb0009ac58b26d2b" +checksum = "37a82c6d637fc9515a4694bbf1cb2457b79d81ce52b3108bdeea58b07dd34a57" dependencies = [ "bytes", "fnv", @@ -551,20 +551,6 @@ dependencies = [ "ahash", ] -[[package]] -name = "hello_world" -version = "0.1.0" -dependencies = [ - "bcrypt", - "hyper", - "mysql", - "rand 0.3.23", - "serde", - "serde_derive", - "serde_json", - "tokio", -] - [[package]] name = "hermit-abi" version = "0.1.19" @@ -598,9 +584,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9100414882e15fb7feccb4897e5f0ff0ff1ca7d1a86a23208ada4d7a18e6c6c4" +checksum = "6330e8a36bd8c859f3fa6d9382911fbb7147ec39807f63b923933a247240b9ba" [[package]] name = "httpdate" @@ -610,9 +596,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "hyper" -version = "0.14.17" +version = "0.14.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043f0e083e9901b6cc658a77d1eb86f4fc650bbb977a4337dd63192826aa85dd" +checksum = "b26ae0a80afebe130861d90abf98e3814a4f28a4c6ffeb5ab8ebb2be311e0ef2" dependencies = [ "bytes", "futures-channel", @@ -645,9 +631,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.8.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223" +checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" dependencies = [ "autocfg", "hashbrown", @@ -776,9 +762,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.121" +version = "0.2.124" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efaa7b300f3b5fe8eb6bf21ce3895e1751d9665086af2d64b42f19701015ff4f" +checksum = "21a41fed9d98f27ab1c6d161da622a4fa35e8a54a8adc24bbf3ddd0ef70b0e50" [[package]] name = "libloading" @@ -803,10 +789,11 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88943dd7ef4a2e5a4bfa2753aaab3013e34ce2533d1996fb18ef591e315e2b3b" +checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" dependencies = [ + "autocfg", "scopeguard", ] @@ -821,13 +808,27 @@ dependencies = [ [[package]] name = "lru" -version = "0.7.3" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb87f3080f6d1d69e8c564c0fcfde1d7aa8cc451ce40cae89479111f03bc0eb" +checksum = "32613e41de4c47ab04970c348ca7ae7382cf116625755af070b008a15516a889" dependencies = [ "hashbrown", ] +[[package]] +name = "main" +version = "0.1.0" +dependencies = [ + "bcrypt", + "hyper", + "mysql", + "rand 0.3.23", + "serde", + "serde_derive", + "serde_json", + "tokio", +] + [[package]] name = "matches" version = "0.1.9" @@ -857,12 +858,11 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.4.4" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +checksum = "d2b29bd4bc3f33391105ebee3589c19197c4271e3e5a9ec9bfe8127eeff8f082" dependencies = [ "adler", - "autocfg", ] [[package]] @@ -963,9 +963,9 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.8" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48ba9f7719b5a0f42f338907614285fb5fd70e53858141f69898a1fb7203b24d" +checksum = "fd7e2f3618557f980e0b17e8856252eee3c97fa12c54dff0ca290fb6266ca4a9" dependencies = [ "lazy_static", "libc", @@ -1111,9 +1111,9 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.1" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28141e0cc4143da2443301914478dc976a61ffdb3f043058310c70df2fed8954" +checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" dependencies = [ "cfg-if", "libc", @@ -1157,9 +1157,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.24" +version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58893f751c9b0412871a09abd62ecd2a00298c6c83befa223ef98c52aef40cbe" +checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" [[package]] name = "ppv-lite86" @@ -1175,18 +1175,18 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] name = "proc-macro2" -version = "1.0.36" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" +checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" dependencies = [ "unicode-xid", ] [[package]] name = "quote" -version = "1.0.16" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4af2ec4714533fcdf07e886f17025ace8b997b9ce51204ee69b6da831c3da57" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" dependencies = [ "proc-macro2", ] @@ -1276,9 +1276,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.2.11" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8380fe0152551244f0747b1bf41737e0f8a74f97a14ccefd1148187271634f3c" +checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" dependencies = [ "bitflags", ] @@ -1311,9 +1311,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.22.0" +version = "1.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d37baa70cf8662d2ba1c1868c5983dda16ef32b105cce41fb5c47e72936a90b3" +checksum = "22dc69eadbf0ee2110b8d20418c0c6edbaefec2811c4963dc17b6344e11fe0f8" dependencies = [ "arrayvec", "num-traits", @@ -1444,9 +1444,9 @@ dependencies = [ [[package]] name = "slab" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9def91fd1e018fe007022791f865d0ccc9b3a0d5001e01aabb8b40e46000afb5" +checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32" [[package]] name = "smallvec" @@ -1482,9 +1482,9 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.89" +version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea297be220d52398dcc07ce15a209fce436d361735ac1db700cab3b6cdfb9f54" +checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" dependencies = [ "proc-macro2", "quote", @@ -1533,9 +1533,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.7" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "004cbc98f30fa233c61a38bc77e96a9106e65c88f2d3bef182ae952027e5753d" +checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd" dependencies = [ "libc", "num_threads", @@ -1589,16 +1589,16 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.6.9" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e99e1983e5d376cd8eb4b66604d2e99e79f5bd988c3055891dcd8c9e2604cc0" +checksum = "0edfdeb067411dba2044da6d1cb2df793dd35add7888d73c16e3381ded401764" dependencies = [ "bytes", "futures-core", "futures-sink", - "log", "pin-project-lite", "tokio", + "tracing", ] [[package]] @@ -1609,20 +1609,32 @@ checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" [[package]] name = "tracing" -version = "0.1.32" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a1bdf54a7c28a2bbf701e1d2233f6c77f473486b94bee4f9678da5a148dca7f" +checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" dependencies = [ "cfg-if", "pin-project-lite", + "tracing-attributes", "tracing-core", ] [[package]] -name = "tracing-core" -version = "0.1.23" +name = "tracing-attributes" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa31669fa42c09c34d94d8165dd2012e8ff3c66aca50f3bb226b68f216f2706c" +checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" dependencies = [ "lazy_static", ] @@ -1747,9 +1759,9 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" -version = "0.32.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3df6e476185f92a12c072be4a189a0210dcdcf512a1891d6dff9edb874deadc6" +checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" dependencies = [ "windows_aarch64_msvc", "windows_i686_gnu", @@ -1760,33 +1772,33 @@ dependencies = [ [[package]] name = "windows_aarch64_msvc" -version = "0.32.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8e92753b1c443191654ec532f14c199742964a061be25d77d7a96f09db20bf5" +checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" [[package]] name = "windows_i686_gnu" -version = "0.32.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a711c68811799e017b6038e0922cb27a5e2f43a2ddb609fe0b6f3eeda9de615" +checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" [[package]] name = "windows_i686_msvc" -version = "0.32.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c11bb1a02615db74680b32a68e2d61f553cc24c4eb5b4ca10311740e44172" +checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" [[package]] name = "windows_x86_64_gnu" -version = "0.32.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c912b12f7454c6620635bbff3450962753834be2a594819bd5e945af18ec64bc" +checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" [[package]] name = "windows_x86_64_msvc" -version = "0.32.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "504a2476202769977a040c6364301a3f65d0cc9e3fb08600b2bda150a0488316" +checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" [[package]] name = "wyz" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 854afdf..6bdad27 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "hello_world" +name = "main" version = "0.1.0" edition = "2018" diff --git a/backend/src/main.rs b/backend/src/main.rs index 2e08fb8..a1e0e93 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -8,6 +8,17 @@ use hyper::{Body, Client, Method, Request, Response, Server, StatusCode}; use hyper::service::{make_service_fn, service_fn}; use bcrypt::{DEFAULT_COST, hash, verify}; use rand::{OsRng, Rng}; +use serde_json::Map; + +#[derive(Serialize, Deserialize)] +struct Proposal { + id: i32, + ladderid: i32, + winner: String, + proposer: i32, + approver: i32, + score: String, +} #[derive(Serialize, Deserialize)] struct User { @@ -18,16 +29,37 @@ struct User { login: String, phone: String, mail: String, + ranking: i32, +} + +#[derive(Serialize, Deserialize)] +struct leaderboard { + name: String, + surname: String, + ranking: i32, +} + +#[derive(Serialize, Deserialize)] +struct ladderRaw { + id: i32, + inAtype: String, + inA: String, + inBtype: String, + inB: String, + winner: String, + round: String, + scores: String, } #[derive(Serialize, Deserialize)] struct Registration { id: i32, - userid: String, + userid: i32, tournamentid: String, paymenttype: String, paymentstatus: String, approval: String, + partner: i32, } #[derive(Serialize, Deserialize)] @@ -40,6 +72,7 @@ struct Usera { phone: String, mail: String, deleted: i32, + ranking: i32, } #[derive(Serialize, Deserialize)] @@ -52,6 +85,8 @@ struct tournament { roles: String, creator: i32, approved: i32, + state: i32, + currentRound: i32, } #[derive(Serialize, Deserialize)] @@ -65,14 +100,45 @@ struct tournamenta { creator: i32, approved: i32, deleted: i32, + state: i32, + currentRound: i32, } -thread_local!(static POOL: Pool = Pool::new(Opts::from_url("mysql://inz:*****!@10.1.6.101:3306/inz").unwrap()).unwrap()); +thread_local!(static POOL: Pool = Pool::new(Opts::from_url("mysql://inz:HaLzqw68CbabS8Smz3Vx!@10.1.6.101:3306/inz").unwrap()).unwrap()); async fn hello_world(req: Request) -> Result> { let mut response = Response::new(Body::empty()); match (req.method(), req.uri().path()) { - (&Method::POST, "/registrations/approve") => { + (&Method::GET, "/proposals/pending") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + let row = it.next(); + let urow = row.unwrap().unwrap(); + let uid: i32 = urow.get(0).unwrap(); + let res = poola.get_conn().unwrap() + .exec_map( + "SELECT * FROM inz.winProposals where proposer in (Select id from registrations where ? = userid or ? = partner ) or approver in (Select id from registrations where ? = userid or ? = partner );", (&uid, &uid, &uid, &uid), + |(id, ladderid, winner, proposer, approver, score)| { + Proposal { id, ladderid, winner, proposer, approver, score } + }, + ); + *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::POST, "/proposal/approve") => { if req.headers().contains_key("Authorization") { let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); let aa = tmp.next().unwrap(); @@ -83,7 +149,493 @@ async fn hello_world(req: Request) -> Result> { let token = tmp.next().unwrap().to_string(); let byte_stream = hyper::body::to_bytes(req).await.unwrap(); let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); - if !s.contains_key("id"){ + let mut row: Option> = None; + let mut row2: Option> = None; + let mut row3: Option> = None; + if !s.contains_key("id") { + *response.body_mut() = "{\"error\":\"id is required\"}".into(); + return Ok(response); + } + let id = s.get("id").unwrap().to_string(); + + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + row = it.next(); + let mut con2 = poola.get_conn().unwrap(); + let mut result2 = con2.exec_iter("Select ladderid, winner, score from winProposals where id =?;", (&id, )).unwrap(); + let mut it2 = result2.iter().unwrap(); + row2 = it2.next(); + let mut con3 = poola.get_conn().unwrap(); + let mut result3 = con3.exec_iter("Select userid, partner from registrations where id =(Select approver from winProposals where id =?);", (&id, )).unwrap(); + let mut it3 = result3.iter().unwrap(); + row3 = it3.next(); + }); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return Ok(response); + } + if row2.is_none() { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + let urow = row.unwrap().unwrap(); + let urow2 = row2.unwrap().unwrap(); + let urow3 = row3.unwrap().unwrap(); + let uid: i32 = urow.get(0).unwrap(); + let user: i32 = urow3.get(0).unwrap(); + let partner: i32 = urow3.get(1).unwrap(); + if !(uid == user || uid == partner) { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + let ladderid: i32 = urow2.get(0).unwrap(); + let winner: String = urow2.get(1).unwrap(); + let score: String = urow2.get(2).unwrap(); + POOL.with(|poola| { + poola.get_conn().unwrap().exec_drop("Update ladder set winner =?, scores=? where id = ?", (winner, score, ladderid)).unwrap(); + poola.get_conn().unwrap().exec_drop("delete from winProposals where id = ?", (id, )).unwrap(); + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::PUT, "/proposal") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + let mut row: Option> = None; + let mut row2: Option> = None; + let ladderid = s.get("ladderid").unwrap().to_string(); + + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + row = it.next(); + let mut con2 = poola.get_conn().unwrap(); + let mut result2 = con2.exec_iter("Select inAtype, inA, inBtype, inB from ladder where deleted = 0 and id =? and winner ='0';", (&ladderid, )).unwrap(); + let mut it2 = result2.iter().unwrap(); + row2 = it2.next(); + }); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return Ok(response); + } + if row2.is_none() { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + let urow = row.unwrap().unwrap(); + let urow2 = row2.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let inAtype: String = urow2.get(0).unwrap(); + let mut inA: String = urow2.get(1).unwrap(); + let inBtype: String = urow2.get(2).unwrap(); + let mut inB: String = urow2.get(3).unwrap(); + if s.contains_key("score") && s.contains_key("winner") { + if s.get("winner").unwrap() != "A" && s.get("winner").unwrap() != "B" { + *response.body_mut() = "{\"error\":\"winner must be A or B\"}".into(); + return Ok(response); + } + if inAtype != "R" { + let mut res3: Option> = None; + POOL.with(|poola| { + res3 = poola.get_conn().unwrap() + .exec_iter("WITH RECURSIVE menu_tree +AS ( +SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val' from ladder where id =? + UNION ALL + SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) + FROM menu_tree mn, inz.ladder la + WHERE mn.val= la.id and mn.type != 'R' +) + SELECT * FROM menu_tree where type = 'R'", (&ladderid, ), + ).unwrap().iter().unwrap().next(); + }); + if !res3.is_none() { + let urow3 = res3.unwrap().unwrap(); + inA = urow3.get(1).unwrap(); + } else { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + } + if inBtype != "R" { + let mut res3: Option> = None; + POOL.with(|poola| { + res3 = poola.get_conn().unwrap() + .exec_iter("WITH RECURSIVE menu_tree +AS ( +SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val' from ladder where id =? + UNION ALL + SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) + FROM menu_tree mn, inz.ladder la + WHERE mn.val= la.id and mn.type != 'R' +) + SELECT * FROM menu_tree where type = 'R'", (&ladderid, ), + ).unwrap().iter().unwrap().next(); + }); + if !res3.is_none() { + let urow3 = res3.unwrap().unwrap(); + inB = urow3.get(1).unwrap(); + } else { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + } + let mut res3: Option> = None; + let mut res4: Option> = None; + POOL.with(|poola| { + res3 = poola.get_conn().unwrap() + .exec_iter("SELECT userid, partner FROM inz.registrations where id = ?;", (&inA, ), + ).unwrap().iter().unwrap().next(); + res4 = poola.get_conn().unwrap() + .exec_iter("SELECT userid, partner FROM inz.registrations where id = ?;", (&inB, ), + ).unwrap().iter().unwrap().next(); + }); + let urow3 = res3.unwrap().unwrap(); + let urow4 = res4.unwrap().unwrap(); + let mut prop = ""; + let mut acc = ""; + let u1: i32 = urow3.get(0).unwrap(); + let u2: i32 = urow3.get(1).unwrap(); + let u3: i32 = urow4.get(0).unwrap(); + let u4: i32 = urow4.get(1).unwrap(); + if u1 == id || u2 == id { + prop = &inA; + acc = &inB; + } else { + if u3 == id || u4 == id { + prop = &inB; + acc = &inA; + } else { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + } + POOL.with(|poola| { + let nid = "{\"id\":".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`winProposals`(ladderid, winner, proposer, approver, score) VALUES (?,?,?,?,?);", (&ladderid, s.get("winner"), prop, acc, s.get("score"))).unwrap().last_insert_id().unwrap().to_string() + "\"}"; + *response.body_mut() = nid.into(); + }); + } else { + *response.body_mut() = "{\"error\":\"not all fields\"}".into(); + } + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::GET, "/ladders/solved") => { + let query: &str = req.uri().query().unwrap(); + let mut splited = query.split("="); + + let id = splited.next().unwrap(); + let val = splited.next().unwrap(); + if id != "id" { + *response.body_mut() = "{\"error\":\"id required\"}".into(); + return Ok(response); + } + POOL.with(|poola| { + let res = poola.get_conn().unwrap() + .exec_iter( + "SELECT id, inAtype, inA, inBtype, inB, winner, round, scores from ladder where deleted =0 and id = ?", (val, ), + ).unwrap().iter().unwrap().next(); + let res2 = poola.get_conn().unwrap() + .exec_iter("WITH RECURSIVE menu_tree +AS ( +SELECT if('A' ='A', inAtype, inBtype) as 'type', if('A' ='A', inA, inB) as 'val' from ladder where id =? + UNION ALL + SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) + FROM menu_tree mn, inz.ladder la + WHERE mn.val= la.id and mn.type != 'R' +) + SELECT * FROM menu_tree where type = 'R'", (val, ), + ).unwrap().iter().unwrap().next(); + let res3 = poola.get_conn().unwrap() + .exec_iter("WITH RECURSIVE menu_tree +AS ( +SELECT if('B' ='A', inAtype, inBtype) as 'type', if('B' ='A', inA, inB) as 'val' from ladder where id =? + UNION ALL + SELECT if(mn.type ='W', if(la.winner ='A', inAtype, if(la.winner ='B', la.inBtype, null)), if(la.winner ='A', la.inBtype, if(la.winner ='B', la.inAtype, null))) , if(mn.type ='W', if(la.winner ='A', la.inA, if(la.winner ='B', la.inB, null)), if(la.winner ='A', la.inB, if(la.winner ='B', la.inA, null))) + FROM menu_tree mn, inz.ladder la + WHERE mn.val= la.id and mn.type != 'R' +) + SELECT * FROM menu_tree where type = 'R'", (val, ), + ).unwrap().iter().unwrap().next(); + let ur = res.unwrap().unwrap(); + let id1: i32 = ur.get(0).unwrap(); + let mut inAtype: String = ur.get(1).unwrap(); + let mut inA: String = ur.get(2).unwrap(); + let mut inBtype: String = ur.get(3).unwrap(); + let mut inB: String = ur.get(4).unwrap(); + let winner: String = ur.get(5).unwrap(); + let round: String = ur.get(6).unwrap(); + let scores: String = ur.get(7).unwrap(); + if !res2.is_none() { + let urow3 = res2.unwrap().unwrap(); + inAtype = urow3.get(0).unwrap(); + inA = urow3.get(1).unwrap(); + } + if !res3.is_none() { + let urow4 = res3.unwrap().unwrap(); + inBtype = urow4.get(0).unwrap(); + inB = urow4.get(1).unwrap(); + } + let res = ladderRaw { id: id1, inAtype: inAtype, inA: inA, inBtype: inBtype, inB: inB, winner: winner, round: round, scores: scores }; + *response.body_mut() = serde_json::to_string(&res).unwrap().into(); + }); + } + (&Method::GET, "/ladders/raw") => { + let query: &str = req.uri().query().unwrap(); + let mut splited = query.split("="); + + let id = splited.next().unwrap(); + let val = splited.next().unwrap(); + if id != "tournamentid" { + *response.body_mut() = "{\"error\":\"tournamentid required\"}".into(); + return Ok(response); + } + POOL.with(|poola| { + let res = poola.get_conn().unwrap() + .exec_map( + "SELECT id, inAtype, inA, inBtype, inB, winner, round, scores from ladder where deleted =0 and tournamentid = ?", (val, ), + |(id, inAtype, inA, inBtype, inB, winner, round, scores)| { + ladderRaw { id, inAtype, inA, inBtype, inB, winner, round, scores } + }, + ); + *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); + }); + } + (&Method::POST, "/ladder") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("id") { + *response.body_mut() = "{\"error\":\"id is required\"}".into(); + return Ok(response); + } + + let mut row: Option> = None; + let mut row3: Option> = None; + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id, role from users where (role='2' or role='3' )and id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + row = it.next(); + }); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return Ok(response); + } + + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + let tournamentid = s.get("id"); + if role == "2" { + POOL.with(|poola| { + let mut con3 = poola.get_conn().unwrap(); + let mut result3 = con3.exec_iter("Select creator from tournaments where id = (Select tournamentid from ladder where id =?);", (&tournamentid, )).unwrap(); + let mut it3 = result3.iter().unwrap(); + row3 = it3.next(); + }); + let urow3 = row3.unwrap().unwrap(); + let creator: i32 = urow3.get(0).unwrap(); + if creator != id { + *response.status_mut() = StatusCode::NOT_FOUND; + return Ok(response); + } + } + POOL.with(|poola| { + if s.contains_key("inAtype") { + if s.get("inAtype").unwrap() != "R" && s.get("inAtype").unwrap() != "W" && s.get("inAtype").unwrap() != "L" { + *response.body_mut() = "{\"error\":\"inAtype must be R, W or L\"}".into(); + return; + } + poola.get_conn().unwrap().exec_drop("Update ladder set inAtype =? where id = ? and deleted =0", (s.get("inAtype"), &tournamentid)).unwrap(); + } + if s.contains_key("inBtype") { + if s.get("inBtype").unwrap() != "R" && s.get("inBtype").unwrap() != "W" && s.get("inBtype").unwrap() != "L" { + *response.body_mut() = "{\"error\":\"inBtype must be R, W or L\"}".into(); + return; + } + poola.get_conn().unwrap().exec_drop("Update ladder set inBtype =? where id = ? and deleted =0", (s.get("inBtype"), &tournamentid)).unwrap(); + } + if s.contains_key("inA") { + poola.get_conn().unwrap().exec_drop("Update ladder set inA =? where id = ? and deleted =0", (s.get("inA"), &tournamentid)).unwrap(); + } + if s.contains_key("inB") { + poola.get_conn().unwrap().exec_drop("Update ladder set inB =? where id = ? and deleted =0", (s.get("inB"), &tournamentid)).unwrap(); + } + if s.contains_key("winner") { + poola.get_conn().unwrap().exec_drop("Update ladder set winner =? where id = ? and deleted =0", (s.get("winner"), &tournamentid)).unwrap(); + } + if s.contains_key("round") { + poola.get_conn().unwrap().exec_drop("Update ladder set round =? where id = ? and deleted =0", (s.get("round"), &tournamentid)).unwrap(); + } + if s.contains_key("scores") { + poola.get_conn().unwrap().exec_drop("Update ladder set scores =? where id = ? and deleted =0", (s.get("scores"), &tournamentid)).unwrap(); + } + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::DELETE, "/ladder") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("id") { + *response.body_mut() = "{\"error\":\"id is required\"}".into(); + return Ok(response); + } + + let mut row: Option> = None; + let mut row3: Option> = None; + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id, role from users where (role='2' or role='3' )and id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + row = it.next(); + }); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return Ok(response); + } + + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + let tournamentid = s.get("id"); + if role == "2" { + POOL.with(|poola| { + let mut con3 = poola.get_conn().unwrap(); + let mut result3 = con3.exec_iter("Select creator from tournaments where id = (Select tournamentid from ladder where id =?);", (&tournamentid, )).unwrap(); + let mut it3 = result3.iter().unwrap(); + row3 = it3.next(); + }); + let urow3 = row3.unwrap().unwrap(); + let creator: i32 = urow3.get(0).unwrap(); + if creator != id { + *response.status_mut() = StatusCode::NOT_FOUND; + return Ok(response); + } + } + POOL.with(|poola| { + poola.get_conn().unwrap().exec_drop("Update ladder set deleted =1 where id = ?", (&s.get("id"), )).unwrap(); + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::PUT, "/ladder") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("inAtype") || !s.contains_key("inA") || !s.contains_key("inBtype") || !s.contains_key("inB") || !s.contains_key("round") || !s.contains_key("tournamentid") { + *response.body_mut() = "{\"error\":\"no all fields\"}".into(); + return Ok(response); + } + if s.get("inBtype").unwrap() != "R" && s.get("inBtype").unwrap() != "W" && s.get("inBtype").unwrap() != "L" { + *response.body_mut() = "{\"error\":\"inBtype must be R, W or L\"}".into(); + return Ok(response); + } + if s.get("inAtype").unwrap() != "R" && s.get("inAtype").unwrap() != "W" && s.get("inAtype").unwrap() != "L" { + *response.body_mut() = "{\"error\":\"inAtype must be R, W or L\"}".into(); + return Ok(response); + } + let mut row: Option> = None; + let mut row3: Option> = None; + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id, role from users where (role='2' or role='3' )and id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + row = it.next(); + }); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return Ok(response); + } + + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + let tournamentid = s.get("tournamentid"); + if role == "2" { + POOL.with(|poola| { + let mut con3 = poola.get_conn().unwrap(); + let mut result3 = con3.exec_iter("Select creator from tournaments where id = ?;", (&tournamentid, )).unwrap(); + let mut it3 = result3.iter().unwrap(); + row3 = it3.next(); + }); + let urow3 = row3.unwrap().unwrap(); + let creator: i32 = urow3.get(0).unwrap(); + if creator != id { + *response.status_mut() = StatusCode::NOT_FOUND; + return Ok(response); + } + } + POOL.with(|poola| { + let nid = "{\"id\":".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`ladder`(`inAtype`,`inA`,`inBtype`,`inB`,`winner`,`round`,`scores`,`tournamentid`,`deleted`) VALUES (?,?,?,?,'0',?,'-1',?,0);", (s.get("inAtype"), s.get("inA"), s.get("inBtype"), s.get("inB"), s.get("round"), s.get("tournamentid"))).unwrap().last_insert_id().unwrap().to_string() + "\"}"; + *response.body_mut() = nid.into(); + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::GET, "/leaderboard") => { + POOL.with(|poola| { + let res = poola.get_conn().unwrap() + .query_map( + "SELECT name, surname, ranking from users where deleted =0 order by ranking DESC", + |(name, surname, ranking)| { + leaderboard { name, surname, ranking } + }, + ); + *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); + }); + } + (&Method::POST, "/tournament/cancelTournament") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("id") { *response.body_mut() = "{\"error\":\"id required\"}".into(); return Ok(response); } @@ -91,7 +643,7 @@ async fn hello_world(req: Request) -> Result> { let mut con = poola.get_conn().unwrap(); let mut result = con.exec_iter("Select id,role from users where (role = '2' OR role = '3')AND id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); let mut it = result.iter().unwrap(); - let mut row = it.next(); + let row = it.next(); if row.is_none() { *response.status_mut() = StatusCode::FORBIDDEN; return; @@ -99,20 +651,233 @@ async fn hello_world(req: Request) -> Result> { let urow = row.unwrap().unwrap(); let id: i32 = urow.get(0).unwrap(); let role: String = urow.get(1).unwrap(); - if (role == "2") { - let mut conn1 = poola.get_conn().unwrap(); - let mut result1 = conn1.exec_iter("Select userid from registrations where id = ?", (&s.get("id"), )).unwrap(); - let mut it1 = result1.iter().unwrap(); - let mut row1 = it1.next(); - let urow1 = row1.unwrap().unwrap(); - let userid: String = urow1.get(0).unwrap(); - if userid != id.to_string() { - return; - } - poola.get_conn().unwrap().exec_drop("Update registrations set approval ='1' where id = ?", (&s.get("id"), )).unwrap(); - } else { - poola.get_conn().unwrap().exec_drop("Update registrations set approval ='1' where id = ?", (&s.get("id"), )).unwrap(); + let mut conn1 = poola.get_conn().unwrap(); + let mut result1 = conn1.exec_iter("Select creator, state from tournaments where id = ?", (&s.get("id"), )).unwrap(); + let mut it1 = result1.iter().unwrap(); + let row1 = it1.next(); + let urow1 = row1.unwrap().unwrap(); + let creator: i32 = urow1.get(0).unwrap(); + let state: i32 = urow1.get(1).unwrap(); + if state == 3 { + *response.status_mut() = StatusCode::BAD_REQUEST; + return; + } + if role == "2" { + if creator != id { + return; } + poola.get_conn().unwrap().exec_drop("Update tournaments set state =4 where id = ?", (&s.get("id"), )).unwrap(); + } else { + poola.get_conn().unwrap().exec_drop("Update tournaments set state =4 where id = ?", (&s.get("id"), )).unwrap(); + } + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::POST, "/tournament/endTournament") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + + let parsed: serde_json::Value = serde_json::from_slice(&byte_stream).unwrap(); + if parsed.get("id") == None { + *response.body_mut() = "{\"error\":\"id required\"}".into(); + return Ok(response); + } + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id,role from users where (role = '2' OR role = '3')AND id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + let row = it.next(); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return; + } + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + let mut conn1 = poola.get_conn().unwrap(); + let mut result1 = conn1.exec_iter("Select creator, state, approved from tournaments where id = ? b", (&parsed.get("id"), )).unwrap(); + let mut it1 = result1.iter().unwrap(); + let row1 = it1.next(); + let urow1 = row1.unwrap().unwrap(); + let creator: i32 = urow1.get(0).unwrap(); + let state: i32 = urow1.get(1).unwrap(); + let approved: i32 = urow1.get(2).unwrap(); + if state != 2 { + *response.status_mut() = StatusCode::BAD_REQUEST; + return; + } + if role == "2" { + if creator != id { + return; + } + poola.get_conn().unwrap().exec_drop("Update tournaments set state =3 where id = ?", (&parsed.get("id"), )).unwrap(); + } else { + poola.get_conn().unwrap().exec_drop("Update tournaments set state =3 where id = ?", (&parsed.get("id"), )).unwrap(); + } + if approved == 2 { + let arr: &Vec = parsed.get("results").unwrap().as_array().unwrap(); + for i in 0..arr.len() { + let cur: &Map = arr.get(i).unwrap().as_object().unwrap(); + poola.get_conn().unwrap().exec_drop("Update users set ranking =ranking+? where id = (Select userid from registrations where id = ?) or id = (Select partner from registrations where id = ?)", (&cur.get("points"), &cur.get("rid"), &cur.get("rid"))).unwrap(); + } + } + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::POST, "/tournament/startTournament") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("id") { + *response.body_mut() = "{\"error\":\"id required\"}".into(); + return Ok(response); + } + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id,role from users where (role = '2' OR role = '3')AND id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + let row = it.next(); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return; + } + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + let mut conn1 = poola.get_conn().unwrap(); + let mut result1 = conn1.exec_iter("Select creator, state from tournaments where id = ?", (&s.get("id"), )).unwrap(); + let mut it1 = result1.iter().unwrap(); + let row1 = it1.next(); + let urow1 = row1.unwrap().unwrap(); + let creator: i32 = urow1.get(0).unwrap(); + let state: i32 = urow1.get(1).unwrap(); + if state != 1 { + *response.status_mut() = StatusCode::BAD_REQUEST; + return; + } + if role == "2" { + if creator != id { + return; + } + poola.get_conn().unwrap().exec_drop("Update tournaments set state =2 where id = ?", (&s.get("id"), )).unwrap(); + } else { + poola.get_conn().unwrap().exec_drop("Update tournaments set state =2 where id = ?", (&s.get("id"), )).unwrap(); + } + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::POST, "/tournament/closeRegistrations") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("id") { + *response.body_mut() = "{\"error\":\"id required\"}".into(); + return Ok(response); + } + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id,role from users where (role = '2' OR role = '3')AND id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + let row = it.next(); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return; + } + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + let mut conn1 = poola.get_conn().unwrap(); + let mut result1 = conn1.exec_iter("Select creator, state from tournaments where id = ?", (&s.get("id"), )).unwrap(); + let mut it1 = result1.iter().unwrap(); + let row1 = it1.next(); + let urow1 = row1.unwrap().unwrap(); + let creator: i32 = urow1.get(0).unwrap(); + let state: i32 = urow1.get(1).unwrap(); + if state != 0 { + *response.status_mut() = StatusCode::BAD_REQUEST; + return; + } + if role == "2" { + if creator != id { + return; + } + poola.get_conn().unwrap().exec_drop("Update tournaments set state =1 where id = ?", (&s.get("id"), )).unwrap(); + } else { + poola.get_conn().unwrap().exec_drop("Update tournaments set state =1 where id = ?", (&s.get("id"), )).unwrap(); + } + }); + } else { + *response.status_mut() = StatusCode::UNAUTHORIZED; + } + } + (&Method::POST, "/registration/approve") => { + if req.headers().contains_key("Authorization") { + let mut tmp = req.headers().get("Authorization").unwrap().to_str().unwrap().split(" "); + let aa = tmp.next().unwrap(); + if aa != "Bearer" { + *response.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(response); + } + let token = tmp.next().unwrap().to_string(); + let byte_stream = hyper::body::to_bytes(req).await.unwrap(); + let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); + if !s.contains_key("id") { + *response.body_mut() = "{\"error\":\"id required\"}".into(); + return Ok(response); + } + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut result = con.exec_iter("Select id,role from users where (role = '2' OR role = '3')AND id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + let row = it.next(); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return; + } + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); + let role: String = urow.get(1).unwrap(); + if role == "2" { + let mut conn1 = poola.get_conn().unwrap(); + let mut result1 = conn1.exec_iter("Select userid from registrations where id = ?", (&s.get("id"), )).unwrap(); + let mut it1 = result1.iter().unwrap(); + let row1 = it1.next(); + let urow1 = row1.unwrap().unwrap(); + let userid: i32 = urow1.get(0).unwrap(); + if userid != id { + return; + } + poola.get_conn().unwrap().exec_drop("Update registrations set approval ='1' where id = ?", (&s.get("id"), )).unwrap(); + } else { + poola.get_conn().unwrap().exec_drop("Update registrations set approval ='1' where id = ?", (&s.get("id"), )).unwrap(); + } }); } else { *response.status_mut() = StatusCode::UNAUTHORIZED; @@ -140,7 +905,7 @@ async fn hello_world(req: Request) -> Result> { let mut con = poola.get_conn().unwrap(); let mut result = con.exec_iter("Select id,role from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); let mut it = result.iter().unwrap(); - let mut row = it.next(); + let row = it.next(); if row.is_none() { *response.status_mut() = StatusCode::FORBIDDEN; return; @@ -149,29 +914,29 @@ async fn hello_world(req: Request) -> Result> { let urow = row.unwrap().unwrap(); let id: i32 = urow.get(0).unwrap(); let role: String = urow.get(1).unwrap(); - if (role == "1") { + if role == "1" { let res = poola.get_conn().unwrap() .exec_map( - "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`FROM `inz`.`registrations` where tournamentid= ? and userid=?;", (&val, id), - |(id, userid, tournamentid, paymenttype, paymentstatus, approval)| { - Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval } + "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner -?);", (&val, id, id), + |(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| { + Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); } else { - if (role == "2") { + if role == "2" { let mut conn1 = poola.get_conn().unwrap(); - let mut result1 = conn1.exec_iter("Select userid from registrations where id = ?", (&val, )).unwrap(); + let mut result1 = conn1.exec_iter("Select creator from tournaments where id = ?", (&val, )).unwrap(); let mut it1 = result1.iter().unwrap(); - let mut row1 = it1.next(); + let row1 = it1.next(); let urow1 = row1.unwrap().unwrap(); - let userid: String = urow1.get(0).unwrap(); - if userid != id.to_string() { + let userid: i32 = urow1.get(0).unwrap(); + if userid != id { let res = poola.get_conn().unwrap() .exec_map( - "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`FROM `inz`.`registrations` where tournamentid= ? and userid=?;", (&val, id), - |(id, userid, tournamentid, paymenttype, paymentstatus, approval)| { - Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval } + "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ? and (userid=? or partner -?);", (&val, id, id), + |(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| { + Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); @@ -181,18 +946,18 @@ async fn hello_world(req: Request) -> Result> { let res = poola.get_conn().unwrap() .exec_map( - "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`FROM `inz`.`registrations` where tournamentid= ?;", (&val, ), - |(id, userid, tournamentid, paymenttype, paymentstatus, approval)| { - Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval } + "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ?;", (&val, ), + |(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| { + Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); } else { let res = poola.get_conn().unwrap() .exec_map( - "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval`FROM `inz`.`registrations` where tournamentid= ?;", (&val, ), - |(id, userid, tournamentid, paymenttype, paymentstatus, approval)| { - Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval } + "SELECT `registrations`.`id`,`registrations`.`userid`,`registrations`.`tournamentid`,`registrations`.`paymenttype`,`registrations`.`paymentstatus`,`registrations`.`approval` ,`registrations`.`partner` FROM `inz`.`registrations` where tournamentid= ?;", (&val, ), + |(id, userid, tournamentid, paymenttype, paymentstatus, approval, partner)| { + Registration { id, userid, tournamentid, paymenttype, paymentstatus, approval, partner } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); @@ -277,7 +1042,7 @@ async fn hello_world(req: Request) -> Result> { *response.body_mut() = Body::from("{\"error\":\"id is required\"}"); return; } - poola.get_conn().unwrap().exec_drop("Update users set deleted =1 where id = ?", (&s.contains_key("id"), )).unwrap(); + poola.get_conn().unwrap().exec_drop("Update users set deleted =1 where id = ?", (&s.get("id"), )).unwrap(); }); } else { *response.status_mut() = StatusCode::UNAUTHORIZED; @@ -304,9 +1069,9 @@ async fn hello_world(req: Request) -> Result> { } let res = poola.get_conn().unwrap() .query_map( - "SELECT `id`, `name`, `surname`, `role`, `login`, `mail`, `phone`,`deleted` from users ", - |(id, name, surname, role, login, mail, phone, deleted)| { - Usera { id, name, surname, role, login, mail, phone, deleted } + "SELECT `id`, `name`, `surname`, `role`, `login`, `mail`, `phone`,`deleted`, `ranking` from users ", + |(id, name, surname, role, login, mail, phone, deleted, ranking)| { + Usera { id, name, surname, role, login, mail, phone, deleted, ranking } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); @@ -386,6 +1151,9 @@ async fn hello_world(req: Request) -> Result> { if s.contains_key("roles") { poola.get_conn().unwrap().exec_drop("Update tournaments set roles =? where id = ?", (s.get("roles"), &s.get("id"))).unwrap(); } + if s.contains_key("currentRound") { + poola.get_conn().unwrap().exec_drop("Update tournaments set currentRound =? where id = ?", (s.get("currentRound"), &s.get("id"))).unwrap(); + } }); } else { *response.status_mut() = StatusCode::UNAUTHORIZED; @@ -412,9 +1180,9 @@ async fn hello_world(req: Request) -> Result> { } let res = poola.get_conn().unwrap() .query_map( - "SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved,deleted from tournaments ", - |(id, name, type_of_ladder, points_for_tournament, places, roles, creator, approved, deleted)| { - tournamenta { id, name, typeOfLadder: type_of_ladder, places, roles, creator, pointsForTournament: points_for_tournament, approved, deleted } + "SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved,deleted, state, currentRound from tournaments ", + |(id, name, type_of_ladder, points_for_tournament, places, roles, creator, approved, deleted, state, currentRound)| { + tournamenta { id, name, typeOfLadder: type_of_ladder, places, roles, creator, pointsForTournament: points_for_tournament, approved, deleted, state, currentRound } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); @@ -453,7 +1221,7 @@ async fn hello_world(req: Request) -> Result> { } let urow2 = row2.unwrap().unwrap(); let approved: i32 = urow2.get(0).unwrap(); - if (approved == 1) { + if approved == 1 { POOL.with(|poola| { poola.get_conn().unwrap().exec_drop("Update tournaments set approved =2 where id = ?", (s.get("id").unwrap(), )).unwrap(); }); @@ -511,7 +1279,7 @@ async fn hello_world(req: Request) -> Result> { let role: String = urow.get(1).unwrap(); let paymenttype: String = urow2.get(0).unwrap(); let tournamentid: String = urow2.get(1).unwrap(); - if (role == "2") { + if role == "2" { POOL.with(|poola| { let mut con3 = poola.get_conn().unwrap(); let mut result3 = con3.exec_iter("Select creator from tournaments where id = ?;", (&tournamentid, )).unwrap(); @@ -519,8 +1287,8 @@ async fn hello_world(req: Request) -> Result> { row3 = it3.next(); }); let urow3 = row3.unwrap().unwrap(); - let creator: String = urow3.get(0).unwrap(); - if creator != id.to_string() { + let creator: i32 = urow3.get(0).unwrap(); + if creator != id { *response.status_mut() = StatusCode::NOT_FOUND; return Ok(response); } @@ -537,7 +1305,7 @@ async fn hello_world(req: Request) -> Result> { *response.status_mut() = StatusCode::UNAUTHORIZED; } } - (&Method::GET, "/registration/paymentstatus") => { + (&Method::GET, "/registration/paymentstatus") => { if req.headers().contains_key("Authorization") { let query: &str = req.uri().query().unwrap(); let mut splited = query.split("="); @@ -580,10 +1348,10 @@ async fn hello_world(req: Request) -> Result> { let role: String = urow.get(1).unwrap(); let paymentstatus: String = urow2.get(0).unwrap(); let paymentreference: String = urow2.get(1).unwrap(); - let userid: String = urow2.get(2).unwrap(); + let userid: i32 = urow2.get(2).unwrap(); let paymenttype: String = urow2.get(3).unwrap(); if role == "1" || role == "2" { - if userid != id.to_string() { + if userid != id { *response.status_mut() = StatusCode::NOT_FOUND; return Ok(response); } @@ -593,9 +1361,9 @@ async fn hello_world(req: Request) -> Result> { let client = Client::new(); let req = Request::builder() .method(Method::GET) - .uri("http://10.1.6.101:8082/api/v1/stores/*****/invoices/".to_owned() + &paymentreference) + .uri("http://10.1.6.101:8082/api/v1/stores/6N6yuxW7HGSbHnsLM1csvFqRz72DP2EkY5YFBz4jGdQK/invoices/".to_owned() + &paymentreference) .header("content-type", "application/json") - .header("Authorization", "token ******").body(Body::empty()).unwrap(); + .header("Authorization", "token 305562c7ec5f6d6870e534abf86084b085696f92").body(Body::empty()).unwrap(); let resp = client.request(req).await.unwrap(); let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap(); let stat: String = parsed.get("status").unwrap().as_str().unwrap().into(); @@ -645,35 +1413,47 @@ async fn hello_world(req: Request) -> Result> { let byte_stream = hyper::body::to_bytes(req).await.unwrap(); let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); let mut row: Option> = None; - POOL.with(|poola| { - let mut con = poola.get_conn().unwrap(); - - let mut result = con.exec_iter("Select id from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); - let mut it = result.iter().unwrap(); - row = it.next(); - }); - if row.is_none() { - *response.status_mut() = StatusCode::FORBIDDEN; - return Ok(response); - } - let urow = row.unwrap().unwrap(); - let id: i32 = urow.get(0).unwrap(); - if s.contains_key("tournament") && s.contains_key("paymentmethod") { + let mut row2: Option> = None; + if s.contains_key("tournament") && s.contains_key("paymentmethod") && s.contains_key("partner") { let tournament = s.get("tournament").unwrap().to_string(); + let partner = s.get("partner").unwrap().to_string(); + + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + + let mut result = con.exec_iter("Select id from users where id =(SELECT user FROM `inz`.`sessions` where token = ? and expire > NOW());", (&token, )).unwrap(); + let mut it = result.iter().unwrap(); + row = it.next(); + let mut con2 = poola.get_conn().unwrap(); + + let mut result2 = con2.exec_iter("Select id from tournaments where state = 0 and id =?;", (&tournament, )).unwrap(); + let mut it2 = result2.iter().unwrap(); + row2 = it2.next(); + }); + if row.is_none() { + *response.status_mut() = StatusCode::FORBIDDEN; + return Ok(response); + } + if row2.is_none() { + *response.status_mut() = StatusCode::BAD_REQUEST; + return Ok(response); + } + let urow = row.unwrap().unwrap(); + let id: i32 = urow.get(0).unwrap(); let paymentmethod = s.get("paymentmethod").unwrap().to_string(); if paymentmethod == "btc" { let client = Client::new(); let req = Request::builder() .method(Method::POST) - .uri("http://10.1.6.101:8082/api/v1/stores/****/invoices") + .uri("http://10.1.6.101:8082/api/v1/stores/6N6yuxW7HGSbHnsLM1csvFqRz72DP2EkY5YFBz4jGdQK/invoices") .header("content-type", "application/json") - .header("Authorization", "token *****") + .header("Authorization", "token 305562c7ec5f6d6870e534abf86084b085696f92") .body(Body::from("{\"metadata\": {\"orderId\": \"id123\"},\"checkout\": {\"speedPolicy\": \"LowMediumSpeed\",\"redirectURL\":\"https://www.google.com\"},\"amount\": \"1.00\",\"currency\": \"PLN\"}")).unwrap(); let resp = client.request(req).await.unwrap(); let parsed: serde_json::Value = serde_json::from_slice(hyper::body::to_bytes(resp.into_body()).await.unwrap().as_ref()).unwrap(); POOL.with(|poola| { let tmp: String = parsed.get("id").unwrap().as_str().unwrap().into(); - let nid: String = poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`)VALUES(?,?,'btc','PENDING',0,?);", (id, tournament, &tmp)).unwrap().last_insert_id().unwrap().to_string(); + let nid: String = poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`, `partner`)VALUES(?,?,'btc','PENDING',0,?,?);", (id, tournament, &tmp, partner)).unwrap().last_insert_id().unwrap().to_string(); let mut checkout: String = parsed.get("checkoutLink").unwrap().as_str().unwrap().into(); checkout = checkout.replace("http://10.1.6.101:8082/", "https://btcpay.dragonmaster.pl/"); *response.body_mut() = Body::from("{\"id\":\"".to_owned() + &nid + "\",\"url\":\"" + &*checkout + "\"}"); @@ -681,7 +1461,7 @@ async fn hello_world(req: Request) -> Result> { } else { if paymentmethod == "cash" { POOL.with(|poola| { - let nid = "{\"id\":".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`)VALUES(?,?,'cash','PENDING',0,'N/A');", (id, tournament)).unwrap().last_insert_id().unwrap().to_string() + "\"}"; + let nid = "{\"id\":\"".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`registrations`(`userid`,`tournamentid`,`paymenttype`,`paymentstatus`,`approval`,`paymentreference`, `partner`)VALUES(?,?,'cash','PENDING',0,'N/A',?);", (id, tournament, partner)).unwrap().last_insert_id().unwrap().to_string() + "\"}"; *response.body_mut() = nid.into(); }); } else { @@ -746,6 +1526,9 @@ async fn hello_world(req: Request) -> Result> { if s.contains_key("roles") { poola.get_conn().unwrap().exec_drop("Update tournaments set roles =? where id = ? and deleted =0", (s.get("roles"), &tid)).unwrap(); } + if s.contains_key("currentRound") { + poola.get_conn().unwrap().exec_drop("Update tournaments set currentRound =? where id = ? and deleted =0", (s.get("currentRound"), &tid)).unwrap(); + } *response.body_mut() = "{}".into(); } else { *response.body_mut() = "{\"error\":\"not all fields\"}".into(); @@ -806,9 +1589,9 @@ async fn hello_world(req: Request) -> Result> { POOL.with(|poola| { let res = poola.get_conn().unwrap() .query_map( - "SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved from tournaments where deleted =0", - |(id, name, type_of_ladder, points_for_tournament, places, roles, creator, approved)| { - tournament { id, name, typeOfLadder: type_of_ladder, places, roles, creator, pointsForTournament: points_for_tournament, approved } + "SELECT id, name, typeOfLadder, pointsForTournament, places, roles, creator,approved, state, currentRound from tournaments where deleted =0", + |(id, name, type_of_ladder, points_for_tournament, places, roles, creator, approved, state, currentRound)| { + tournament { id, name, typeOfLadder: type_of_ladder, places, roles, creator, pointsForTournament: points_for_tournament, approved, state, currentRound } }, ); *response.body_mut() = serde_json::to_string(&res.unwrap()).unwrap().into(); @@ -852,7 +1635,7 @@ async fn hello_world(req: Request) -> Result> { if ranked != "0" && ranked != "1" { ranked = String::from("0"); } - let str = "{\"id\":".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`tournaments`(`name`,`typeOfLadder`,`pointsForTournament`,`places`,`roles`,`creator`,`deleted`,`approved`) VALUES (?,?,?,?,?,?,0,?);", (name, type_of_ladder, points_for_tournament, places, roles, id, ranked)).unwrap().last_insert_id().unwrap().to_string() + "}"; + let str = "{\"id\":".to_owned() + &poola.get_conn().unwrap().exec_iter("INSERT INTO `inz`.`tournaments`(`name`,`typeOfLadder`,`pointsForTournament`,`places`,`roles`,`creator`,`deleted`,`approved`,`state`,`currentRound`) VALUES (?,?,?,?,?,?,0,?,0,0);", (name, type_of_ladder, points_for_tournament, places, roles, id, ranked)).unwrap().last_insert_id().unwrap().to_string() + "}"; *response.body_mut() = str.into(); } else { *response.body_mut() = "{\"error\":\"not all fields\"}".into(); @@ -898,7 +1681,7 @@ async fn hello_world(req: Request) -> Result> { poola.get_conn().unwrap().exec_drop("Update users set mail =? where id = ?", (s.get("mail"), idi)).unwrap(); } if s.contains_key("phone") { - poola.get_conn().unwrap().exec_drop("Update users set phone =? where id = ?", (s.get("phone "), idi)).unwrap(); + poola.get_conn().unwrap().exec_drop("Update users set phone =? where id = ?", (s.get("phone"), idi)).unwrap(); } }); } else { @@ -924,7 +1707,7 @@ async fn hello_world(req: Request) -> Result> { return; } let urow = row.unwrap().unwrap(); - let a = User { id: urow.get(0).unwrap(), name: urow.get(1).unwrap(), surname: urow.get(2).unwrap(), role: urow.get(3).unwrap(), login: urow.get(4).unwrap(), phone: urow.get(7).unwrap(), mail: urow.get(6).unwrap() }; + let a = User { id: urow.get(0).unwrap(), name: urow.get(1).unwrap(), surname: urow.get(2).unwrap(), role: urow.get(3).unwrap(), login: urow.get(4).unwrap(), phone: urow.get(7).unwrap(), mail: urow.get(6).unwrap(), ranking: urow.get(8).unwrap() }; *response.body_mut() = serde_json::to_string(&a).unwrap().into(); }); @@ -935,27 +1718,22 @@ async fn hello_world(req: Request) -> Result> { (&Method::PUT, "/user/create") => { let byte_stream = hyper::body::to_bytes(req).await.unwrap(); let s: HashMap = serde_json::from_slice(&byte_stream).unwrap(); - if s.contains_key("username") && s.contains_key("name") && s.contains_key("surname") && s.contains_key("password") && s.contains_key("role") && s.contains_key("mail") && s.contains_key("phone") { + if s.contains_key("username") && s.contains_key("name") && s.contains_key("surname") && s.contains_key("password") && s.contains_key("mail") && s.contains_key("phone") { let username = s.get("username").unwrap().to_string(); let name = s.get("name").unwrap().to_string(); let surname = s.get("surname").unwrap().to_string(); let password = hash(s.get("password").unwrap().to_string(), DEFAULT_COST - 6).unwrap(); - let role = s.get("role").unwrap().to_string(); let mail = s.get("mail").unwrap().to_string(); let phone = s.get("phone").unwrap().to_string(); - if role == "1" || role == "2" { - POOL.with(|poola| { - let mut con = poola.get_conn().unwrap() ; - let mut a = con.exec_iter("select `login` from users where login = ?", (&username,)).unwrap(); - let it = a.iter().unwrap().next(); - if(it.is_none()) { - poola.get_conn().unwrap().exec_drop("INSERT INTO `inz`.`users`(`name`,`surname`,`role`,`login`,`password`,`mail`,`phone`,`deleted`)VALUES (?,?,?,?,?,?,?,0);", (name, surname, role, username, password, mail, phone)).unwrap(); - } - }); - *response.body_mut() = "{}".into(); - } else { - *response.body_mut() = "{\"error\":\"bad role\"}".into(); - } + POOL.with(|poola| { + let mut con = poola.get_conn().unwrap(); + let mut a = con.exec_iter("select `login` from users where login = ?", (&username, )).unwrap(); + let it = a.iter().unwrap().next(); + if it.is_none() { + poola.get_conn().unwrap().exec_drop("INSERT INTO `inz`.`users`(`name`,`surname`,`role`,`login`,`password`,`mail`,`phone`,`deleted`,`ranking`)VALUES (?,?,1,?,?,?,?,0,0);", (name, surname, username, password, mail, phone)).unwrap(); + } + }); + *response.body_mut() = "{}".into(); } else { *response.body_mut() = "{\"error\":\"not all fields\"}".into(); } diff --git a/backend/src/main1.rs b/backend/src/main1.rs deleted file mode 100644 index db48c7a..0000000 --- a/backend/src/main1.rs +++ /dev/null @@ -1,55 +0,0 @@ -use serde_derive::{Serialize, Deserialize}; -use mysql::*; -use mysql::prelude::*; -use std::convert::Infallible; -use std::net::SocketAddr; -use hyper::{Body, Request, Response, Server}; -use hyper::service::{make_service_fn, service_fn}; -#[derive(Serialize, Deserialize)] -struct dane { - id:i32, - data:String -} - -fn getJson() -> Vec { - let url = "mysql://inz:HaLzqw68CbabS8Smz3Vx!@localhost:3306/inz"; - -let opts = Opts::from_url(url).unwrap(); -let pool = Pool::new(opts).unwrap(); -let mut conn = pool.get_conn().unwrap(); -let res = conn - .query_map( - "SELECT id, data from dane", - |(id,data)| { - dane { id,data } - }, - ); - return res.unwrap(); -} -async fn hello_world(_req: Request) -> Result> { - let path :String = _req.uri().path().to_string(); - if path != "/mysql"{ -return Ok(Response::new(path.into())); -}else{ - return Ok(Response::new(serde_json::to_string(&getJson()).unwrap().into())) - } -} -#[tokio::main] -async fn main() { - let addr = SocketAddr::from(([0, 0, 0, 0], 1000)); - - // A `Service` is needed for every connection, so this - // creates one from our `hello_world` function. - let make_svc = make_service_fn(|_conn| async { - // service_fn converts our function into a `Service` - Ok::<_, Infallible>(service_fn(hello_world)) - }); - - let server = Server::bind(&addr).serve(make_svc); - - // Run this server for... forever! - if let Err(e) = server.await { - eprintln!("server error: {}", e); - } - -}