gitust/src/main.rs

205 lines
6.1 KiB
Rust

use std::collections::HashMap;
use std::io;
use std::io::{BufRead, ErrorKind, Read, Write};
use std::ops::Add;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use actix_files::Files;
use actix_session::{CookieSession, Session};
use actix_web::{App, Error, get, HttpMessage, HttpRequest, HttpResponse, HttpServer, post, Responder};
use actix_web::client::PayloadError;
use actix_web::dev::ServiceRequest;
use actix_web::http::{header, StatusCode};
use actix_web::http::header::Header;
use actix_web::http::header::IntoHeaderValue;
use actix_web::middleware::Logger;
use actix_web::web as webx;
use actix_web::web::{Buf, Bytes};
use actix_web_httpauth::extractors::AuthenticationError;
use actix_web_httpauth::extractors::basic::{BasicAuth, Config};
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
use actix_web_httpauth::middleware::HttpAuthentication;
use askama_actix::Template;
use env_logger::Env;
use futures::{future, pin_mut, Stream, stream, StreamExt, TryFutureExt, TryStreamExt};
use git2::ObjectType;
use serde::Deserialize;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdout, Command};
use gitutils::gitcommit::GitRef;
use gitutils::gitdir::GitDir;
use gitutils::gitfile::GitFile;
use gitutils::gitproto;
use gitutils::gitrepo::GitRepo;
use web::repo;
use webutils::auth;
use crate::git::GitBrowseEntry;
use crate::gitust::Gitust;
use crate::ite::SuperIterator;
use crate::reader::ToStream;
use crate::writer::Writer;
mod git;
mod ite;
mod reader;
mod writer;
mod gitust;
mod error;
mod web;
mod gitutils;
mod webutils;
#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate<'a> {
name: &'a str,
}
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Bonjour monde !")
}
#[get("/test")]
async fn hello_test() -> impl Responder {
HttpResponse::Ok().body("Coucou")
}
#[get("/askama")]
async fn askama() -> impl Responder {
let name : &str = "world";
HelloTemplate { name }
}
#[get("/session")]
async fn hello_session(session : Session) -> impl Responder {
// session.renew();
match session.set("VieuxVy", 1) {
Ok(_) => HttpResponse::Ok().body("Coucou\r\n"),
Err(e) => HttpResponse::BadGateway().body("fail\r\n"),
}
}
// #[get("/auth")]
async fn hello_auth(req : HttpRequest) -> impl Responder {
match Authorization::<Basic>::parse(&req){
Ok(auth) => HttpResponse::Ok().body(format!("Hello, {}!", auth.as_ref().user_id())),
Err(e) => HttpResponse::Unauthorized().body("forbidden")
}
}
#[get("/chunk")]
async fn chunk() -> HttpResponse {
let (tx, rx) = actix_utils::mpsc::channel::<Result<Bytes, Error>>();
actix_web::rt::spawn(async move {
if tx.send(Ok(Bytes::from_static(b"trying to echo"))).is_err() {
return;
};
loop {
tokio::time::delay_for(std::time::Duration::from_secs(1)).await;
println!("send message");
tx.send(Ok(Bytes::from_static(b"coucou")));
}
});
HttpResponse::Ok().streaming(rx)
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!\r\n")
}
#[get("/{id}/{name}/index.html")]
async fn index(webx::Path((id, name)): webx::Path<(u32, String)>) -> impl Responder {
format!("Hello {}! id:{}", name, id)
}
async fn basic_auth_validator(req: ServiceRequest, credentials: BasicAuth) -> Result<ServiceRequest, Error> {
let config = req
.app_data::<Config>()
.map(|data| data.clone())
.unwrap_or_else(Default::default);
match validate_credentials(credentials.user_id(), credentials.password().map(|s| s.trim())) {
Ok(res) => {
if res == true {
Ok(req)
} else {
Err(AuthenticationError::from(config).into())
}
}
Err(_) => Err(AuthenticationError::from(config).into()),
}
}
fn validate_credentials(user_id: &str, user_password: Option<&str>) -> Result<bool, std::io::Error>
{
if user_id.eq("hubert") && user_password.eq(&Option::Some("hubert")) {
return Ok(true);
}
return Err(std::io::Error::new(std::io::ErrorKind::Other, "Authentication failed!"));
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::from_env(Env::default().default_filter_or("info")).init();
HttpServer::new(|| {
let auth = HttpAuthentication::basic(basic_auth_validator);
let gitust = Gitust {
repo_root_path: "/home/hubert/gitust".to_string(),
session_key: "oWe0ait9bi2Ohyiod2eeXirao1Oochie".to_string(),
};
let session_key = (&gitust.session_key).as_bytes();
App::new()
.wrap(Logger::default())
// .wrap(Logger::new("%a %{User-Agent}i"))
.wrap(CookieSession::signed(session_key).secure(false))
.data(gitust)
.data(auth::TestValidator)
.service(hello)
.service(echo)
.service(hello_test)
.service(index)
.service(askama)
.service(repo::git_main)
.service(hello_session)
.service(chunk)
//.service(git_proto)
// .service(
// web::scope("/auth")
// .wrap(auth)
// .route("/", web::get().to(hello_auth))
// )
.service(
webx::resource("/auth")
.wrap(auth)
.route(webx::get().to(hello_auth))
)
.service(
webx::resource("/git/{user}/{repo}.git/{path:.*}")
.route(webx::route().to(gitproto::git_proto::<auth::TestValidator>))
)
.service(
Files::new("/static", "static")
.use_last_modified(true)
.use_etag(true)
// .show_files_listing()
)
.route("/hey", webx::get().to(manual_hello))
})
.bind("127.0.0.1:8080")?
.run()
.await
}