1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

//! Run 
//! ```not_rust
//! cargo run -p example-static-file-server
//! ```

// use axum_auth::AuthBasic;

#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(html_logo_url = "../images/docserver.svg")]
#[doc = include_str!("../README.md")]
// #![doc(html_no_source)]



// TODO tasks https://docs.rs/async-sqlx-session/latest/async_sqlx_session/struct.SqliteSessionStore.html

use rand_core::{SeedableRng,OsRng, RngCore};
use rand_chacha::ChaCha8Rng;

use axum::{
    extract::Host,
    handler::HandlerWithoutStateExt,
    routing::MethodRouter,
    http::{
        StatusCode,
        Uri,
        header::HeaderValue,
        Method,
    },
    BoxError,
    Extension,
    response::Redirect,
//    http::Request, handler::HandlerWithoutStateExt, http::StatusCode, routing::get, Router,    
    Router,
};
use tower::ServiceBuilder;
use axum_server::tls_rustls::RustlsConfig;
use std::{
    net::SocketAddr, 
    path::PathBuf,
    sync::{Arc, Mutex},
    path::Path, 
};
// use std::net::SocketAddr;
// use tower::ServiceExt;
use tower_http::{
    services::{ServeDir,ServeFile},
    trace::TraceLayer,
    cors::CorsLayer,
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use once_cell::sync::Lazy;
// use once_cell::sync::{Lazy,OnceCell};
// use async_session::{Session, SessionStore, MemoryStore};

use tera::Context;
use async_sqlx_session::SqliteSessionStore;
use sqlx::AnyPool;

mod tera_tpls;
mod defs;
mod login_password;
mod handlers;
mod tools;

use defs::{
    AppDBs,
    SessionStoreDB,
    UserStore,
    FileStore,
    Config,
    parse_args,
//    User,
};
use tera_tpls::init_tera;
use tower_cookies::CookieManagerLayer;
use handlers::{
    handle_404,
    rewrite_request_uri,
    admin_router_handlers,
    users_router_handlers,
    pages_router_handlers,
};
use crate::tools::get_socket_addr;

pub const USER_AGENT: &str = "user-agent";
pub const SESSION_COOKIE_NAME: &str = "doc_session";
pub const CFG_FILE_EXTENSION: &str  = ".toml";
pub const FILE_SCHEME: &str = "file:///"; 

pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
// static WEBSERVER: AtomicUsize = AtomicUsize::new(0);
pub const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
// const PKG_VERSION: Option&<&'static str> = option_env!("CARGO_PKG_VERSION");
// const PKG_DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
// const COOKIE_NAME: &str = "lc_authz";
// const COOKIE_SEP: &str = ":tk:";
const GIT_VERSION: &str = ""; //git_version::git_version!();
static GIT_VERSION_NAME: Lazy<String> = Lazy::new(|| {
    format!("v{} [build: {}]",PKG_VERSION,GIT_VERSION)
});
static PKG_FULLNAME: Lazy<String> = Lazy::new(|| {
    format!("{}: TII CL Rust",PKG_NAME)
});

pub const USERS_TABLENAME: &str = "users";
pub const USERS_FILESTORE: &str = "users";
pub const DEFAULT_ROLES: &str = "user";


#[derive(Clone, Copy)]
struct Ports {
    http: u16,
    https: u16,
}

pub fn route(path: &str, method_router: MethodRouter) -> Router {
    Router::new().route(path, method_router)
}

#[tokio::main]
async fn main() {
    let config_path = parse_args();
    if config_path.is_empty() {
        eprintln!("No config-file found");
        std::process::exit(2)
    }
    //	pretty_env_logger::init();
    let config = {
        let mut server_cfg: Config = Config::load_from_file(&config_path, "server-config").unwrap_or_else(|e|{
            eprintln!("Settings error: {}",e);
            std::process::exit(2)
        });
        server_cfg.load_items();
        //config.fix_root_path::<ServerConfig>(String::new());
        server_cfg
    };
    if config.verbose > 1 { dbg!("{:?}",&config); }
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "example_static_file_server=debug,tower_http=debug".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    // you can convert handler function to service

    // let store = FileStore {
    //     sess_path: "store".to_owned(),
    //     ses_file: "data".to_owned(),
    //     // sess_path: sessions_config.session_store_uri.replace(FILE_SCHEME,"").to_owned(),
    //     // ses_file: sessions_config.session_store_file.to_owned(),
    // };
    // let session_store = SessionStoreDB::connect_file_store(store);
    // let session_store = SessionStoreDB::connect_memory_store();
    let session_store = if config.session_store_uri.starts_with(FILE_SCHEME) {
        let store = FileStore {
            sess_path: config.session_store_uri.replace(FILE_SCHEME,"").to_owned(),
            ses_file: config.session_store_file.to_owned(),
        };
        if let Err(e) = store.check_paths() {
            eprintln!("Error creation File Store: {}",e);
            std::process::exit(2)
        }
        SessionStoreDB::connect_file_store(store)
    } else if config.session_store_uri.starts_with("sqlite:") {
        let store = SqliteSessionStore::new(&config.session_store_uri).await.unwrap_or_else(|e|{
            eprintln!("Error session database {}: {}",
                config.session_store_uri,e
            );
            std::process::exit(2)
        });
        let _ = store.migrate().await;
        let _ = store.cleanup().await;
        SessionStoreDB::connect_sqlite_store(store)
    } else if config.session_store_uri.starts_with("memory") {
        SessionStoreDB::connect_memory_store()
    } else {
        SessionStoreDB::None
    }; 
    let user_store = if config.users_store_uri.starts_with(FILE_SCHEME) {
        let users_store_uri = config.users_store_uri.replace(FILE_SCHEME,"").to_owned();
        if ! Path::new(&users_store_uri).exists() {
            if let Err(e) = std::fs::File::create(Path::new(&users_store_uri)) {
                eprintln!("Error creation Users store {}: {}",
                    &users_store_uri,e);
                std::process::exit(2)
            }
        }
        UserStore::File(users_store_uri)
    // } else if config.users_store_uri.starts_with("sqlite:") {
    } else if config.users_store_uri.contains("sql") {
        //let m = Migrator::new(Path::new("./migrations")).await?;
        //}
        let pool = AnyPool::connect(&config.users_store_uri).await.unwrap_or_else(|e|{
            eprintln!("Error pool database {}: {}",
                config.users_store_uri,e
            );
            std::process::exit(2)
        });
        // let pool = SqlitePool::connect(&config.users_store_uri).await.unwrap_or_else(|e|{
        //     eprintln!("Error pool database {}: {}",
        //         config.users_store_uri,e
        //     );
        //     std::process::exit(2)
        // });
        UserStore::Sql(pool)
    } else {
        eprintln!("User store {}: Not defined",&config.users_store_uri);
        std::process::exit(2)
    };
    #[cfg(feature = "casbin")]
    let enforcer = if !config.authz_model_path.is_empty() && ! config.authz_policy_path.is_empty() {
        AppDBs::create_enforcer(
        Box::leak(config.authz_model_path.to_owned().into_boxed_str()),
        Box::leak(config.authz_policy_path.to_owned().into_boxed_str())
        ).await
    } else {
        eprintln!("Error auth enforcer {} + {}",
            config.authz_model_path, config.authz_policy_path
        );
        std::process::exit(2);
    };

    let ports = Ports {
        http: 7878,
        https: 8800,
    };
    // optional: spawn a second server to redirect http requests to this server
    if config.protocol.contains("http") {
        tokio::spawn(redirect_http_to_https(ports));
    }

    let mut origins: Vec<HeaderValue> = Vec::new();
    for itm in config.allow_origin.to_owned() {
        match HeaderValue::from_str(itm.as_str()) {
            Ok(val) => origins.push(val),
            Err(e) =>  println!("error {} with {} header for allow_origin",e,itm),
        }
    }	

    let mut context = Context::new();
    context.insert("server_name","DOC Server");
    context.insert("pkg_name",&PKG_NAME);
    context.insert("pkg_version",&PKG_VERSION);
    context.insert("git_version",&GIT_VERSION);
    context.insert("git_version_name",GIT_VERSION_NAME.as_str());
    context.insert("pkg_fullname",PKG_FULLNAME.as_str());

    // let app = Router::new().route("/", get(handler));
    #[cfg(feature = "authstore")]
    let app_dbs = Arc::new(
        AppDBs::new(&config, session_store, user_store,
            init_tera(&config.templates_path), context
        )
    );
    #[cfg(feature = "casbin")]
    let app_dbs = Arc::new(
        AppDBs::new(&config, session_store, user_store, enforcer,
            init_tera(&config.templates_path), context
        )
    );
    let middleware = 
        axum::middleware::from_fn_with_state(app_dbs.clone(),rewrite_request_uri);
    // apply the layer around the whole `Router`
    // this way the middleware will run before `Router` receives the request

    let mut web_router = Router::new();

    // Parse serv_paths to add static paths as service 
    for item in &config.serv_paths {
        // Try to check src_path ...
        let src_path: String;
        if Path::new(&item.src_path).exists() {
            src_path = format!("{}",item.src_path); 
        } else {
            src_path = if item.src_path.starts_with("/") {
                format!("{}",item.src_path)
            } else {
                format!("{}/{}",&config.root_path,item.src_path)
            };
            if ! Path::new(&src_path).exists() {
                eprintln!("File path {}: not found", &src_path);
                continue;
            } 
        }    
        // Add ServeDir with not_found page ...
        if item.not_found.is_empty() {
            web_router = web_router.nest_service(
                &item.url_path,
                ServeDir::new(&src_path).not_found_service(handle_404.into_service())
            );
            println!("Added path {} => {}", &src_path,&item.url_path);
        } else {
            web_router = web_router.nest_service(
                &item.url_path,
                ServeDir::new(&src_path).not_found_service(ServeFile::new(&item.not_found))
            );
            println!("Added path {} => {} ({})", &src_path,&item.url_path,&item.not_found);
        }
    }
    web_router = web_router
        .merge(users_router_handlers())
        .merge(admin_router_handlers())
        .merge(pages_router_handlers())
        .layer(ServiceBuilder::new().layer(middleware))
        .layer(CookieManagerLayer::new())
        .layer(Extension(app_dbs))
        .fallback_service(handle_404.into_service())
        ;

    if config.use_random {
        let mut key = [0u8; 16];
        let mut os_rng = OsRng{};
        os_rng.fill_bytes(&mut key);
        let random = ChaCha8Rng::seed_from_u64(OsRng.next_u64());
        web_router = web_router
            .layer(Extension(Arc::new(Mutex::new(random))))
    }
   

    // if !config.html_path.is_empty() && !config.html_url.is_empty() {
    //     MAIN_URL.set(config.server.html_url.to_owned()).unwrap_or_default();
    //     println!("SpaRoutert local path {} to {}",&config.server.html_path,&config.server.html_url);
    //     web_router = web_router.merge(
    //     )
    //     .fallback(fallback);
    // }

    if config.verbose > 2 { dbg!("{:?}",&origins); }
    if config.allow_origin.len() > 0 {
         web_router = web_router.layer(CorsLayer::new()
            .allow_origin(origins)
            .allow_methods(vec![Method::GET, Method::POST])
            .allow_headers(tower_http::cors::Any)
        );
    }
    let addr = get_socket_addr(&config.bind,config.port);
    tracing::debug!("listening on {}", addr);
    println!("listening on {}", addr);
    if config.protocol.as_str() == "http" {
    // let app_with_middleware = middleware.layer(app);
    // run https server
        //let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
        //tracing::debug!("listening on {}", addr);
        let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
        axum::serve(listener, web_router.layer(TraceLayer::new_for_http()))
          .await
          .unwrap();
    } else {
        // configure certificate and private key used by https
        // let tls_config = RustlsConfig::from_pem_file(
        //     PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        //         .join("self_signed_certs")
        //         .join("cert.pem"),
        //     PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        //         .join("self_signed_certs")
        //         .join("key.pem"),
        // )
        let tls_config = RustlsConfig::from_pem_file(
            PathBuf::from(&config.cert_file),
            PathBuf::from(&config.key_file)
        )
        .await
        .unwrap_or_else(|e|{
            eprintln!("Error TLS config: {}",e);
            std::process::exit(2)
        });
        //let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));
        //tracing::debug!("listening on {}", addr);
        //let app_with_middleware = middleware.layer(app);
        // apply the layer around the whole `Router`middleware.layer(app);
        axum_server::bind_rustls(addr, tls_config)
          .serve(web_router.into_make_service())
          .await
          .unwrap();
    }
/*
    // let port = 3002;

    // tokio::join!(
    //     serve(using_serve_dir(), 3001),
    //     serve(using_serve_dir_with_assets_fallback(), 3002),
    //     serve(using_serve_dir_only_from_root_via_fallback(), 3003),
    //     serve(using_serve_dir_with_handler_as_service(), 3004),
    //     serve(two_serve_dirs(), 3005),
    //     serve(calling_serve_dir_from_a_handler(), 3006),
    // );

    //let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let addr = SocketAddr::from(([192,168,1,4], port));
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    tracing::debug!("listening on {}", listener.local_addr().unwrap());

        // let _ = axum::Server::bind(&addr)
        //     .serve(
        //         // router.layer(TraceLayer::new_for_http())
        //         //router.into_make_service_with_connect_info::<SocketAddr>()
        //         router.into_make_service()
        //     )
        //     .await
        //     .expect("server failed");
 
    // axum_server::bind(addr)
    //     .serve(router.into_make_service())
    //     .await
    //     .unwrap();
     axum::serve(listener, router.layer(TraceLayer::new_for_http()))
         .await
        .unwrap();
    // let _ = axum::Server::bind(&addr)
    //     .serve(
    //             app.layer(TraceLayer::new_for_http()).into_make_service()
    //            //    web_router.into_make_service_with_connect_info::<SocketAddr>()
    //             // web_router.into_make_service()
    //     )
    //     .await
    //     .unwrap();
*/
}

async fn redirect_http_to_https(ports: Ports) {
    fn make_https(host: String, uri: Uri, ports: Ports) -> Result<Uri, BoxError> {
        let mut parts = uri.into_parts();

        parts.scheme = Some(axum::http::uri::Scheme::HTTPS);

        if parts.path_and_query.is_none() {
            parts.path_and_query = Some("/".parse().unwrap());
        }

        let https_host = host.replace(&ports.http.to_string(), &ports.https.to_string());
        parts.authority = Some(https_host.parse()?);

        Ok(Uri::from_parts(parts)?)
    }

    let redirect = move |Host(host): Host, uri: Uri| async move {
        match make_https(host, uri, ports) {
            Ok(uri) => Ok(Redirect::permanent(&uri.to_string())),
            Err(error) => {
                tracing::warn!(%error, "failed to convert URI to HTTPS");
                Err(StatusCode::BAD_REQUEST)
            }
        }
    };

    let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    tracing::debug!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, redirect.into_make_service())
        .await
        .unwrap();
}

/*
fn using_serve_dir() -> Router {
    // serve the file in the "assets" directory under `/assets`
    Router::new().nest_service("/assets", ServeDir::new("assets"))
}

fn using_serve_dir_with_assets_fallback() -> Router {
    // `ServeDir` allows setting a fallback if an asset is not found
    // so with this `GET /assets/doesnt-exist.jpg` will return `index.html`
    // rather than a 404
    let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html"));

    Router::new()
        .route("/foo", get(|| async { "Hi from /foo" }))
        .nest_service("/assets", serve_dir.clone())
        .fallback_service(serve_dir)
}

fn using_serve_dir_only_from_root_via_fallback() -> Router {
    // you can also serve the assets directly from the root (not nested under `/assets`)
    // by only setting a `ServeDir` as the fallback
    let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html"));

    Router::new()
        .route("/foo", get(|| async { "Hi from /foo" }))
        .fallback_service(serve_dir)
}

fn using_serve_dir_with_handler_as_service() -> Router {
    async fn handle_404() -> (StatusCode, &'static str) {
        (StatusCode::NOT_FOUND, "Not found")
    }

    // you can convert handler function to service
    let service = handle_404.into_service();

    let serve_dir = ServeDir::new("assets").not_found_service(service);

    Router::new()
        .route("/foo", get(|| async { "Hi from /foo" }))
        .fallback_service(serve_dir)
}

fn two_serve_dirs() -> Router {
    // you can also have two `ServeDir`s nested at different paths
    let serve_dir_from_assets = ServeDir::new("assets");
    let serve_dir_from_dist = ServeDir::new("dist");

    Router::new()
        .nest_service("/assets", serve_dir_from_assets)
        .nest_service("/dist", serve_dir_from_dist)
}

#[allow(clippy::let_and_return)]
fn calling_serve_dir_from_a_handler() -> Router {
    // via `tower::Service::call`, or more conveniently `tower::ServiceExt::oneshot` you can
    // call `ServeDir` yourself from a handler
    Router::new().nest_service(
        "/foo",
        get(|request: Request<_>| async {
            let service = ServeDir::new("assets");
            let result = service.oneshot(request).await;
            result
        }),
    )
}

async fn serve(app: Router, port: u16) {
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    tracing::debug!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app.layer(TraceLayer::new_for_http()))
        .await
        .unwrap();
    // let _ = axum::Server::bind(&addr)
    //     .serve(
    //             app.layer(TraceLayer::new_for_http()).into_make_service()
    //            //    web_router.into_make_service_with_connect_info::<SocketAddr>()
    //             // web_router.into_make_service()
    //     )
    //     .await
    //     .unwrap();
}
*/