aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorKunoiSayami <[email protected]>2021-05-08 01:24:07 +0800
committerKunoiSayami <[email protected]>2021-05-08 01:24:07 +0800
commita3eaa8611425c87ef940215650bad6668464c301 (patch)
treefa8169a7344eb1bfba65254b3eecc7a86e03f20f /src
parent86e4c76dabb20b7f489abcb1f1c3cdb11a494b91 (diff)
style: Address cargo fmt
Diffstat (limited to 'src')
-rw-r--r--src/datastructures.rs18
-rw-r--r--src/main.rs92
2 files changed, 48 insertions, 62 deletions
diff --git a/src/datastructures.rs b/src/datastructures.rs
index b920eb4..0438b70 100644
--- a/src/datastructures.rs
+++ b/src/datastructures.rs
@@ -18,12 +18,12 @@
** along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-use sha2::Digest;
use anyhow::Result;
-use url::form_urlencoded;
+use sha2::Digest;
use std::borrow::Cow;
-use std::path::Path;
use std::fs::read_to_string;
+use std::path::Path;
+use url::form_urlencoded;
const DEFAULT_CONFIG_LOCATION: &str = "/etc/cgitrc";
const DEFAULT_COOKIE_TTL: u64 = 1200;
@@ -56,10 +56,9 @@ impl Config {
let mut cookie_ttl: u64 = DEFAULT_COOKIE_TTL;
let mut database: &str = "/etc/cgit/auth.db";
for line in file.lines() {
-
let line = line.trim();
if !line.contains('=') || !line.starts_with("cgit-simple-auth-") {
- continue
+ continue;
}
let (key, value) = if line.contains('#') {
@@ -76,7 +75,7 @@ impl Config {
}
Self {
cookie_ttl,
- database: database.to_string()
+ database: database.to_string(),
}
}
@@ -85,7 +84,6 @@ impl Config {
}
}
-
#[derive(Debug, Clone, Default)]
pub struct FormData {
user: String,
@@ -95,7 +93,9 @@ pub struct FormData {
impl FormData {
pub fn new() -> Self {
- Self { ..Default::default()}
+ Self {
+ ..Default::default()
+ }
}
pub fn get_string_sha256_value(s: &str) -> Result<String> {
@@ -165,4 +165,4 @@ impl From<String> for FormData {
fn from(s: String) -> Self {
Self::from(&s)
}
-} \ No newline at end of file
+}
diff --git a/src/main.rs b/src/main.rs
index 0875993..699d34f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -21,21 +21,20 @@
mod database;
mod datastructures;
+use crate::datastructures::{Config, FormData};
use anyhow::Result;
-use std::io::{stdin, Read};
-use std::env;
-use clap::{Arg, App, SubCommand, ArgMatches};
-use rand::Rng;
-use serde::{Serialize};
+use clap::{App, Arg, ArgMatches, SubCommand};
use handlebars::Handlebars;
-use sqlx::Connection;
-use crate::datastructures::{Config, FormData};
+use rand::Rng;
use redis::AsyncCommands;
+use serde::Serialize;
+use sqlx::Connection;
+use std::env;
+use std::io::{stdin, Read};
use std::result::Result::Ok;
const COOKIE_LENGTH: usize = 45;
-
fn get_current_timestamp() -> u64 {
let start = std::time::SystemTime::now();
let since_the_epoch = start
@@ -65,37 +64,28 @@ fn rand_int() -> i32 {
rng.gen()
}
-
#[derive(Serialize)]
struct Meta<'a> {
action: &'a str,
redirect: &'a str,
}
-
// Processing the `authenticate-basic` called by cgit.
-fn cmd_authenticate_basic(
- _matches: &ArgMatches,
- _cfg: Config,
-) -> Result<()> {
+fn cmd_authenticate_basic(_matches: &ArgMatches, _cfg: Config) -> Result<()> {
unimplemented!()
}
// Processing the `authenticate-cookie` called by cgit.
-async fn cmd_authenticate_cookie(
- matches: &ArgMatches<'_>,
- cfg: Config,
-) -> Result<bool> {
- let cookies = matches.value_of("http-cookie").unwrap_or("");
+async fn cmd_authenticate_cookie(matches: &ArgMatches<'_>, cfg: Config) -> Result<bool> {
+ let cookies = matches.value_of("http-cookie").unwrap_or("");
if cookies.is_empty() {
- return Ok(false)
+ return Ok(false);
}
let redis_conn = redis::Client::open("redis://127.0.0.1/")?;
let mut conn = redis_conn.get_async_connection().await?;
-
for cookie in cookies.split(';').map(|x| x.trim()) {
let (key, value) = cookie.split_once('=').unwrap();
if key.eq("cgit_auth") {
@@ -103,34 +93,33 @@ async fn cmd_authenticate_cookie(
let value = std::str::from_utf8(&value).unwrap_or("");
if !value.contains(';') {
- break
+ break;
}
- let (key, value) = value.split_once(';').unwrap();//.unwrap_or(("0_0", "0"));
+ let (key, value) = value.split_once(';').unwrap(); //.unwrap_or(("0_0", "0"));
let (timestamp, _) = key.split_once("_").unwrap_or(("0", ""));
if get_current_timestamp() - timestamp.parse::<u64>().unwrap_or(0) > cfg.cookie_ttl {
- break
+ break;
}
if let Ok(r) = conn.get::<_, String>(format!("cgit_auth_{}", key)).await {
if r == value {
- return Ok(true)
+ return Ok(true);
}
}
- break
+ break;
}
}
Ok(false)
}
-
async fn cmd_init(cfg: Config) -> Result<()> {
log::trace!("{}", cfg.get_database_location());
let loc = std::path::Path::new(cfg.get_database_location());
- if ! loc.exists() {
+ if !loc.exists() {
std::fs::File::create(loc)?;
}
@@ -148,13 +137,15 @@ async fn cmd_init(cfg: Config) -> Result<()> {
log::info!("Initialize the database successfully");
}
-
Ok(())
}
async fn verify_login(cfg: &Config, data: &FormData) -> Result<bool> {
- let database_file_name = std::path::Path::new(datastructures::CACHE_DIR)
- .join(std::path::Path::new(cfg.get_database_location()).file_name().unwrap());
+ let database_file_name = std::path::Path::new(datastructures::CACHE_DIR).join(
+ std::path::Path::new(cfg.get_database_location())
+ .file_name()
+ .unwrap(),
+ );
std::fs::copy(cfg.get_database_location(), database_file_name.clone())?;
let mut conn = sqlx::SqliteConnection::connect(database_file_name.to_str().unwrap()).await?;
let password_sha = data.get_password_sha256()?;
@@ -167,12 +158,8 @@ async fn verify_login(cfg: &Config, data: &FormData) -> Result<bool> {
Ok(!ret.is_empty())
}
-
// Processing the `authenticate-post` called by cgit.
-async fn cmd_authenticate_post(
- matches: &ArgMatches<'_>,
- cfg: Config,
-) -> Result<()> {
+async fn cmd_authenticate_post(matches: &ArgMatches<'_>, cfg: Config) -> Result<()> {
// Read stdin from upstream.
let mut buffer = String::new();
stdin().read_to_string(&mut buffer)?;
@@ -192,13 +179,18 @@ async fn cmd_authenticate_post(
let redis_conn = redis::Client::open("redis://127.0.0.1/")?;
let mut conn = redis_conn.get_async_connection().await?;
- conn.set_ex::<_, _, String>(format!("cgit_auth_{}", key), &value, cfg.cookie_ttl as usize).await?;
+ conn.set_ex::<_, _, String>(
+ format!("cgit_auth_{}", key),
+ &value,
+ cfg.cookie_ttl as usize,
+ )
+ .await?;
let cookie_value = base64::encode(format!("{};{}", key, value));
let is_secure = matches
.value_of("https")
- .map_or(false, | x | matches!(x, "yes" | "on" | "1"));
+ .map_or(false, |x| matches!(x, "yes" | "on" | "1"));
let domain = matches.value_of("http-host").unwrap_or("*");
let location = matches
.value_of("current-url")
@@ -220,11 +212,9 @@ async fn cmd_authenticate_post(
}
println!();
-
Ok(())
}
-
// Processing the `body` called by cgit.
async fn cmd_body(matches: &ArgMatches<'_>, _cfg: Config) {
let source = include_str!("authentication_page.html");
@@ -238,12 +228,11 @@ async fn cmd_body(matches: &ArgMatches<'_>, _cfg: Config) {
.unwrap();
}
-
-async fn cmd_add_user(matches: &ArgMatches<'_>, cfg: Config) -> Result<()>{
+async fn cmd_add_user(matches: &ArgMatches<'_>, cfg: Config) -> Result<()> {
let user = matches.value_of("user").unwrap_or("");
let passwd = matches.value_of("password").unwrap_or("").to_string();
if user.is_empty() || passwd.is_empty() {
- return Err(anyhow::Error::msg("Invalid user or password"))
+ return Err(anyhow::Error::msg("Invalid user or password"));
}
let mut conn = sqlx::SqliteConnection::connect(cfg.get_database_location()).await?;
@@ -252,8 +241,8 @@ async fn cmd_add_user(matches: &ArgMatches<'_>, cfg: Config) -> Result<()>{
.fetch_all(&mut conn)
.await?;
- if ! items.is_empty() {
- return Err(anyhow::Error::msg("User already exists!"))
+ if !items.is_empty() {
+ return Err(anyhow::Error::msg("User already exists!"));
}
sqlx::query(r#"INSERT INTO "accounts" ("user", "password") VALUES (?, ?) "#)
@@ -265,12 +254,12 @@ async fn cmd_add_user(matches: &ArgMatches<'_>, cfg: Config) -> Result<()>{
Ok(())
}
-async fn async_main(arg_matches: ArgMatches<'_>, cfg: Config) -> Result<i32>{
+async fn async_main(arg_matches: ArgMatches<'_>, cfg: Config) -> Result<i32> {
match arg_matches.subcommand() {
("authenticate-cookie", Some(matches)) => {
if let Ok(should_pass) = cmd_authenticate_cookie(matches, cfg).await {
if should_pass {
- return Ok(1)
+ return Ok(1);
}
}
}
@@ -292,12 +281,10 @@ async fn async_main(arg_matches: ArgMatches<'_>, cfg: Config) -> Result<i32>{
Ok(0)
}
-fn main() -> Result<()>{
-
+fn main() -> Result<()> {
simple_logging::log_to_file("/tmp/auth.log", log::LevelFilter::Debug)?;
- log::debug!("{}", env::args().collect::<Vec<String>>()
- .join(" "));
+ log::debug!("{}", env::args().collect::<Vec<String>>().join(" "));
// Sub-arguments for each command, see cgi defines.
let sub_args = &[
@@ -337,7 +324,6 @@ fn main() -> Result<()>{
.about("Add user to database")
.arg(Arg::with_name("user").required(true))
.arg(Arg::with_name("password").required(true)),
-
)
.get_matches();
@@ -354,4 +340,4 @@ fn main() -> Result<()>{
}
Ok(())
-} \ No newline at end of file
+}