From 3ce7eec8e0e5604d2500c3c8ae6954252a8e319f Mon Sep 17 00:00:00 2001
From: peterrabbit <pierre.jarriges@tutanota.com>
Date: Sun, 11 Sep 2022 20:34:10 +0200
Subject: [PATCH] wip pass auth token to auth service

---
 src/app/args.rs                  |  4 ++--
 src/main.rs                      | 13 +++++++++++
 src/middleware/authentication.rs | 37 ++++++++++----------------------
 src/static_files/static_files.rs |  3 ---
 4 files changed, 26 insertions(+), 31 deletions(-)

diff --git a/src/app/args.rs b/src/app/args.rs
index 8bd54ee..9f8a0d7 100644
--- a/src/app/args.rs
+++ b/src/app/args.rs
@@ -24,9 +24,9 @@ pub struct AppArgs {
     #[structopt(long = "certs_dir", default_value = "/etc/letsencrypt/live")]
     pub ssl_certs_dir: PathBuf,
 
-    #[structopt(short = "u", long = "username", default_value = "admin")]
+    #[structopt(long = "adm", default_value = "admin")]
     pub admin_id: String,
 
-    #[structopt(short = "p", long = "password", default_value = "password")]
+    #[structopt(long = "pwd", default_value = "password")]
     pub admin_pwd: String,
 }
diff --git a/src/main.rs b/src/main.rs
index b1c536e..3bf320a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,10 +9,16 @@ use actix_files::Files;
 use actix_web::{web, App, HttpServer};
 use actix_web_lab::middleware::RedirectHttps;
 use app::AppState;
+use middleware::AuthService;
 use static_files::StaticFilesManager;
 use tls_config::tls_config;
 use website::WebSiteBuilder;
 
+#[actix_web::get("/admin")]
+async fn test_unauthorized() -> impl actix_web::Responder {
+    actix_web::HttpResponse::Ok().finish()
+}
+
 #[actix_web::main]
 async fn main() -> std::io::Result<()> {
     let app_state = AppState::new();
@@ -45,6 +51,13 @@ async fn main() -> std::io::Result<()> {
             .app_data(web::Data::clone(&app_state))
             .app_data(web::Data::clone(&mut_website))
             .service(Files::new("/static/", &static_dir))
+            .service(
+                web::scope("/admin")
+                    .wrap(AuthService {
+                        token: String::from("abc"),
+                    })
+                    .service(test_unauthorized),
+            )
             .service(service::files::favicon)
             .service(service::page)
     })
diff --git a/src/middleware/authentication.rs b/src/middleware/authentication.rs
index 6fb4c4e..99e6fd1 100644
--- a/src/middleware/authentication.rs
+++ b/src/middleware/authentication.rs
@@ -7,13 +7,11 @@ use futures::prelude::future::LocalBoxFuture;
 use std::future::{ready, Ready};
 
 #[derive(Clone)]
-pub struct AuthData {
-    id: String,
-    password: String,
-    _token: Option<String>,
+pub struct AuthService {
+    pub token: String,
 }
 
-impl<S, B> Transform<S, ServiceRequest> for AuthData
+impl<S, B> Transform<S, ServiceRequest> for AuthService
 where
     S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
     B: MessageBody + 'static,
@@ -27,35 +25,21 @@ where
     fn new_transform(&self, service: S) -> Self::Future {
         ready(Ok(AuthenticatedMiddleware {
             service: std::rc::Rc::new(service),
-            auth_data: self.clone(),
+            auth: self.clone(),
         }))
     }
 }
 
 pub struct AuthenticatedMiddleware<S> {
     service: std::rc::Rc<S>,
-    auth_data: AuthData,
+    auth: AuthService,
 }
 
-#[derive(serde::Deserialize)]
-struct Credentials {
-    id: String,
-    password: String,
-}
-
-async fn authenticate(req: &mut ServiceRequest, auth_data: &AuthData) -> bool {
+async fn authenticate(req: &mut ServiceRequest, token: String) -> bool {
     let cookie = req.cookie("auth");
     match cookie {
-        Some(_) => true,
-        None => match req.extract::<actix_web::web::Form<Credentials>>().await {
-            Ok(credentials) => {
-                if credentials.id == auth_data.id && credentials.password == auth_data.password {
-                    return true;
-                }
-                return false;
-            }
-            Err(_) => false,
-        },
+        Some(cookie) => return cookie.value().to_string().eq(&token),
+        None => false,
     }
 }
 
@@ -72,10 +56,11 @@ where
 
     fn call(&self, req: ServiceRequest) -> Self::Future {
         let service = self.service.clone();
-        let auth_data = self.auth_data.clone();
+        let token = self.auth.token.to_owned();
+
         Box::pin(async move {
             let mut req = req;
-            if let false = authenticate(&mut req, &auth_data).await {
+            if let false = authenticate(&mut req, token).await {
                 return Ok(req.into_response(
                     actix_web::HttpResponse::Unauthorized()
                         .finish()
diff --git a/src/static_files/static_files.rs b/src/static_files/static_files.rs
index c4c3bf9..4e4f601 100644
--- a/src/static_files/static_files.rs
+++ b/src/static_files/static_files.rs
@@ -131,15 +131,12 @@ impl StaticFilesManager {
     }
 
     pub fn remove_path(&mut self, strpath: String) {
-        println!("REMOVE {}", strpath);
-        println!("current Index {:#?}", self.index);
         self.index = self
             .index
             .iter()
             .filter(|url| !strpath.eq(*url))
             .map(|s| s.to_owned())
             .collect();
-        println!("Updated Index {:#?}", self.index);
     }
 
     pub fn get_index(&self) -> Vec<String> {
-- 
GitLab