From 0e96cb1bda49aa33ea517a037cae024b4f3ca033 Mon Sep 17 00:00:00 2001 From: Martin Brodbeck Date: Tue, 26 Sep 2023 11:09:00 +0200 Subject: [PATCH] first implementation of /users/auth --- src/main.rs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index d6416d0..c56d98b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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) -> (StatusCode, String) { +async fn create_user(Json(payload): Json) -> (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) -> (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() {}