kosyncrs/src/main.rs

91 lines
2.3 KiB
Rust
Raw Normal View History

2023-09-26 11:09:00 +02:00
use axum::{
http::HeaderMap, http::StatusCode, routing::get, routing::post, routing::put, Json, Router,
};
2023-09-25 15:54:07 +02:00
use serde_json::{json, Value};
2023-09-25 15:12:47 +02:00
2023-09-26 10:38:50 +02:00
use serde::Deserialize;
use redis::Commands;
#[derive(Deserialize)]
2023-09-26 11:09:00 +02:00
pub struct User {
2023-09-26 10:38:50 +02:00
username: String,
password: String,
}
2023-09-25 15:12:47 +02:00
#[tokio::main]
async fn main() {
// build our application with a single route
2023-09-25 15:54:07 +02:00
let app = Router::new()
.route("/", get(root))
.route("/users/create", post(create_user))
.route("/users/auth", get(auth_user))
.route("/syncs/progress", put(update_progress))
.route("/syncs/progress/:document", put(get_progress))
.route("/healthcheck", get(healthcheck));
2023-09-25 15:12:47 +02:00
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
2023-09-25 15:54:07 +02:00
async fn root() -> &'static str {
2023-09-25 16:13:14 +02:00
"KOreader sync server"
2023-09-25 15:54:07 +02:00
}
2023-09-26 12:48:53 +02:00
async fn create_user(Json(payload): Json<User>) -> (StatusCode, String) {
2023-09-26 10:38:50 +02:00
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
let username = payload.username;
let password = payload.password;
let user_key = format!("user:{username}:key");
let does_exist: bool = con.exists(&user_key).unwrap();
if does_exist == false {
let _: () = con.set(&user_key, password).unwrap();
} else {
2023-09-26 12:48:53 +02:00
return (
StatusCode::PAYMENT_REQUIRED,
"Username is already registered.".to_owned(),
);
2023-09-26 10:38:50 +02:00
}
2023-09-26 12:48:53 +02:00
(StatusCode::CREATED, format!("username = {username}"))
2023-09-26 10:38:50 +02:00
}
2023-09-25 15:54:07 +02:00
2023-09-26 12:40:52 +02:00
async fn auth_user(headers: HeaderMap) -> StatusCode {
2023-09-26 11:09:00 +02:00
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
let username = headers["x-auth-user"].to_str().unwrap_or("");
let password = headers["x-auth-key"].to_str().unwrap_or("");
if username.is_empty() || password.is_empty() {
2023-09-26 12:40:52 +02:00
return StatusCode::UNAUTHORIZED;
2023-09-26 11:09:00 +02:00
}
let user_key = format!("user:{username}:key");
let redis_pw: String = con.get(&user_key).unwrap();
if password != redis_pw {
2023-09-26 12:40:52 +02:00
return StatusCode::UNAUTHORIZED;
2023-09-26 11:09:00 +02:00
}
2023-09-26 12:40:52 +02:00
StatusCode::OK
2023-09-26 11:09:00 +02:00
}
2023-09-25 15:54:07 +02:00
async fn update_progress() {}
async fn get_progress() {}
2023-09-26 10:42:24 +02:00
async fn healthcheck() -> (StatusCode, String) {
(StatusCode::OK, "state = 'OK'".to_owned())
2023-09-25 15:54:07 +02:00
}