mirror of
https://forge.pointfixe.fr/hubert/gitust.git
synced 2026-02-04 12:17:29 +01:00
Compare commits
26 Commits
a562c4616c
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 6beae6629f | |||
|
|
ba19d67f66 | ||
|
|
f9bc5b2e39 | ||
|
|
dbba11a416 | ||
|
|
edf6f9f81a | ||
|
|
5f6f7b7efe | ||
|
|
1f4d08aff1 | ||
|
|
f71e8ff1b3 | ||
|
|
4134982739 | ||
|
|
1e7c773c19 | ||
|
|
9832f30360 | ||
|
|
22836e1f3a | ||
|
|
90ea298a61 | ||
|
|
e3008262fc | ||
|
|
abc1f367bb | ||
| 6d87adb2e6 | |||
| aa131d009f | |||
|
|
9af4fa56e1 | ||
|
|
90bc6d6d4f | ||
|
|
381347e66a | ||
| 234e2ccaa3 | |||
|
|
2bc387920c | ||
|
|
07f11b238e | ||
|
|
0875a78cf8 | ||
| 510bbe7381 | |||
| 1950a5312e |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,2 +1,3 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
Cargo.lock
|
||||
/.idea/
|
||||
|
||||
22
src/error.rs
22
src/error.rs
@@ -1,17 +1,31 @@
|
||||
use actix_web::dev::HttpResponseBuilder;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web_httpauth::extractors::{basic, AuthenticationError};
|
||||
|
||||
pub struct Error(String);
|
||||
pub enum Error {
|
||||
BadGateway(String),
|
||||
Unauthorized(String),
|
||||
}
|
||||
|
||||
impl Error {
|
||||
}
|
||||
|
||||
impl From<git2::Error> for Error {
|
||||
fn from(giterr: git2::Error) -> Self {
|
||||
// panic!()
|
||||
Error(format!("{}", giterr))
|
||||
Error::BadGateway(format!("{}", giterr))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(ioerr: std::io::Error) -> Self {
|
||||
Error::BadGateway(format!("{}", ioerr))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for actix_web::error::Error {
|
||||
fn from(e: Error) -> Self {
|
||||
HttpResponseBuilder::new(StatusCode::BAD_GATEWAY).body(e.0).into()
|
||||
match e {
|
||||
Error::BadGateway(msg) => {HttpResponseBuilder::new(StatusCode::BAD_GATEWAY).body(msg).into()}
|
||||
Error::Unauthorized(realm) => {AuthenticationError::from(basic::Config::default().realm(realm)).into()}}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ use std::ops::Add;
|
||||
|
||||
use git2::{Commit, ObjectType, Oid, Reference, Repository, Tree};
|
||||
|
||||
use crate::gitdir::GitDir;
|
||||
use crate::gitfile::GitFile;
|
||||
use crate::gitutils::gitdir::GitDir;
|
||||
use crate::gitutils::gitfile::GitFile;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum GitBrowseEntry<'a> {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub struct Gitust {
|
||||
pub repo_root_path : String,
|
||||
pub session_key : String,
|
||||
}
|
||||
109
src/gitutils/gitproto.rs
Normal file
109
src/gitutils/gitproto.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use std::process::Stdio;
|
||||
|
||||
use actix_web::{HttpRequest, web, HttpResponse};
|
||||
use actix_web::http::{header, StatusCode};
|
||||
use actix_web::web::Buf;
|
||||
use actix_web_httpauth::extractors::basic::BasicAuth;
|
||||
use futures::StreamExt;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
|
||||
use crate::gitust::Gitust;
|
||||
use crate::reader::ToStream;
|
||||
use crate::error;
|
||||
use crate::webutils::auth;
|
||||
|
||||
//#[get("/git/{owner}/{repo}.git/{path:.*}")]
|
||||
pub async fn git_proto<T : auth::AuthValidator>(
|
||||
mut payload : web::Payload,
|
||||
web::Path((owner, reponame, path)): web::Path<(String, String, String)>,
|
||||
mut req: HttpRequest,
|
||||
gitust : web::Data<Gitust>,
|
||||
authenticator : web::Data<T>,
|
||||
auth : Option<BasicAuth>,
|
||||
) -> Result<HttpResponse, error::Error>{
|
||||
let user = auth.and_then(|a| authenticator.check_basic(&a)).ok_or(error::Error::Unauthorized("git_proto".to_string()))?;
|
||||
//println!("enter git_proto");
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("http-backend");
|
||||
|
||||
// Required environment variables
|
||||
cmd.env("REQUEST_METHOD", req.method().as_str());
|
||||
cmd.env("GIT_PROJECT_ROOT", &gitust.repo_root_path);
|
||||
cmd.env("PATH_INFO", format!("/{}/{}.git/{}",owner, reponame, path));
|
||||
cmd.env("REMOTE_USER", user.get_name());
|
||||
//cmd.env("REMOTE_ADDR", req.remote_addr().to_string());
|
||||
cmd.env("QUERY_STRING", req.query_string());
|
||||
cmd.env("CONTENT_TYPE", header(&req, header::CONTENT_TYPE));
|
||||
cmd.env("GIT_HTTP_EXPORT_ALL", "");
|
||||
cmd.stderr(Stdio::inherit())
|
||||
.stdout(Stdio::piped())
|
||||
.stdin(Stdio::piped());
|
||||
let mut p: Child = cmd.spawn()?;
|
||||
let mut input = p.stdin.take().unwrap();
|
||||
//println!("Displaying request...");
|
||||
while let Some(Ok(bytes)) = payload.next().await {
|
||||
//println!("request body : {}", String::from_utf8_lossy(bytes.bytes()));
|
||||
input.write_all(bytes.bytes()).await;
|
||||
}
|
||||
//println!("input sent");
|
||||
let mut rdr = tokio::io::BufReader::new(p.stdout.take().unwrap());
|
||||
|
||||
let mut headers = HashMap::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
let len = rdr.read_line(&mut line).await?;
|
||||
// println!("line : \"{}\"", line);
|
||||
if line.len() == 2 {
|
||||
break;
|
||||
}
|
||||
|
||||
let mut parts = line.splitn(2, ':');
|
||||
let key = parts.next().unwrap();
|
||||
let value = parts.next().unwrap();
|
||||
let value_len = value.len();
|
||||
let value = &value[1..value_len-2];
|
||||
headers
|
||||
.entry(key.to_string())
|
||||
.or_insert_with(Vec::new)
|
||||
.push(value.to_string());
|
||||
}
|
||||
//println!("response headers : {:?}", headers);
|
||||
|
||||
let status_code : u16 = {
|
||||
let line = headers.remove("Status").unwrap_or_default();
|
||||
// println!("{:?}", &line);
|
||||
let line = line.into_iter().next().unwrap_or_default();
|
||||
let parts : Vec<&str> = line.split(' ').collect();
|
||||
parts.into_iter().next().unwrap_or("").parse().unwrap_or(200)
|
||||
};
|
||||
// println!("status code {}", status_code);
|
||||
|
||||
let statusCode = match StatusCode::from_u16(status_code) {
|
||||
Ok(v) => {Ok(v)}
|
||||
Err(ioe) => {Err(io::Error::new(ErrorKind::Other, "Invalid HTTP status code"))}
|
||||
};
|
||||
let mut builder = HttpResponse::build(statusCode?);
|
||||
for (name, vec) in headers.iter() {
|
||||
for value in vec {
|
||||
// println!("entry : ({}, {})", name, value.clone());
|
||||
builder.header(name, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// println!("Write body...");
|
||||
|
||||
let response = builder.streaming(ToStream(rdr));
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
fn header(req: &HttpRequest, name: header::HeaderName) -> &str {
|
||||
req.headers()
|
||||
.get(name)
|
||||
.map(|value| value.to_str().unwrap_or_default())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -3,9 +3,9 @@ use std::ops::Add;
|
||||
use git2::{ObjectType, Oid, Repository, BranchType};
|
||||
|
||||
use crate::git::GitBrowseEntry;
|
||||
use crate::gitcommit::GitRef;
|
||||
use crate::gitdir::GitDir;
|
||||
use crate::gitfile::GitFile;
|
||||
use crate::gitutils::gitcommit::GitRef;
|
||||
use crate::gitutils::gitdir::GitDir;
|
||||
use crate::gitutils::gitfile::GitFile;
|
||||
use std::path::{PathBuf, Path};
|
||||
use std::str::FromStr;
|
||||
|
||||
@@ -78,4 +78,28 @@ impl GitRepo {
|
||||
return Ok(res);
|
||||
}
|
||||
|
||||
pub fn get_revisions_nbr(&self) -> u32 {
|
||||
let mut res = 0;
|
||||
let mut revwalk = self.git2.revwalk().expect("revisions walk is not defined");
|
||||
revwalk.push_head(); // todo : voir ce qu'il faut réellement pousser si on veux avoir TOUS les commits (genre par exemple si le HEAD n'est pas fils de tous les commits)
|
||||
for _ in revwalk{
|
||||
res = res + 1;
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
pub fn get_branches_nbr(&self) -> u32 {
|
||||
let mut res = 0;
|
||||
for _ in self.git2.branches(Some(BranchType::Local)){
|
||||
res = res + 1;
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
pub fn get_tags_nbr(&self) -> u32 {
|
||||
let mut res = 0;
|
||||
self.git2.tag_foreach(|_,_| {res = res + 1;true});
|
||||
res
|
||||
}
|
||||
|
||||
}
|
||||
5
src/gitutils/mod.rs
Normal file
5
src/gitutils/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub mod gitdir;
|
||||
pub mod gitrepo;
|
||||
pub mod gitcommit;
|
||||
pub mod gitfile;
|
||||
pub mod gitproto;
|
||||
256
src/main.rs
256
src/main.rs
@@ -7,15 +7,16 @@ 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, web};
|
||||
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::dev::{ServiceRequest, Service};
|
||||
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::{AuthenticationError, AuthExtractor};
|
||||
use actix_web_httpauth::extractors::basic::{BasicAuth, Config};
|
||||
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
|
||||
use actix_web_httpauth::middleware::HttpAuthentication;
|
||||
@@ -27,27 +28,31 @@ use serde::Deserialize;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::process::{Child, ChildStdout, Command};
|
||||
|
||||
use gitcommit::GitRef;
|
||||
use gitdir::GitDir;
|
||||
use gitrepo::GitRepo;
|
||||
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;
|
||||
use crate::gitfile::GitFile;
|
||||
use crate::web::repo::GitWebQ;
|
||||
use crate::webutils::auth::{TestValidator, AuthValidator, User};
|
||||
|
||||
mod git;
|
||||
mod ite;
|
||||
mod reader;
|
||||
mod writer;
|
||||
mod gitust;
|
||||
mod gitdir;
|
||||
mod gitrepo;
|
||||
mod gitcommit;
|
||||
mod gitfile;
|
||||
mod error;
|
||||
mod web;
|
||||
mod gitutils;
|
||||
mod webutils;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "hello.html")]
|
||||
@@ -55,36 +60,6 @@ struct HelloTemplate<'a> {
|
||||
name: &'a str,
|
||||
}
|
||||
|
||||
struct User {
|
||||
name : String,
|
||||
}
|
||||
|
||||
struct Owner {
|
||||
name : String,
|
||||
}
|
||||
|
||||
struct Repository {
|
||||
name : String,
|
||||
owner : Owner,
|
||||
}
|
||||
|
||||
enum Entry {
|
||||
Dir(String),
|
||||
File(String),
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "git.html")]
|
||||
struct GitMainTemplate<TS, ROOT>
|
||||
where for <'a> &'a TS : IntoIterator<Item = &'a Entry>,
|
||||
for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>,
|
||||
{
|
||||
repo : Repository,
|
||||
browse : TS,
|
||||
root : ROOT,
|
||||
user_opt : Option<User>,
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
async fn hello() -> impl Responder {
|
||||
HttpResponse::Ok().body("Bonjour monde !")
|
||||
@@ -120,14 +95,6 @@ async fn hello_auth(req : HttpRequest) -> impl Responder {
|
||||
}
|
||||
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GitWebQ {
|
||||
commit: Option<String>,
|
||||
path: Option<String>,
|
||||
branch: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
#[get("/chunk")]
|
||||
async fn chunk() -> HttpResponse {
|
||||
let (tx, rx) = actix_utils::mpsc::channel::<Result<Bytes, Error>>();
|
||||
@@ -146,144 +113,6 @@ async fn chunk() -> HttpResponse {
|
||||
HttpResponse::Ok().streaming(rx)
|
||||
}
|
||||
|
||||
#[get("/git/{owner}/{repo}.git")]
|
||||
async fn git_main(
|
||||
web::Path((ownername, reponame)): web::Path<(String, String)>,
|
||||
web::Query(GitWebQ{commit : commitnameopt, path : pathopt, branch : branchopt}) : web::Query<GitWebQ>,
|
||||
gitust : web::Data<Gitust>
|
||||
) -> Result<GitMainTemplate<Vec<Entry>, Vec<(String, String)>>, error::Error> {
|
||||
let rootname = match pathopt {
|
||||
None => {"".to_string()}
|
||||
Some(s) => {
|
||||
if s.starts_with("/") {
|
||||
(&s[1..]).to_string()
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
};
|
||||
let commit = match commitnameopt {
|
||||
None => {match branchopt {
|
||||
None => {GitRef::Head}
|
||||
Some(s) => {GitRef::Branch(s)}
|
||||
}}
|
||||
Some(s) => {GitRef::Commit(s)}
|
||||
};
|
||||
let owner = Owner { name : ownername};
|
||||
let repo = Repository {name : reponame, owner};
|
||||
let user = User { name : "Hubert".to_string()};
|
||||
// il faut ajouter le commit/branch dans la query
|
||||
let path = rootname.split("/").map_accum("/git/".to_string() + &repo.owner.name + "/" + &repo.name, |str_ref, b| {
|
||||
let href = b + "/" + str_ref;
|
||||
((str_ref.to_string(), href.clone()), href)
|
||||
}).collect();
|
||||
let gitrepo = GitRepo::new(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name).as_str())?;
|
||||
let root = gitrepo.get_tree(&commit, Path::new(rootname.as_str()))?;
|
||||
let browse = gitrepo.browse(&root).await?;
|
||||
let mut entries : Vec<Entry> = Vec::new();
|
||||
for entry in browse {
|
||||
match entry {
|
||||
GitBrowseEntry::EGitFile(GitFile(fullname)) => {
|
||||
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
|
||||
entries.push(Entry::File(format!("{}",osstr.to_string_lossy())));
|
||||
}
|
||||
GitBrowseEntry::EGitDir(GitDir{fullname, .. }) => {
|
||||
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
|
||||
entries.push(Entry::Dir(format!("{}",osstr.to_string_lossy())));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(GitMainTemplate { repo, browse : entries, root : path, user_opt : Some(user)})
|
||||
}
|
||||
//#[get("/git/{owner}/{repo}.git/{path:.*}")]
|
||||
async fn git_proto(
|
||||
mut payload : web::Payload,
|
||||
web::Path((owner, reponame, path)): web::Path<(String, String, String)>,
|
||||
mut req: HttpRequest,
|
||||
gitust : web::Data<Gitust>,
|
||||
auth : BasicAuth,
|
||||
) -> io::Result<HttpResponse>{
|
||||
//println!("enter git_proto");
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("http-backend");
|
||||
|
||||
// Required environment variables
|
||||
cmd.env("REQUEST_METHOD", req.method().as_str());
|
||||
cmd.env("GIT_PROJECT_ROOT", &gitust.repo_root_path);
|
||||
cmd.env("PATH_INFO", format!("/{}/{}.git/{}",owner, reponame, path));
|
||||
cmd.env("REMOTE_USER", auth.user_id().to_string());
|
||||
//cmd.env("REMOTE_ADDR", req.remote_addr().to_string());
|
||||
cmd.env("QUERY_STRING", req.query_string());
|
||||
cmd.env("CONTENT_TYPE", header(&req, header::CONTENT_TYPE));
|
||||
cmd.env("GIT_HTTP_EXPORT_ALL", "");
|
||||
cmd.stderr(Stdio::inherit())
|
||||
.stdout(Stdio::piped())
|
||||
.stdin(Stdio::piped());
|
||||
let mut p: Child = cmd.spawn()?;
|
||||
let mut input = p.stdin.take().unwrap();
|
||||
//println!("Displaying request...");
|
||||
while let Some(Ok(bytes)) = payload.next().await {
|
||||
//println!("request body : {}", String::from_utf8_lossy(bytes.bytes()));
|
||||
input.write_all(bytes.bytes()).await;
|
||||
}
|
||||
//println!("input sent");
|
||||
let mut rdr = tokio::io::BufReader::new(p.stdout.take().unwrap());
|
||||
|
||||
let mut headers = HashMap::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
let len = rdr.read_line(&mut line).await?;
|
||||
// println!("line : \"{}\"", line);
|
||||
if line.len() == 2 {
|
||||
break;
|
||||
}
|
||||
|
||||
let mut parts = line.splitn(2, ':');
|
||||
let key = parts.next().unwrap();
|
||||
let value = parts.next().unwrap();
|
||||
let value_len = value.len();
|
||||
let value = &value[1..value_len-2];
|
||||
headers
|
||||
.entry(key.to_string())
|
||||
.or_insert_with(Vec::new)
|
||||
.push(value.to_string());
|
||||
}
|
||||
//println!("response headers : {:?}", headers);
|
||||
|
||||
let status_code : u16 = {
|
||||
let line = headers.remove("Status").unwrap_or_default();
|
||||
// println!("{:?}", &line);
|
||||
let line = line.into_iter().next().unwrap_or_default();
|
||||
let parts : Vec<&str> = line.split(' ').collect();
|
||||
parts.into_iter().next().unwrap_or("").parse().unwrap_or(200)
|
||||
};
|
||||
// println!("status code {}", status_code);
|
||||
|
||||
let statusCode = match StatusCode::from_u16(status_code) {
|
||||
Ok(v) => {Ok(v)}
|
||||
Err(ioe) => {Err(io::Error::new(ErrorKind::Other, "Invalid HTTP status code"))}
|
||||
};
|
||||
let mut builder = HttpResponse::build(statusCode?);
|
||||
for (name, vec) in headers.iter() {
|
||||
for value in vec {
|
||||
// println!("entry : ({}, {})", name, value.clone());
|
||||
builder.header(name, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// println!("Write body...");
|
||||
|
||||
let response = builder.streaming(ToStream(rdr));
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
fn header(req: &HttpRequest, name: header::HeaderName) -> &str {
|
||||
req.headers()
|
||||
.get(name)
|
||||
.map(|value| value.to_str().unwrap_or_default())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[post("/echo")]
|
||||
async fn echo(req_body: String) -> impl Responder {
|
||||
HttpResponse::Ok().body(req_body)
|
||||
@@ -294,7 +123,7 @@ async fn manual_hello() -> impl Responder {
|
||||
}
|
||||
|
||||
#[get("/{id}/{name}/index.html")]
|
||||
async fn index(web::Path((id, name)): web::Path<(u32, String)>) -> impl Responder {
|
||||
async fn index(webx::Path((id, name)): webx::Path<(u32, String)>) -> impl Responder {
|
||||
format!("Hello {}! id:{}", name, id)
|
||||
}
|
||||
|
||||
@@ -323,25 +152,55 @@ fn validate_credentials(user_id: &str, user_password: Option<&str>) -> Result<bo
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::Other, "Authentication failed!"));
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct LoginQ {
|
||||
login: Option<bool>,
|
||||
}
|
||||
|
||||
#[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()
|
||||
.data(Gitust {
|
||||
repo_root_path: "/home/hubert/gitust".to_string(),
|
||||
})
|
||||
.wrap(Logger::default())
|
||||
// .wrap(Logger::new("%a %{User-Agent}i"))
|
||||
.wrap(CookieSession::signed(&[0; 32]).secure(false))
|
||||
.wrap(CookieSession::signed(session_key).secure(false))
|
||||
.data(gitust)
|
||||
.data(auth::TestValidator)
|
||||
.service(hello)
|
||||
.service(echo)
|
||||
.service(hello_test)
|
||||
.service(index)
|
||||
.service(askama)
|
||||
.service(git_main)
|
||||
.service(
|
||||
webx::resource("/git/{owner}/{repo}.git")
|
||||
.wrap_fn(|req, serv| {
|
||||
let query : Result<webx::Query<LoginQ>, _> = webx::Query::from_query(req.query_string());
|
||||
let authFut = BasicAuth::from_service_request(&req);
|
||||
let resFut = serv.call(req);
|
||||
async {
|
||||
let webx::Query(LoginQ{login}) = query?;
|
||||
match login {
|
||||
Some(true) => {
|
||||
let auth = authFut.await?;
|
||||
match TestValidator.check_basic(&auth) {
|
||||
None => {Err(AuthenticationError::from(Config::default().realm("auth")).into())}
|
||||
Some(_) => {resFut.await}
|
||||
}
|
||||
}
|
||||
_ => {resFut.await}
|
||||
}
|
||||
}
|
||||
})
|
||||
.route(webx::get().to(repo::git_main::<auth::TestValidator>))
|
||||
)
|
||||
.service(hello_session)
|
||||
.service(chunk)
|
||||
//.service(git_proto)
|
||||
@@ -351,14 +210,13 @@ async fn main() -> std::io::Result<()> {
|
||||
// .route("/", web::get().to(hello_auth))
|
||||
// )
|
||||
.service(
|
||||
web::resource("/auth")
|
||||
webx::resource("/auth")
|
||||
.wrap(auth)
|
||||
.route(web::get().to(hello_auth))
|
||||
.route(webx::get().to(hello_auth))
|
||||
)
|
||||
.service(
|
||||
web::resource("/git/{user}/{repo}.git/{path:.*}")
|
||||
// .wrap(auth)
|
||||
.route(web::route().to(git_proto))
|
||||
webx::resource("/git/{user}/{repo}.git/{path:.*}")
|
||||
.route(webx::route().to(gitproto::git_proto::<auth::TestValidator>))
|
||||
)
|
||||
.service(
|
||||
Files::new("/static", "static")
|
||||
@@ -366,7 +224,7 @@ async fn main() -> std::io::Result<()> {
|
||||
.use_etag(true)
|
||||
// .show_files_listing()
|
||||
)
|
||||
.route("/hey", web::get().to(manual_hello))
|
||||
.route("/hey", webx::get().to(manual_hello))
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
|
||||
1
src/web/mod.rs
Normal file
1
src/web/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod repo;
|
||||
188
src/web/repo.rs
Normal file
188
src/web/repo.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
use crate::auth::AuthValidator;
|
||||
use std::path::Path;
|
||||
|
||||
use actix_web::web;
|
||||
use actix_web_httpauth::extractors::basic;
|
||||
|
||||
use actix_web::get;
|
||||
use askama_actix::Template;
|
||||
use serde::Deserialize;
|
||||
|
||||
|
||||
use crate::error;
|
||||
use crate::git::GitBrowseEntry;
|
||||
use crate::gitust::Gitust;
|
||||
use crate::gitutils::gitcommit::GitRef;
|
||||
use crate::gitutils::gitdir::GitDir;
|
||||
use crate::gitutils::gitfile::GitFile;
|
||||
use crate::gitutils::gitrepo::GitRepo;
|
||||
use crate::ite::SuperIterator;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
struct User {
|
||||
name : String,
|
||||
}
|
||||
|
||||
struct Owner {
|
||||
name : String,
|
||||
}
|
||||
|
||||
struct Repository {
|
||||
name : String,
|
||||
owner : Owner,
|
||||
}
|
||||
|
||||
pub enum Entry {
|
||||
Dir(String),
|
||||
File(String),
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "git.html")]
|
||||
pub struct GitMainTemplate<TS, BREADCRUMB>
|
||||
where for <'a> &'a TS : IntoIterator<Item = &'a Entry>,
|
||||
for <'a> &'a BREADCRUMB: IntoIterator<Item = &'a (String, String)>,
|
||||
{
|
||||
repo : Repository,
|
||||
browse : TS,
|
||||
query : GitWebQ,
|
||||
breadcrumb: BREADCRUMB,
|
||||
user_opt : Option<User>,
|
||||
revisions_nbr : u32,
|
||||
branches_nbr : u32,
|
||||
tags_nbr : u32,
|
||||
size : String,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct GitWebQ {
|
||||
commit: Option<String>,
|
||||
path: Option<String>,
|
||||
branch: Option<String>,
|
||||
}
|
||||
|
||||
impl GitWebQ {
|
||||
fn clone_with_commit(&self, commit : Option<String>) -> GitWebQ {
|
||||
let mut res = self.clone();
|
||||
res.commit = commit;
|
||||
return res;
|
||||
}
|
||||
|
||||
fn clone_with_path(&self, path : Option<String>) -> GitWebQ {
|
||||
let mut res = self.clone();
|
||||
res.path = path;
|
||||
return res;
|
||||
}
|
||||
|
||||
fn clone_with_branch(&self, branch : Option<String>) -> GitWebQ {
|
||||
let mut res = self.clone();
|
||||
res.branch = branch;
|
||||
return res;
|
||||
}
|
||||
|
||||
fn root_query(&self) -> GitWebQ {
|
||||
self.clone_with_path(None)
|
||||
}
|
||||
|
||||
fn add_path(&self, name : &&String) -> GitWebQ {
|
||||
match &self.path {
|
||||
None => {self.clone_with_path(Some(name.to_string()))}
|
||||
Some(path) => {if path.ends_with("/") {
|
||||
self.clone_with_path(Some(path.clone() + name))
|
||||
} else {
|
||||
self.clone_with_path(Some(path.clone() + "/" + name))
|
||||
}}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for GitWebQ{
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "?{}{}{}",
|
||||
match &self.commit {
|
||||
None => {"".to_string()}
|
||||
Some(c) => {format!("commit={}", c)}
|
||||
},
|
||||
match &self.path {
|
||||
None => {"".to_string()}
|
||||
Some(p) => {format!("&path={}", p)}
|
||||
},
|
||||
match &self.branch {
|
||||
None => {"".to_string()}
|
||||
Some(b) => {format!("&branch={}", b)}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
//#[get("/git/{owner}/{repo}.git")]
|
||||
pub async fn git_main<T : AuthValidator>(
|
||||
web::Path((ownername, reponame)): web::Path<(String, String)>,
|
||||
query : web::Query<GitWebQ>,
|
||||
gitust : web::Data<Gitust>,
|
||||
auth : Option<basic::BasicAuth>,
|
||||
validator : web::Data<T>,
|
||||
//auth : BasicAuth,
|
||||
) -> Result<GitMainTemplate<Vec<Entry>, Vec<(String, String)>>, error::Error> {
|
||||
// let authtorization = auth.ok_or(error::Error::Unauthorized("safe repo".to_string()))?;
|
||||
//let authorization = auth.and_then(|cred| validator.check_basic(&cred)).ok_or(error::Error::Unauthorized("safe repo".to_string()))?;
|
||||
let web::Query(query_struct) = query;
|
||||
// let GitWebQ{commit : commitnameopt, path : pathopt, branch : branchopt} = query_struct;
|
||||
let rootname = match &query_struct.path {
|
||||
None => {"".to_string()}
|
||||
Some(s) => {
|
||||
if s.starts_with("/") {
|
||||
(&s[1..]).to_string()
|
||||
} else {
|
||||
s.clone()
|
||||
}
|
||||
}
|
||||
};
|
||||
let commit = match &query_struct.commit {
|
||||
None => {match &query_struct.branch {
|
||||
None => {GitRef::Head}
|
||||
Some(s) => {GitRef::Branch(s.clone())}
|
||||
}}
|
||||
Some(s) => {GitRef::Commit(s.clone())}
|
||||
};
|
||||
let owner = Owner { name : ownername};
|
||||
let repo = Repository {name : reponame, owner};
|
||||
// let user = User { name : "Hubert".to_string()};
|
||||
let user = auth.map(|auth| User{name : auth.user_id().to_string()});
|
||||
// il faut ajouter le commit/branch dans la query
|
||||
let path = rootname.split("/").map_accum(query_struct.clone_with_path(Some("".to_string())), |direname, b| {
|
||||
let newpath = (&b.path).as_ref().map(|path| {path.clone() + "/" + direname});
|
||||
let newb = b.clone_with_path(newpath);
|
||||
((direname.to_string(), format!("{}", newb)), newb)
|
||||
}).collect();
|
||||
let gitrepo = GitRepo::new(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name).as_str())?;
|
||||
let root = gitrepo.get_tree(&commit, Path::new(rootname.as_str()))?;
|
||||
let browse = gitrepo.browse(&root).await?;
|
||||
let mut entries : Vec<Entry> = Vec::new();
|
||||
for entry in browse {
|
||||
match entry {
|
||||
GitBrowseEntry::EGitFile(GitFile(fullname)) => {
|
||||
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
|
||||
entries.push(Entry::File(format!("{}",osstr.to_string_lossy())));
|
||||
}
|
||||
GitBrowseEntry::EGitDir(GitDir{fullname, .. }) => {
|
||||
let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?;
|
||||
entries.push(Entry::Dir(format!("{}",osstr.to_string_lossy())));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(GitMainTemplate {
|
||||
repo,
|
||||
browse : entries,
|
||||
query : query_struct,
|
||||
breadcrumb: path,
|
||||
user_opt : user,
|
||||
revisions_nbr : gitrepo.get_revisions_nbr(),
|
||||
branches_nbr : gitrepo.get_branches_nbr(),
|
||||
tags_nbr : gitrepo.get_tags_nbr(),
|
||||
size : "16 KiB".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
48
src/webutils/auth.rs
Normal file
48
src/webutils/auth.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use actix_session::Session;
|
||||
use actix_web_httpauth::extractors::basic::BasicAuth;
|
||||
|
||||
pub trait AuthValidator {
|
||||
fn check_user(&self, name : &String, pwd : &String) -> bool;
|
||||
|
||||
fn check_basic(&self, basic : &BasicAuth) -> Option<User> {
|
||||
match basic.password() {
|
||||
Option::Some(pwd) => {
|
||||
let username = basic.user_id().to_string();
|
||||
if self.check_user(&username, &pwd.to_string()) {
|
||||
Some(User(username))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Option::None => {None}
|
||||
}
|
||||
//basic.password().and_then(|pwd| self.check_user(&basic.user_id().to_string(), &pwd.to_string()))
|
||||
}
|
||||
|
||||
fn check_session(&self, session : &Session) -> Option<User> {
|
||||
let result = session.get::<String>("user");
|
||||
match result {
|
||||
Ok(username) => {username.map(|u| User(u))}
|
||||
Err(e) => {
|
||||
println!("{}", e);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TestValidator;
|
||||
|
||||
impl AuthValidator for TestValidator {
|
||||
fn check_user(&self, name: &String, pwd: &String) -> bool {
|
||||
pwd.eq(&(name.clone() + "pwd"))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct User(String);
|
||||
|
||||
impl User {
|
||||
pub fn get_name(&self) -> String {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
2
src/webutils/mod.rs
Normal file
2
src/webutils/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod auth;
|
||||
pub mod user;
|
||||
0
src/webutils/user.rs
Normal file
0
src/webutils/user.rs
Normal file
@@ -26,7 +26,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{% when None %}
|
||||
<a href="#" class="w3-bar-item w3-button w3-right"><i class="fa fa-sign-in"></i> Log in</a>
|
||||
<a href="?login=true" class="w3-bar-item w3-button w3-right"><i class="fa fa-sign-in"></i> Log in</a>
|
||||
{% endmatch %}
|
||||
</div>
|
||||
{% block content %}{% endblock %}
|
||||
|
||||
@@ -26,16 +26,16 @@
|
||||
|
||||
<div class="w3-panel w3-border w3-cell-row">
|
||||
<div class="w3-center w3-cell">
|
||||
<i class="fa fa-history"></i> 112 revisions
|
||||
<i class="fa fa-history"></i> {{ revisions_nbr }} revisions
|
||||
</div>
|
||||
<div class="w3-center w3-cell">
|
||||
<i class="fa fa-code-branch"></i> 10 branches
|
||||
<i class="fa fa-code-branch"></i> {{ branches_nbr }} branches
|
||||
</div>
|
||||
<div class="w3-center w3-cell">
|
||||
<i class="fa fa-tag"></i> 5 tags
|
||||
<i class="fa fa-tag"></i> {{ tags_nbr }} tags
|
||||
</div>
|
||||
<div class="w3-center w3-cell">
|
||||
<i class="fa fa-database"></i> 10 KiB
|
||||
<i class="fa fa-database"></i> {{ size }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -60,8 +60,8 @@
|
||||
<div class="w3-cell-row">
|
||||
<div class="w3-cell">
|
||||
<ul class="breadcrumb">
|
||||
<li><a href="#">{{repo.name}}</a></li>
|
||||
{% for (dir, prev) in root %}
|
||||
<li><a href="{{query.root_query()}}">{{repo.name}}.git</a></li>
|
||||
{% for (dir, prev) in breadcrumb %}
|
||||
<li><a href="{{prev}}">{{dir}}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
@@ -77,7 +77,7 @@
|
||||
{% for entry in browse %}
|
||||
{% match entry %}
|
||||
{% when Entry::Dir with (name) %}
|
||||
<li><i class="fa fa-folder"></i> {{ name }}</li>
|
||||
<li><i class="fa fa-folder"></i> <a href="{{query.add_path(name)}}">{{ name }}</a></li>
|
||||
{% when Entry::File with (name) %}
|
||||
<li><i class="fa fa-file"></i> {{ name }}</li>
|
||||
{% endmatch %}
|
||||
|
||||
Reference in New Issue
Block a user