aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/api/mod.rs
blob: 84dd6a86c24afa7f2ee95716111c8761c409b1fc (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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/

use super::ui::{
    account::{login_logic, LoginForm},
    error::MyResult,
};
use crate::database::Database;
use reqwest::Client;
use rocket::{get, post, response::Redirect, serde::json::Json, State};
use serde_json::{json, Value};

#[get("/api")]
pub fn r_api_root() -> Redirect {
    Redirect::moved("https://codeberg.org/metamuffin/jellything/src/branch/master/api.md")
}

#[get("/api/version")]
pub fn r_api_version() -> &'static str {
    "2"
}

#[post("/api/account/login", data = "<data>")]
pub fn r_api_account_login(database: &State<Database>, data: Json<LoginForm>) -> MyResult<Value> {
    let token = login_logic(database, &data.username, &data.password)?;
    Ok(json!(token))
}
pub async fn c_api_account_login(
    host: &str,
    tls: bool,
    username: String,
    password: String,
    expire: u64,
) -> MyResult<String> {
    Ok(Client::builder()
        .build()?
        .post(format!(
            "{}://{host}/api/account/login",
            if tls { "https" } else { "http" }
        ))
        .body(serde_json::to_string(&LoginForm {
            expire,
            password,
            username,
        })?)
        .send()
        .await?
        .json()
        .await?)
}