Compare commits

...

24 Commits

Author SHA1 Message Date
6beae6629f gestion des paths 2021-11-13 07:15:51 +01:00
Hubert
ba19d67f66 save 2021-07-24 08:27:53 +02:00
Hubert
f9bc5b2e39 working breadcrumb 2021-07-24 08:02:16 +02:00
Hubert
dbba11a416 renaming 2021-07-24 07:07:03 +02:00
Hubert
edf6f9f81a root -> breadcrumb 2021-07-24 06:52:46 +02:00
hubert
5f6f7b7efe get_tags_nbr 2021-07-23 13:47:41 +02:00
hubert
1f4d08aff1 get_branches_nbr 2021-07-23 13:43:04 +02:00
hubert
f71e8ff1b3 revisions_nbr 2021-07-23 13:35:14 +02:00
hubert
4134982739 login button works 2021-07-23 12:54:42 +02:00
Hubert
1e7c773c19 basic auth triggered by query 2021-07-23 06:55:24 +02:00
hubert
9832f30360 add commented line as place holder 2021-07-22 13:52:49 +02:00
hubert
22836e1f3a generalise git_main 2021-07-22 13:36:48 +02:00
hubert
90ea298a61 prepare generalisation git_main 2021-07-22 13:33:49 +02:00
hubert
e3008262fc change validator api 2021-07-22 13:24:11 +02:00
hubert
abc1f367bb print error when validating 2021-07-22 13:14:58 +02:00
6d87adb2e6 validator for git proto 2021-07-21 13:33:12 +02:00
aa131d009f save 2021-07-21 13:16:09 +02:00
Hubert
9af4fa56e1 save 2021-07-21 07:03:27 +02:00
Hubert
90bc6d6d4f save 2021-07-21 06:53:03 +02:00
Hubert
381347e66a user from basic auth 2021-07-21 06:05:54 +02:00
234e2ccaa3 save 2021-07-20 21:47:20 +02:00
Hubert
2bc387920c save 2021-07-20 07:03:14 +02:00
Hubert
07f11b238e save refacto 2021-07-20 06:52:19 +02:00
Hubert
0875a78cf8 save refacto 2021-07-20 06:46:24 +02:00
13 changed files with 444 additions and 200 deletions

View File

@@ -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()}}
}
}

View File

@@ -1,3 +1,4 @@
pub struct Gitust {
pub repo_root_path : String,
pub session_key : String,
}

109
src/gitutils/gitproto.rs Normal file
View 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()
}

View File

@@ -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
}
}

View File

@@ -2,3 +2,4 @@ pub mod gitdir;
pub mod gitrepo;
pub mod gitcommit;
pub mod gitfile;
pub mod gitproto;

View File

@@ -9,14 +9,14 @@ 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::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;
@@ -31,13 +31,18 @@ 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;
use crate::web::repo::GitWebQ;
use crate::webutils::auth::{TestValidator, AuthValidator, User};
mod git;
mod ite;
@@ -47,6 +52,7 @@ mod gitust;
mod error;
mod web;
mod gitutils;
mod webutils;
#[derive(Template)]
#[template(path = "hello.html")]
@@ -54,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 !")
@@ -119,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>>();
@@ -145,146 +113,6 @@ async fn chunk() -> HttpResponse {
HttpResponse::Ok().streaming(rx)
}
#[get("/git/{owner}/{repo}.git")]
async fn git_main(
webx::Path((ownername, reponame)): webx::Path<(String, String)>,
webx::Query(GitWebQ{commit : commitnameopt, path : pathopt, branch : branchopt}) : webx::Query<GitWebQ>,
gitust : webx::Data<Gitust>,
auth : Option<BasicAuth>,
//auth : BasicAuth,
) -> 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 : webx::Payload,
webx::Path((owner, reponame, path)): webx::Path<(String, String, String)>,
mut req: HttpRequest,
gitust : webx::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)
@@ -324,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);
App::new()
.data(Gitust {
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(&[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)
@@ -358,8 +216,7 @@ async fn main() -> std::io::Result<()> {
)
.service(
webx::resource("/git/{user}/{repo}.git/{path:.*}")
// .wrap(auth)
.route(webx::route().to(git_proto))
.route(webx::route().to(gitproto::git_proto::<auth::TestValidator>))
)
.service(
Files::new("/static", "static")

View File

@@ -1 +1 @@
mod repo;
pub mod repo;

View 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
View 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
View File

@@ -0,0 +1,2 @@
pub mod auth;
pub mod user;

0
src/webutils/user.rs Normal file
View File

View 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 %}

View File

@@ -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 %}