From 9ef4176091f5627e70825b26d22154537c8517d3 Mon Sep 17 00:00:00 2001
From: BitHeaven <o.o@bitheaven.ru>
Date: Sun, 14 Jul 2024 21:15:00 +0300
Subject: [PATCH] Fatal broke (refactor)

---
 src/funcs.rs         |  38 ++++++++++++
 src/main.rs          | 142 +++----------------------------------------
 src/url.rs           |   6 ++
 src/url/authorize.rs |  19 ++++++
 src/url/index.rs     |   4 ++
 src/url/login.rs     |   2 +-
 src/url/nf.rs        |   4 ++
 src/url/recover.rs   |   4 ++
 src/url/register.rs  |  29 +++++++++
 src/url/user.rs      |  16 +++++
 10 files changed, 131 insertions(+), 133 deletions(-)
 create mode 100644 src/url/authorize.rs
 create mode 100644 src/url/index.rs
 create mode 100644 src/url/nf.rs
 create mode 100644 src/url/recover.rs
 create mode 100644 src/url/register.rs
 create mode 100644 src/url/user.rs

diff --git a/src/funcs.rs b/src/funcs.rs
index 94d2d18..43e33f6 100644
--- a/src/funcs.rs
+++ b/src/funcs.rs
@@ -378,3 +378,41 @@ pub async fn get_user(pool: DBPool, login: String) -> Res<Users, SkyError> {
 
 	Ok(q?)
 }
+
+fn get_cookies(headers: HeaderMap) -> HashMap<String, String> {
+	let header = headers.get(hyper::header::COOKIE);
+	let cookies = match header.is_none() {
+		false => header.unwrap().to_str().unwrap(),
+		_ => ""
+	};
+
+	double_split(cookies.to_owned(), ";", "=")
+}
+
+async fn authorize_user(pool: DBPool, token: String, session: String) {
+	let mut con = pool.get().await.unwrap();
+
+	let data: JsonMap<String, Json> = jwt_verify(pool.clone(), &token)
+		.await
+		.unwrap()
+		.claims
+		.as_object()
+		.unwrap()
+		.clone();
+
+	let login = data.get("login").unwrap().as_str();
+	let uuid = data.get("uuid").unwrap().as_str();
+
+	let _ = con.query_parse::<()>(&query!(
+		r#"INSERT INTO bitauth.v0 {
+			session: ?,
+			login: ?,
+			uuid: ?,
+			expire: ?
+		}"#,
+		session,
+		login,
+		uuid,
+		time() + APIV0_LIFETIME
+	)).await;
+}
diff --git a/src/main.rs b/src/main.rs
index cb6419f..f68834f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -84,10 +84,7 @@ use {
 		},
 		html::*,
 		funcs::*,
-		url::{
-			api,
-			login,
-		},
+		url,
 	},
 };
 
@@ -273,16 +270,16 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
 	}
 
 	(body, parts.status, restype) = match req.uri().path().as_ref() {
-		"/" => uri_index(),
-		"/cabinet" => login::uri_login(req, pool.clone(), &mut headers).await?,
-		"/login" => login::uri_login(req, pool.clone(), &mut headers).await?,
-		x if x == "/authorize" && logged => uri_authorize(req, pool.clone(), token).await?,
+		"/" => url::index::index(),
+		"/cabinet" => url::login::login(req, pool.clone(), &mut headers).await?,
+		"/login" => url::login::login(req, pool.clone(), &mut headers).await?,
+		x if x == "/authorize" && logged => url::authorize::authorize(req, pool.clone(), token).await?,
 		"/authorize" => uri_auth_required(req, &mut headers).await?,
-		"/register" => uri_register(req, pool.clone(), &mut headers).await?,
-		"/recover" => uri_recover(),
-		x if x.starts_with("/@") => uri_user(req, pool.clone()).await?,
-		x if x.starts_with("/api/") => api::endpoint(req, pool.clone()).await,
-		_ => uri_404()
+		"/register" => url::register::register(req, pool.clone(), &mut headers).await?,
+		"/recover" => url::recover::recover(),
+		x if x.starts_with("/@") => url::user::user(req, pool.clone()).await?,
+		x if x.starts_with("/api/") => url::api::endpoint(req, pool.clone()).await,
+		_ => url::nf::nf()
 	};
 
 	headers.insert(hyper::header::CONTENT_TYPE, restype);
@@ -292,35 +289,6 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
 	Ok(Response::from_parts(parts, Full::new(Bytes::from(body))))
 }
 
-fn get_cookies(headers: HeaderMap) -> HashMap<String, String> {
-	let header = headers.get(hyper::header::COOKIE);
-	let cookies = match header.is_none() {
-		false => header.unwrap().to_str().unwrap(),
-		_ => ""
-	};
-
-	double_split(cookies.to_owned(), ";", "=")
-}
-
-async fn uri_authorize(req: Request<Incoming>, pool: DBPool, token: String) -> Result<(String, StatusCode, HeaderValue)> {
-	// TODO: Forward for versions.
-	if *req.method() == Method::POST {
-		let r = double_split(req.uri().query().or(Some("")).unwrap().to_owned(), "&", "=");
-
-		let session = r.get("session");
-		let session = match session.is_none() {
-			false => session.unwrap().to_owned(),
-			_ => "".to_owned()
-		};
-
-		if session != "" && session.len() <= 128 {
-			authorize_user(pool.clone(), token, session).await;
-		}
-	}
-
-	let restype: HeaderValue = "text/html".parse().unwrap();
-	Ok((build_html(AUTHORIZE_HTML), StatusCode::OK, restype))
-}
 
 async fn uri_auth_required(req: Request<Incoming>, headers: &mut HeaderMap) -> Result<(String, StatusCode, HeaderValue)> {
 	let url = url_encode(req.uri().path_and_query().unwrap().as_str());
@@ -330,93 +298,3 @@ async fn uri_auth_required(req: Request<Incoming>, headers: &mut HeaderMap) -> R
 	let restype: HeaderValue = "text/html".parse().unwrap();
 	Ok(("".to_owned(), StatusCode::FOUND, restype))
 }
-
-async fn authorize_user(pool: DBPool, token: String, session: String) {
-	let mut con = pool.get().await.unwrap();
-
-	let data: JsonMap<String, Json> = jwt_verify(pool.clone(), &token)
-		.await
-		.unwrap()
-		.claims
-		.as_object()
-		.unwrap()
-		.clone();
-
-	let login = data.get("login").unwrap().as_str();
-	let uuid = data.get("uuid").unwrap().as_str();
-
-	let _ = con.query_parse::<()>(&query!(
-		r#"INSERT INTO bitauth.v0 {
-			session: ?,
-			login: ?,
-			uuid: ?,
-			expire: ?
-		}"#,
-		session,
-		login,
-		uuid,
-		time() + APIV0_LIFETIME
-	)).await;
-}
-
-fn uri_index() -> (String, StatusCode, HeaderValue) {
-	let restype: HeaderValue = "text/html".parse().unwrap();
-	(build_html(INDEX_HTML), StatusCode::OK, restype)
-}
-
-async fn uri_register(req: Request<Incoming>, pool: DBPool, headers: &mut HeaderMap) -> Result<(String, StatusCode, HeaderValue)> {
-	let mut body = "".to_owned();
-	let mut status = StatusCode::OK;
-	let restype: HeaderValue = "text/html".parse().unwrap();
-
-	if *req.method() == Method::POST {
-		let request = get_body_from_request(req).await?;
-		let request = String::from_utf8(request).unwrap();
-		let request = double_split(request, "&", "=");
-
-		match create_user(pool.clone(), request).await? {
-			true => {
-				println!("Created");
-				set_location(headers, "/login");
-			},
-			_ => {
-				println!("Failed");
-				set_location(headers, "/register");
-			}
-		}
-
-		status = StatusCode::FOUND;
-	}
-	else {
-		body = build_html(REG_HTML);
-	}
-
-	Ok((body, status, restype))
-}
-
-fn uri_recover() -> (String, StatusCode, HeaderValue) {
-	let restype: HeaderValue = "text/html".parse().unwrap();
-	(build_html(RECOVER_HTML), StatusCode::OK, restype)
-}
-
-async fn uri_user(req: Request<Incoming>, pool: DBPool) -> Res<(String, StatusCode, HeaderValue), SkyError> {
-	let uri: &str = req.uri().path().as_ref();
-	let login = &uri[2..uri.len()];
-	let body: String;
-
-	let user = get_user(pool, login.to_string()).await;
-	if user.is_ok() {
-		body = format!("{}", user?.uuid);
-	}
-	else {
-		body = "Not fond :(".to_owned();
-	}
-
-	let restype: HeaderValue = "text/html".parse().unwrap();
-	Ok((build_html(&body), StatusCode::OK, restype))
-}
-
-fn uri_404() -> (String, StatusCode, HeaderValue) {
-	let restype: HeaderValue = "text/html".parse().unwrap();
-	(build_html(NF_HTML), StatusCode::NOT_FOUND, restype)
-}
diff --git a/src/url.rs b/src/url.rs
index e649fd1..2ed1ff9 100644
--- a/src/url.rs
+++ b/src/url.rs
@@ -1,2 +1,8 @@
 pub mod api;
 pub mod login;
+pub mod index;
+pub mod authorize;
+pub mod nf;
+pub mod register;
+pub mod user;
+pub mod recover;
diff --git a/src/url/authorize.rs b/src/url/authorize.rs
new file mode 100644
index 0000000..02ff5b0
--- /dev/null
+++ b/src/url/authorize.rs
@@ -0,0 +1,19 @@
+pub async fn authorize(req: Request<Incoming>, pool: DBPool, token: String) -> Result<(String, StatusCode, HeaderValue)> {
+	// TODO: Forward for versions.
+	if *req.method() == Method::POST {
+		let r = double_split(req.uri().query().or(Some("")).unwrap().to_owned(), "&", "=");
+
+		let session = r.get("session");
+		let session = match session.is_none() {
+			false => session.unwrap().to_owned(),
+			_ => "".to_owned()
+		};
+
+		if session != "" && session.len() <= 128 {
+			authorize_user(pool.clone(), token, session).await;
+		}
+	}
+
+	let restype: HeaderValue = "text/html".parse().unwrap();
+	Ok((build_html(AUTHORIZE_HTML), StatusCode::OK, restype))
+}
diff --git a/src/url/index.rs b/src/url/index.rs
new file mode 100644
index 0000000..f496c97
--- /dev/null
+++ b/src/url/index.rs
@@ -0,0 +1,4 @@
+pub fn index() -> (String, StatusCode, HeaderValue) {
+	let restype: HeaderValue = "text/html".parse().unwrap();
+	(build_html(INDEX_HTML), StatusCode::OK, restype)
+}
diff --git a/src/url/login.rs b/src/url/login.rs
index 1d214af..a8e827b 100644
--- a/src/url/login.rs
+++ b/src/url/login.rs
@@ -92,7 +92,7 @@ type DBPool = Arc<Pool<ConnectionMgrTcp>>;
 type FullBytes = Result<Response<Full<Bytes>>>;
 
 
-pub async fn uri_login(req: Request<Incoming>, pool: DBPool, headers: &mut HeaderMap) -> Result<(String, StatusCode, HeaderValue)> {
+pub async fn login(req: Request<Incoming>, pool: DBPool, headers: &mut HeaderMap) -> Result<(String, StatusCode, HeaderValue)> {
 	let mut body = build_html(LOGIN_HTML);
 	let mut status = StatusCode::OK;
 	let restype: HeaderValue = "text/html".parse().unwrap();
diff --git a/src/url/nf.rs b/src/url/nf.rs
new file mode 100644
index 0000000..f76d923
--- /dev/null
+++ b/src/url/nf.rs
@@ -0,0 +1,4 @@
+pub fn nf() -> (String, StatusCode, HeaderValue) {
+	let restype: HeaderValue = "text/html".parse().unwrap();
+	(build_html(NF_HTML), StatusCode::NOT_FOUND, restype)
+}
diff --git a/src/url/recover.rs b/src/url/recover.rs
new file mode 100644
index 0000000..46a2be4
--- /dev/null
+++ b/src/url/recover.rs
@@ -0,0 +1,4 @@
+pub fn recover() -> (String, StatusCode, HeaderValue) {
+	let restype: HeaderValue = "text/html".parse().unwrap();
+	(build_html(RECOVER_HTML), StatusCode::OK, restype)
+}
diff --git a/src/url/register.rs b/src/url/register.rs
new file mode 100644
index 0000000..af144b2
--- /dev/null
+++ b/src/url/register.rs
@@ -0,0 +1,29 @@
+pub async fn register(req: Request<Incoming>, pool: DBPool, headers: &mut HeaderMap) -> Result<(String, StatusCode, HeaderValue)> {
+	let mut body = "".to_owned();
+	let mut status = StatusCode::OK;
+	let restype: HeaderValue = "text/html".parse().unwrap();
+
+	if *req.method() == Method::POST {
+		let request = get_body_from_request(req).await?;
+		let request = String::from_utf8(request).unwrap();
+		let request = double_split(request, "&", "=");
+
+		match create_user(pool.clone(), request).await? {
+			true => {
+				println!("Created");
+				set_location(headers, "/login");
+			},
+			_ => {
+				println!("Failed");
+				set_location(headers, "/register");
+			}
+		}
+
+		status = StatusCode::FOUND;
+	}
+	else {
+		body = build_html(REG_HTML);
+	}
+
+	Ok((body, status, restype))
+}
diff --git a/src/url/user.rs b/src/url/user.rs
new file mode 100644
index 0000000..6b20207
--- /dev/null
+++ b/src/url/user.rs
@@ -0,0 +1,16 @@
+pub async fn user(req: Request<Incoming>, pool: DBPool) -> Res<(String, StatusCode, HeaderValue), SkyError> {
+	let uri: &str = req.uri().path().as_ref();
+	let login = &uri[2..uri.len()];
+	let body: String;
+
+	let user = get_user(pool, login.to_string()).await;
+	if user.is_ok() {
+		body = format!("{}", user?.uuid);
+	}
+	else {
+		body = "Not fond :(".to_owned();
+	}
+
+	let restype: HeaderValue = "text/html".parse().unwrap();
+	Ok((build_html(&body), StatusCode::OK, restype))
+}