first implementation of /users/auth

This commit is contained in:
Martin Brodbeck 2023-09-26 11:09:00 +02:00
parent 9e3b82fbde
commit 0e96cb1bda

View file

@ -1,4 +1,6 @@
use axum::{http::StatusCode, routing::get, routing::post, routing::put, Json, Router};
use axum::{
http::HeaderMap, http::StatusCode, routing::get, routing::post, routing::put, Json, Router,
};
use serde_json::{json, Value};
@ -7,7 +9,7 @@ use serde::Deserialize;
use redis::Commands;
#[derive(Deserialize)]
pub struct CreateUser {
pub struct User {
username: String,
password: String,
}
@ -34,7 +36,7 @@ async fn root() -> &'static str {
"KOreader sync server"
}
async fn create_user(Json(payload): Json<CreateUser>) -> (StatusCode, String) {
async fn create_user(Json(payload): Json<User>) -> (StatusCode, String) {
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let mut con = client.get_connection().unwrap();
@ -57,7 +59,29 @@ async fn create_user(Json(payload): Json<CreateUser>) -> (StatusCode, String) {
(StatusCode::CREATED, format!("username = {username}"))
}
async fn auth_user() {}
async fn auth_user(headers: HeaderMap) -> (StatusCode, String) {
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("");
println!("AHA");
if username.is_empty() || password.is_empty() {
return (StatusCode::UNAUTHORIZED, "Unauthorized".to_owned());
}
let user_key = format!("user:{username}:key");
let redis_pw: String = con.get(&user_key).unwrap();
if password != redis_pw {
return (StatusCode::UNAUTHORIZED, "Unauthorized".to_owned());
}
(StatusCode::OK, "authorized = 'OK'".to_owned())
}
async fn update_progress() {}