Thoroughly lint the file-service

This commit is contained in:
Savanni D'Gerinel 2023-10-04 15:57:18 -04:00
parent 94e74abd1d
commit 2a3611dd46
7 changed files with 25 additions and 44 deletions

View File

@ -26,11 +26,7 @@ pub async fn main() {
Commands::AddUser { username } => { Commands::AddUser { username } => {
match authdb.add_user(Username::from(username.clone())).await { match authdb.add_user(Username::from(username.clone())).await {
Ok(token) => { Ok(token) => {
println!( println!("User {} created. Auth token: {}", username, *token);
"User {} created. Auth token: {}",
username,
token.to_string()
);
} }
Err(err) => { Err(err) => {
println!("Could not create user {}", username); println!("Could not create user {}", username);
@ -38,7 +34,7 @@ pub async fn main() {
} }
} }
} }
Commands::DeleteUser { username } => {} Commands::DeleteUser { .. } => {}
Commands::ListUsers => {} Commands::ListUsers => {}
} }
} }

View File

@ -1,6 +1,5 @@
use build_html::Html; use build_html::Html;
use bytes::Buf; use bytes::Buf;
use cookie::time::error::Format;
use file_service::WriteFileError; use file_service::WriteFileError;
use futures_util::StreamExt; use futures_util::StreamExt;
use http::{Error, StatusCode}; use http::{Error, StatusCode};
@ -80,25 +79,22 @@ pub async fn handle_auth(
form: HashMap<String, String>, form: HashMap<String, String>,
) -> Result<http::Response<String>, Error> { ) -> Result<http::Response<String>, Error> {
match form.get("token") { match form.get("token") {
Some(token) => match app Some(token) => match app.authenticate(AuthToken::from(token.clone())).await {
.authenticate(AuthToken::from(AuthToken::from(token.clone())))
.await
{
Ok(Some(session_token)) => Response::builder() Ok(Some(session_token)) => Response::builder()
.header("location", "/") .header("location", "/")
.header( .header(
"set-cookie", "set-cookie",
format!( format!(
"session={}; Secure; HttpOnly; SameSite=Strict", "session={}; Secure; HttpOnly; SameSite=Strict",
session_token.to_string() *session_token
), ),
) )
.status(StatusCode::SEE_OTHER) .status(StatusCode::SEE_OTHER)
.body("".to_owned()), .body("".to_owned()),
Ok(None) => render_auth_page(Some(format!("no user found"))), Ok(None) => render_auth_page(Some("no user found".to_owned())),
Err(_) => render_auth_page(Some(format!("invalid auth token"))), Err(_) => render_auth_page(Some("invalid auth token".to_owned())),
}, },
None => render_auth_page(Some(format!("no token available"))), None => render_auth_page(Some("no token available".to_owned())),
} }
} }

View File

@ -38,7 +38,7 @@ impl Html for Form {
fn to_html_string(&self) -> String { fn to_html_string(&self) -> String {
let encoding = match self.encoding { let encoding = match self.encoding {
Some(ref encoding) => format!("enctype=\"{encoding}\"", encoding = encoding), Some(ref encoding) => format!("enctype=\"{encoding}\"", encoding = encoding),
None => format!(""), None => "".to_owned(),
}; };
format!( format!(
"<form action=\"{path}\" method=\"{method}\" {encoding}>\n{elements}\n</form>\n", "<form action=\"{path}\" method=\"{method}\" {encoding}>\n{elements}\n</form>\n",
@ -108,10 +108,12 @@ impl Input {
self self
} }
/*
pub fn with_content(mut self, val: &str) -> Self { pub fn with_content(mut self, val: &str) -> Self {
self.content = Some(val.to_owned()); self.content = Some(val.to_owned());
self self
} }
*/
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]

View File

@ -1,23 +1,16 @@
#[macro_use]
extern crate log; extern crate log;
use handlers::{file, handle_auth, handle_upload, thumbnail};
use http::status::StatusCode;
// use mustache::{compile_path, Template};
// use orizentic::{Permissions, ResourceName, Secret};
use bytes::Buf;
use cookie::Cookie; use cookie::Cookie;
use futures_util::StreamExt; use handlers::{file, handle_auth, handle_upload, thumbnail};
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
convert::Infallible, convert::Infallible,
io::Read,
net::{IpAddr, Ipv4Addr, SocketAddr}, net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf, path::PathBuf,
sync::Arc, sync::Arc,
}; };
use tokio::sync::RwLock; use tokio::sync::RwLock;
use warp::{filters::multipart::Part, Filter, Rejection}; use warp::{Filter, Rejection};
mod handlers; mod handlers;
mod html; mod html;
@ -82,10 +75,7 @@ fn parse_cookies(cookie_str: &str) -> Result<HashMap<String, String>, cookie::Pa
} }
fn get_session_token(cookies: HashMap<String, String>) -> Option<SessionToken> { fn get_session_token(cookies: HashMap<String, String>) -> Option<SessionToken> {
cookies cookies.get("session").cloned().map(SessionToken::from)
.get("session")
.cloned()
.and_then(|session| Some(SessionToken::from(session)))
} }
fn maybe_with_session() -> impl Filter<Extract = (Option<SessionToken>,), Error = Rejection> + Copy fn maybe_with_session() -> impl Filter<Extract = (Option<SessionToken>,), Error = Rejection> + Copy

View File

@ -97,7 +97,7 @@ impl TryFrom<&Path> for PathResolver {
.ok_or(PathError::InvalidPath)?, .ok_or(PathError::InvalidPath)?,
id: path id: path
.file_stem() .file_stem()
.and_then(|s| s.to_str().map(|s| FileId::from(s))) .and_then(|s| s.to_str().map(FileId::from))
.ok_or(PathError::InvalidPath)?, .ok_or(PathError::InvalidPath)?,
extension: path extension: path
.extension() .extension()
@ -146,7 +146,7 @@ impl FileHandle {
}; };
let mut md_file = std::fs::File::create(path.metadata_path())?; let mut md_file = std::fs::File::create(path.metadata_path())?;
md_file.write(&serde_json::to_vec(&info)?)?; let _ = md_file.write(&serde_json::to_vec(&info)?)?;
Ok(Self { id, path, info }) Ok(Self { id, path, info })
} }
@ -168,7 +168,7 @@ impl FileHandle {
self.info.hash = self.hash_content(&content).as_string(); self.info.hash = self.hash_content(&content).as_string();
let mut md_file = std::fs::File::create(self.path.metadata_path())?; let mut md_file = std::fs::File::create(self.path.metadata_path())?;
md_file.write(&serde_json::to_vec(&self.info)?)?; let _ = md_file.write(&serde_json::to_vec(&self.info)?)?;
self.write_thumbnail()?; self.write_thumbnail()?;
@ -188,9 +188,9 @@ impl FileHandle {
} }
fn write_thumbnail(&self) -> Result<(), WriteFileError> { fn write_thumbnail(&self) -> Result<(), WriteFileError> {
let img = image::open(&self.path.file_path())?; let img = image::open(self.path.file_path())?;
let tn = img.resize(640, 640, FilterType::Nearest); let tn = img.resize(640, 640, FilterType::Nearest);
tn.save(&self.path.thumbnail_path())?; tn.save(self.path.thumbnail_path())?;
Ok(()) Ok(())
} }
@ -203,7 +203,7 @@ impl FileHandle {
fn load_content(path: &Path) -> Result<Vec<u8>, ReadFileError> { fn load_content(path: &Path) -> Result<Vec<u8>, ReadFileError> {
let mut buf = Vec::new(); let mut buf = Vec::new();
let mut file = std::fs::File::open(&path)?; let mut file = std::fs::File::open(path)?;
file.read_to_end(&mut buf)?; file.read_to_end(&mut buf)?;
Ok(buf) Ok(buf)
} }

View File

@ -3,7 +3,6 @@ use crate::FileId;
use super::{ReadFileError, WriteFileError}; use super::{ReadFileError, WriteFileError};
use chrono::prelude::*; use chrono::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json;
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
path::PathBuf, path::PathBuf,
@ -33,7 +32,7 @@ impl FileInfo {
pub fn save(&self, path: PathBuf) -> Result<(), WriteFileError> { pub fn save(&self, path: PathBuf) -> Result<(), WriteFileError> {
let ser = serde_json::to_string(self).unwrap(); let ser = serde_json::to_string(self).unwrap();
let mut file = std::fs::File::create(path)?; let mut file = std::fs::File::create(path)?;
file.write(ser.as_bytes())?; let _ = file.write(ser.as_bytes())?;
Ok(()) Ok(())
} }
} }

View File

@ -3,12 +3,10 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use sqlx::{ use sqlx::{
sqlite::{SqlitePool, SqliteRow}, sqlite::{SqlitePool, SqliteRow},
Executor, Row, Row,
}; };
use std::collections::HashSet; use std::{collections::HashSet, ops::Deref, path::PathBuf};
use std::{ops::Deref, path::PathBuf, sync::Arc};
use thiserror::Error; use thiserror::Error;
use tokio::sync::RwLock;
use uuid::Uuid; use uuid::Uuid;
mod filehandle; mod filehandle;
@ -288,7 +286,7 @@ impl AuthDB {
return Err(AuthError::DuplicateAuthToken); return Err(AuthError::DuplicateAuthToken);
} }
if results.len() == 0 { if results.is_empty() {
return Ok(None); return Ok(None);
} }
@ -322,7 +320,7 @@ impl AuthDB {
return Err(AuthError::DuplicateSessionToken); return Err(AuthError::DuplicateSessionToken);
} }
if rows.len() == 0 { if rows.is_empty() {
return Ok(None); return Ok(None);
} }
@ -348,7 +346,7 @@ impl Store {
let path_ = path.unwrap().path(); let path_ = path.unwrap().path();
if path_.extension().and_then(|s| s.to_str()) == Some("json") { if path_.extension().and_then(|s| s.to_str()) == Some("json") {
let stem = path_.file_stem().and_then(|s| s.to_str()).unwrap(); let stem = path_.file_stem().and_then(|s| s.to_str()).unwrap();
Some(FileId::from(FileId::from(stem))) Some(FileId::from(stem))
} else { } else {
None None
} }