mirror of
https://forge.pointfixe.fr/hubert/gitust.git
synced 2026-02-04 19:07:29 +01:00
base
This commit is contained in:
156
src/main.rs
Normal file
156
src/main.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
mod git;
|
||||
mod ite;
|
||||
|
||||
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Error, HttpRequest};
|
||||
use askama_actix::Template;
|
||||
use actix_session::{Session, CookieSession};
|
||||
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
|
||||
use actix_web::http::header::Header;
|
||||
use actix_web_httpauth::middleware::HttpAuthentication;
|
||||
use actix_web::dev::ServiceRequest;
|
||||
use actix_web_httpauth::extractors::basic::{BasicAuth, Config};
|
||||
use actix_web_httpauth::extractors::AuthenticationError;
|
||||
use crate::git::{GitBrowseEntry, GitRepo, GitCommit, GitBrowseDir};
|
||||
use actix_web::middleware::Logger;
|
||||
use env_logger::Env;
|
||||
use crate::ite::SuperIterator;
|
||||
use std::ops::Add;
|
||||
use std::path::{PathBuf, Path};
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "hello.html")]
|
||||
struct HelloTemplate<'a> {
|
||||
name: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "git.html")]
|
||||
struct GitMainTemplate<TS, ROOT>
|
||||
where for <'a> &'a TS : IntoIterator<Item = &'a GitBrowseEntry>,
|
||||
for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>,
|
||||
{
|
||||
user: String,
|
||||
repo : String,
|
||||
browse : TS,
|
||||
root : ROOT,
|
||||
}
|
||||
|
||||
#[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("/git/{user}/{repo}/{commit}/{path:.*}")]
|
||||
async fn git_main(web::Path((user, reponame, commitname, rootname)): web::Path<(String, String, String, String)>) -> impl Responder {
|
||||
let repo = GitRepo::new();
|
||||
let path : Vec<(String, String)> = rootname.split("/").map_accum("/git/".to_string() + &user + "/" + &reponame + "/" + &commitname, |str_ref, b| {
|
||||
let href = b + "/" + str_ref;
|
||||
((str_ref.to_string(), href.clone()), href)
|
||||
}).collect();
|
||||
let commit = GitCommit::new(commitname);
|
||||
let root = GitBrowseDir::new(rootname);
|
||||
let browse = repo.browse(&commit, &root).await;
|
||||
GitMainTemplate { user, repo : reponame, browse : browse, root : path}
|
||||
}
|
||||
|
||||
#[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(web::Path((id, name)): web::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("karl") && user_password.eq(&Option::Some("password")) {
|
||||
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);
|
||||
App::new()
|
||||
.wrap(Logger::default())
|
||||
// .wrap(Logger::new("%a %{User-Agent}i"))
|
||||
.wrap(CookieSession::signed(&[0; 32]).secure(false))
|
||||
.service(hello)
|
||||
.service(echo)
|
||||
.service(hello_test)
|
||||
.service(index)
|
||||
.service(askama)
|
||||
.service(git_main)
|
||||
.service(hello_session)
|
||||
// .service(
|
||||
// web::scope("/auth")
|
||||
// .wrap(auth)
|
||||
// .route("/", web::get().to(hello_auth))
|
||||
// )
|
||||
.service(
|
||||
web::resource("/auth")
|
||||
.wrap(auth)
|
||||
.route(web::get().to(hello_auth))
|
||||
)
|
||||
.route("/hey", web::get().to(manual_hello))
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
Reference in New Issue
Block a user