summaryrefslogtreecommitdiff
path: root/src/api/admin.rs
blob: a23d20f21552cfcfdf176e944530a1e9b2a77707 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::env;

use axum::{response::Response, routing::post, Router};
use serde::Deserialize;
use tower_cookies::{Cookie, Cookies};

use crate::{
    database,
    public::admin,
    types::{
        extract::{AdminUser, Check, CheckResult, Json},
        http::ResponseCode,
    },
};

#[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_else(|_| "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(true);
    cookie.set_http_only(true);
    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. {changes} lines changed."
        )),
        Err(err) => ResponseCode::InternalServerError.text(&format!("{err}")),
    }
}

async fn posts(_: AdminUser) -> Response {
    admin::generate_posts()
}

async fn users(_: AdminUser) -> Response {
    admin::generate_users()
}

async fn sessions(_: AdminUser) -> Response {
    admin::generate_sessions()
}

async fn check(check: Option<AdminUser>) -> 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))
}