aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCurly Bryce <curlybryce@protonmail.com>2024-07-03 19:13:13 -0600
committerCurly Bryce <curlybryce@protonmail.com>2024-07-03 19:13:13 -0600
commitc06632d0dfdb19e047ae1175a46b926e6772650f (patch)
treeca41cd0637af6d21a850b88cc0b8d143a06d0014
parent99f49f5bedbf9cdd3ccdd689da3acb4fe8ff685e (diff)
downloadpoko_server-c06632d0dfdb19e047ae1175a46b926e6772650f.tar.gz
poko_server-c06632d0dfdb19e047ae1175a46b926e6772650f.tar.bz2
poko_server-c06632d0dfdb19e047ae1175a46b926e6772650f.zip
Serialize, Deserialize UID to make coding easier
-rw-r--r--TODO1
-rw-r--r--src/db.rs64
-rw-r--r--src/main.rs88
-rw-r--r--src/uid.rs78
4 files changed, 136 insertions, 95 deletions
diff --git a/TODO b/TODO
index 2aea99f..2ee5694 100644
--- a/TODO
+++ b/TODO
@@ -1,5 +1,4 @@
Need to make a proper http status code thingy
-Deleting of users
Transfers
Token Values
Token Stock Prices (Values)
diff --git a/src/db.rs b/src/db.rs
index 43a9f9c..a6ca7b0 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -127,12 +127,12 @@ impl User {
pub fn get_name(&self) -> String {
self.name.clone()
}
- pub fn hex_id(&self) -> String {
- self.id.to_hex()
- }
pub fn get_tokovec(&self) -> Vec<Token> {
self.tokovec.clone()
}
+ pub fn get_id(&self) -> UID {
+ self.id
+ }
}
#[derive(Serialize, Deserialize)]
@@ -179,22 +179,18 @@ impl DB {
DB { uid_generator: uid::Generator::new(), users: vec![], config }
}
- pub async fn get_user(&self, id: &str) -> Result<&User, String> {
- match UID::from(id.to_string()) {
- Ok(n) => {
- for u in self.users.iter() {
- if u.id == n {
- return Ok(u)
- }
- }
- },
- Err(_) => (),
+ pub fn get_user(&self, id: UID) -> Result<&User, String> {
+ for u in self.users.iter() {
+ if u.id == id {
+ return Ok(u)
+ }
}
Err("Not Found".into())
}
- pub async fn get_user_authenticated(&self, id: &str, session: &String) -> Result<&User, String> {
- match self.get_user(id).await {
+
+ pub async fn get_user_authenticated(&self, id: UID, session: &String) -> Result<&User, String> {
+ match self.get_user(id) {
Ok(u) => {
if u.authenticate(session) {
Ok(u)
@@ -205,16 +201,11 @@ impl DB {
Err(n) => Err(n)
}
}
- pub async fn get_mut_user(&mut self, id: &str) -> Result<&mut User, String> {
- match UID::from(id.to_string()) {
- Ok(n) => {
- for u in self.users.iter_mut() {
- if u.id == n {
- return Ok(u)
- }
- }
- },
- Err(_) => (),
+ pub async fn get_mut_user(&mut self, id: UID) -> Result<&mut User, String> {
+ for u in self.users.iter_mut() {
+ if u.id == id {
+ return Ok(u)
+ }
}
Err("Not Found".into())
@@ -250,7 +241,7 @@ impl DB {
self.save().await
}
- pub async fn login(&mut self, id: &String, password: &String, clientid: &String) -> Result<String, String> {
+ pub async fn login(&mut self, id: UID, password: &String, clientid: &String) -> Result<String, String> {
let r = match self.get_mut_user(id).await {
Ok(n) => {
n.login(password, clientid)
@@ -261,7 +252,7 @@ impl DB {
let _ = self.save().await;
r
}
- pub async fn logout(&mut self, id: &String, session: &String) -> Result<(), String> {
+ pub async fn logout(&mut self, id: UID, session: &String) -> Result<(), String> {
let r = match self.get_mut_user(id).await {
Ok(n) => {
n.logout(session)
@@ -272,7 +263,7 @@ impl DB {
let _ = self.save().await;
r
}
- pub async fn logout_all(&mut self, id: &String, session: &String) -> Result<String, String> {
+ pub async fn logout_all(&mut self, id: UID, session: &String) -> Result<String, String> {
let r = match self.get_mut_user(id).await {
Ok(n) => {
n.clear_sessions(session);
@@ -285,8 +276,8 @@ impl DB {
r
}
- pub async fn get_sessions(&self, id: &String, session: &String) -> Result<Vec<(String, String)>, String> {
- let r = match self.get_user(id).await {
+ pub async fn get_sessions(&self, id: UID, session: &String) -> Result<Vec<(String, String)>, String> {
+ let r = match self.get_user(id) {
Ok(n) => {
n.get_sessions(session)
},
@@ -297,17 +288,12 @@ impl DB {
r
}
- pub async fn delete_user(&mut self, id: &String, session: &String) -> Result<String, String> {
- match UID::from(id.clone()) {
- Ok(n) => {
- self.users = self.users.clone().into_iter().filter(|u| !u.authenticate(session) && n != u.id).collect();
- self.uid_generator.delete_uid(n);
- },
- Err(n) => return Err(n)
- };
+ pub async fn delete_user(&mut self, id: UID, session: &String) -> Result<String, String> {
+ self.users = self.users.clone().into_iter().filter(|u| !u.authenticate(session) && id != u.id).collect();
+ self.uid_generator.delete_uid(id);
// Validate
- let r = match self.get_user(id).await {
+ let r = match self.get_user(id) {
Ok(_) => Err("Could not delete".into()),
Err(_) => {
Ok("Deleted".into())
diff --git a/src/main.rs b/src/main.rs
index 709b5b3..aad989f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,10 +8,7 @@ use tokio::sync::Mutex;
use uid::UID;
mod db;
-use db::DB;
-use db::User;
-use db::Config;
-use db::Token;
+use db::{DB, User, Config, Token, Color};
#[get("/")]
async fn index() -> &'static str {
@@ -21,36 +18,36 @@ async fn index() -> &'static str {
#[derive(Serialize)]
struct AuthUserOut {
name: String,
- id: String,
+ id: UID,
tokovec: Vec<Token>,
}
impl Into<AuthUserOut> for User {
fn into(self) -> AuthUserOut {
- AuthUserOut { name: self.get_name(), id: self.hex_id(), tokovec: self.get_tokovec() }
+ AuthUserOut { name: self.get_name(), id: self.get_id(), tokovec: self.get_tokovec() }
}
}
#[derive(Serialize)]
struct UserOut {
name: String,
- id: String,
+ id: UID,
}
impl Into<UserOut> for User {
fn into(self) -> UserOut {
- UserOut { name: self.get_name(), id: self.hex_id() }
+ UserOut { name: self.get_name(), id: self.get_id() }
}
}
#[post("/get", data="<data>", format="json")]
async fn get_user_authenticated(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, Result<Json<AuthUserOut>, Json<String>>) {
let db = db.lock().await;
- match db.get_user_authenticated(&data.id, &data.session).await {
+ match db.get_user_authenticated(data.id, &data.session).await {
Ok(n) => (Status::Ok, Ok(Json(n.clone().into()))),
Err(n) => (Status::NotFound, Err(n.into()))
}
}
#[get("/<user>")]
-async fn get_user(user: &str, db: &State<Mutex<DB>>) -> (Status, Result<Json<UserOut>, Json<String>>) {
+async fn get_user(user: UID, db: &State<Mutex<DB>>) -> (Status, Result<Json<UserOut>, Json<String>>) {
let db = db.lock().await;
- match db.get_user(user).await {
+ match db.get_user(user) {
Ok(n) => (Status::Ok, Ok(Json(n.clone().into()))),
Err(n) => (Status::NotFound, Err(n.into()))
}
@@ -73,22 +70,22 @@ async fn get_all_users(db: &State<Mutex<DB>>) -> (Status, Result<Json<Vec<UserOu
}
}
-fn default_id() -> String {
- "random".into()
+fn default_id() -> UID {
+ uid::EMPTY_UID
}
#[derive(Deserialize)]
struct UserForm {
name: String,
password: String,
#[serde(default = "default_id")]
- id: String,
+ id: UID,
}
#[post("/register", data="<data>", format="json")]
async fn new_user(data: Json<UserForm>, db: &State<Mutex<DB>>) -> (Status, Result<(), Json<String>>) {
let mut db = db.lock().await;
let id;
- if data.id == "random".to_string() {
+ if data.id == uid::EMPTY_UID {
match db.uid_generator.new_uid() {
// Gotten a new UID to make a new user with
Ok(n) => id = Some(n),
@@ -96,25 +93,18 @@ async fn new_user(data: Json<UserForm>, db: &State<Mutex<DB>>) -> (Status, Resul
Err(n) => return (Status::InternalServerError, Err(n.clone().into())),
};
} else {
- match UID::from(data.id.clone()) {
- // Could not make UID from input
- Err(n) => return (Status::BadRequest, Err(n.into())),
- // Made a UID
- Ok(n) => {
- if db.uid_generator.is_taken(n) {
- // UID is taken
- return (Status::BadRequest, Err("UID is taken".to_string().into()));
- } else {
- // UID is not taken
- match db.uid_generator.add_uid(n) {
- // Could not add UID for some reason
- Err(n) => return (Status::InternalServerError, Err(n.into())),
- // Made
- Ok(n) => id = Some(n),
- };
- }
- },
- };
+ if db.uid_generator.is_taken(data.id) {
+ // UID is taken
+ return (Status::BadRequest, Err("UID is taken".to_string().into()));
+ } else {
+ // UID is not taken
+ match db.uid_generator.add_uid(data.id) {
+ // Could not add UID for some reason
+ Err(n) => return (Status::InternalServerError, Err(n.into())),
+ // Made
+ Ok(n) => id = Some(n),
+ };
+ }
}
match id {
@@ -132,14 +122,14 @@ async fn new_user(data: Json<UserForm>, db: &State<Mutex<DB>>) -> (Status, Resul
#[derive(Deserialize)]
struct LoginForm {
- id: String,
+ id: UID,
password: String,
clientid: String,
}
#[post("/login", data="<data>", format="json", rank=2)]
async fn login(data: Json<LoginForm>, db: &State<Mutex<DB>>) -> (Status, Json<String>) {
let mut db = db.lock().await;
- match db.login(&data.id, &data.password, &data.clientid).await {
+ match db.login(data.id, &data.password, &data.clientid).await {
Ok(n) => (Status::Ok, n.into()),
Err(n) => (Status::Unauthorized, n.into()),
}
@@ -147,13 +137,13 @@ async fn login(data: Json<LoginForm>, db: &State<Mutex<DB>>) -> (Status, Json<St
#[derive(Deserialize)]
struct LogoutForm {
- id: String,
+ id: UID,
session: String,
}
#[post("/logout", data="<data>", format="json")]
async fn logout(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, Result<(), Json<String>>) {
let mut db = db.lock().await;
- match db.logout(&data.id, &data.session).await {
+ match db.logout(data.id, &data.session).await {
Ok(_) => (Status::Ok, Ok(())),
Err(n) => (Status::Unauthorized, Err(n.into())),
}
@@ -161,7 +151,7 @@ async fn logout(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, Resul
#[post("/logout/all", data="<data>", format="json")]
async fn logout_all(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, Result<Json<String>, Json<String>>) {
let mut db = db.lock().await;
- match db.logout_all(&data.id, &data.session).await {
+ match db.logout_all(data.id, &data.session).await {
Ok(n) => (Status::Ok, Ok(n.into())),
Err(n) => (Status::Unauthorized, Err(n.into())),
}
@@ -169,7 +159,7 @@ async fn logout_all(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, R
#[post("/sessions", data="<data>", format="json")]
async fn get_sessions(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, Result<Json<Vec<(String, String)>>, Json<String>>) {
let db = db.lock().await;
- match db.get_sessions(&data.id, &data.session).await {
+ match db.get_sessions(data.id, &data.session).await {
Ok(n) => (Status::Ok, Ok(n.into())),
Err(n) => (Status::Unauthorized, Err(n.into())),
}
@@ -178,16 +168,30 @@ async fn get_sessions(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status,
#[post("/delete", data="<data>", format="json")]
async fn delete(data: Json<LogoutForm>, db: &State<Mutex<DB>>) -> (Status, Result<Json<String>, Json<String>>) {
let mut db = db.lock().await;
- match db.delete_user(&data.id, &data.session).await {
+ match db.delete_user(data.id, &data.session).await {
Ok(n) => (Status::Ok, Ok(n.into())),
Err(n) => (Status::Unauthorized, Err(n.into())),
}
}
+#[derive(Deserialize, Debug)]
+struct TransferForm {
+ id: UID,
+ session: String,
+ to: UID,
+ color: Color,
+ amount: usize,
+}
+#[post("/out", data="<data>", format="json")]
+async fn transfer_out(data: Json<TransferForm>, db: &State<Mutex<DB>>) -> (Status, Result<(), String>) {
+ println!("{:?}", data);
+ (Status::Ok, Ok(()))
+}
+
#[launch]
fn rocket() -> _ {
rocket::build().manage(Mutex::new(DB::load(Config::new())))
.mount("/", routes![index])
.mount("/user", routes![login, get_users_by_name, get_user_authenticated, get_user, new_user, get_all_users, logout, logout_all, get_sessions, delete])
- .mount("/transfer", routes![])
+ .mount("/transfer", routes![transfer_out])
} \ No newline at end of file
diff --git a/src/uid.rs b/src/uid.rs
index 886b9c8..6a748cd 100644
--- a/src/uid.rs
+++ b/src/uid.rs
@@ -1,24 +1,76 @@
-use serde::{Deserialize, Serialize};
+use base16ct::lower;
+use rocket::request::FromParam;
+use serde::{de::{IntoDeserializer, Visitor}, ser::SerializeTupleStruct, Deserialize, Deserializer, Serialize};
-#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UID(u8, u8);
-impl UID {
- pub fn to_hex(&self) -> String {
- hex::encode_upper(vec![self.0, self.1])
+pub const EMPTY_UID: UID = UID(0,0);
+struct UIDVisitor;
+impl<'de> Visitor<'de> for UIDVisitor {
+ type Value = UID;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ formatter.write_str("A Hex String containing 2 bytes")
}
- pub fn from(s: String) -> Result<Self, String> {
- if s.is_ascii() {
- if s.len() == 4 {
- match hex::decode(s) {
+
+ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error, {
+ println!("TEST");
+ if v.is_ascii() {
+ if v.len() == 4 {
+ match hex::decode(v) {
Ok(n) => Ok(UID(n[0], n[1])),
- Err(_) => Err("Could not decode hex".into())
+ Err(_) => panic!()
+ }
+ } else {
+ println!("NOT");
+ panic!()
+ }
+ } else {
+ panic!()
+ }
+ }
+}
+impl<'de> Deserialize<'de> for UID {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de> {
+ println!("TEST2");
+ deserializer.deserialize_str(UIDVisitor)
+ }
+}
+impl From<&str> for UID {
+ fn from(value: &str) -> Self {
+ if value.is_ascii() {
+ if value.len() == 4 {
+ match hex::decode(value) {
+ Ok(n) => UID(n[0], n[1]),
+ Err(_) => panic!("Could not decode hex")
}
-
} else {
- Err("UID length is incorrect".into())
+ panic!();
}
} else {
- Err("UID String is not valid".into())
+ panic!();
+ }
+ }
+}
+impl Serialize for UID {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer {
+ serializer.serialize_str(&lower::encode_string(&[self.0, self.1]))
+ }
+}
+impl<'a> FromParam<'a> for UID {
+ type Error = &'a str;
+
+ fn from_param(param: &'a str) -> Result<Self, Self::Error> {
+ let x: Result<UID, serde_json::Error> = param.into_deserializer().deserialize_str(UIDVisitor);
+ match x {
+ Ok(n) => Ok(n),
+ Err(_) => Err("Could not convert param using deserializer"),
}
}
}