create_user works

This commit is contained in:
Martin Brodbeck 2025-01-07 14:55:56 +01:00
parent 5b258ae040
commit cdf909159d
3 changed files with 1122 additions and 94 deletions

1141
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
axum = "0.8.1"
redis = { version = "0.23.3", features = ["tokio-comp"] }
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.107"
sqlx = { version = "0.8.3", features = ["runtime-tokio", "postgres"] }
tokio = { version = "1.32.0", features = ["macros", "rt-multi-thread"] }

View file

@ -1,12 +1,18 @@
use axum::{
extract::Path, http::HeaderMap, http::StatusCode, routing::get, routing::post, routing::put,
extract::{Path, State},
http::HeaderMap,
http::StatusCode,
routing::get,
routing::post,
routing::put,
Json, Router,
};
use redis::Commands;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sqlx::{postgres::PgPoolOptions, PgPool};
use std::time::{SystemTime, UNIX_EPOCH};
use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Deserialize)]
pub struct User {
@ -35,6 +41,18 @@ pub struct GetProgress {
#[tokio::main]
async fn main() {
let pg_url: String = env::var("POSTGRES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap();
let db_pool = PgPoolOptions::new()
.max_connections(64)
.acquire_timeout(Duration::from_secs(5))
.connect(&pg_url)
.await
.expect("Can't connect to database.");
// build our application with a single route
let app = Router::new()
.route("/", get(root))
@ -42,10 +60,13 @@ async fn main() {
.route("/users/auth", get(auth_user))
.route("/syncs/progress", put(update_progress))
.route("/syncs/progress/{document}", get(get_progress))
.route("/healthcheck", get(healthcheck));
.route("/healthcheck", get(healthcheck))
.with_state(db_pool);
// run it with hyper on localhost:3003
let listener = tokio::net::TcpListener::bind("127.0.0.1:3003").await.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3003")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
@ -53,19 +74,34 @@ async fn root() -> &'static str {
"KOreader sync server"
}
async fn create_user(Json(payload): Json<User>) -> (StatusCode, Json<Value>) {
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
async fn create_user(
State(db_pool): State<PgPool>,
Json(payload): Json<User>,
) -> (StatusCode, Json<Value>) {
//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 user_key = format!("user:{username}:key");
let does_exist: bool = con.exists(&user_key).unwrap();
let row: (i64,) = sqlx::query_as("SELECT COUNT(id) FROM users WHERE username = $1")
.bind(&username)
.fetch_one(&db_pool)
.await
.unwrap();
let does_exist: bool = if row.0 == 1 { true } else { false };
if does_exist == false {
let _: () = con.set(&user_key, password).unwrap();
//let _: () = con.set(&user_key, password).unwrap();
sqlx::query("INSERT INTO users (username, password) VALUES ($1, $2)")
.bind(&username)
.bind(&password)
.execute(&db_pool)
.await
.unwrap();
} else {
return (
StatusCode::PAYMENT_REQUIRED,
@ -77,7 +113,7 @@ async fn create_user(Json(payload): Json<User>) -> (StatusCode, Json<Value>) {
}
fn authorize(username: &str, password: &str) -> bool {
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
/*let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
if username.is_empty() || password.is_empty() {
@ -90,7 +126,7 @@ fn authorize(username: &str, password: &str) -> bool {
if password != redis_pw {
return false;
}
} */
true
}
@ -117,7 +153,7 @@ async fn update_progress(headers: HeaderMap, Json(payload): Json<UpdateProgress>
return StatusCode::UNAUTHORIZED;
}
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
/*let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
let timestamp = SystemTime::now()
@ -138,7 +174,7 @@ async fn update_progress(headers: HeaderMap, Json(payload): Json<UpdateProgress>
("timestamp", &timestamp.to_string()),
],
)
.unwrap();
.unwrap(); */
StatusCode::OK
}
@ -154,7 +190,7 @@ async fn get_progress(
return (StatusCode::UNAUTHORIZED, Json(json!("")));
}
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
/* let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
let doc_key = format!("user:{username}:document:{document}");
@ -177,9 +213,10 @@ async fn get_progress(
device_id: values[3].clone(),
timestamp: values[4].parse().unwrap(),
document,
};
}; */
(StatusCode::OK, Json(json!(res)))
//(StatusCode::OK, Json(json!(res)))
(StatusCode::OK, Json(json!("")))
}
async fn healthcheck() -> (StatusCode, Json<Value>) {