summaryrefslogtreecommitdiff
path: root/src/api/admin.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/api/admin.rs')
-rw-r--r--src/api/admin.rs83
1 files changed, 83 insertions, 0 deletions
diff --git a/src/api/admin.rs b/src/api/admin.rs
new file mode 100644
index 0000000..e654628
--- /dev/null
+++ b/src/api/admin.rs
@@ -0,0 +1,83 @@
+use std::env;
+
+use axum::{response::Response, Router, routing::post};
+use serde::Deserialize;
+use tower_cookies::{Cookies, Cookie};
+
+use crate::{types::{extract::{Check, CheckResult, Json, AdminUser, Log}, http::ResponseCode}, admin, database};
+
+#[derive(Deserialize)]
+struct AdminAuthRequest {
+ secret: String,
+}
+
+impl Check for AdminAuthRequest {
+ fn check(&self) -> CheckResult {
+ Ok(())
+ }
+}
+
+async fn auth(cookies: Cookies, Json(body) : Json<AdminAuthRequest>) -> Response {
+
+ let check = env::var("SECRET").unwrap_or("admin".to_string());
+ if check != body.secret {
+ return ResponseCode::BadRequest.text("Invalid admin secret")
+ }
+
+ let mut cookie = Cookie::new("admin", admin::regen_secret().await);
+ cookie.set_secure(false);
+ cookie.set_http_only(false);
+ cookie.set_path("/");
+
+ cookies.add(cookie);
+
+ ResponseCode::Success.text("Successfully logged in")
+}
+
+#[derive(Deserialize)]
+struct QueryRequest {
+ query: String,
+}
+
+impl Check for QueryRequest {
+ fn check(&self) -> CheckResult {
+ Ok(())
+ }
+}
+
+async fn query(_: AdminUser, Json(body) : Json<QueryRequest>) -> Response {
+ match database::query(body.query) {
+ Ok(changes) => ResponseCode::Success.text(&format!("Query executed successfully. {} lines changed.", changes)),
+ Err(err) => ResponseCode::InternalServerError.text(&format!("{}", err))
+ }
+}
+
+async fn posts(_: AdminUser, _: Log) -> Response {
+ admin::generate_posts()
+}
+
+async fn users(_: AdminUser, _: Log) -> Response {
+ admin::generate_users()
+}
+
+async fn sessions(_: AdminUser, _: Log) -> Response {
+ admin::generate_sessions()
+}
+
+async fn check(check: Option<AdminUser>, _: Log) -> Response {
+ if check.is_none() {
+ ResponseCode::Success.text("false")
+ } else {
+ ResponseCode::Success.text("true")
+ }
+}
+
+pub fn router() -> Router {
+ Router::new()
+ .route("/auth", post(auth))
+ .route("/query", post(query))
+ .route("/posts", post(posts))
+ .route("/users", post(users))
+ .route("/sessions", post(sessions))
+ .route("/check", post(check))
+}