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

View File

@ -1,6 +1,5 @@
use build_html::Html;
use bytes::Buf;
use cookie::time::error::Format;
use file_service::WriteFileError;
use futures_util::StreamExt;
use http::{Error, StatusCode};
@ -80,25 +79,22 @@ pub async fn handle_auth(
form: HashMap<String, String>,
) -> Result<http::Response<String>, Error> {
match form.get("token") {
Some(token) => match app
.authenticate(AuthToken::from(AuthToken::from(token.clone())))
.await
{
Some(token) => match app.authenticate(AuthToken::from(token.clone())).await {
Ok(Some(session_token)) => Response::builder()
.header("location", "/")
.header(
"set-cookie",
format!(
"session={}; Secure; HttpOnly; SameSite=Strict",
session_token.to_string()
*session_token
),
)
.status(StatusCode::SEE_OTHER)
.body("".to_owned()),
Ok(None) => render_auth_page(Some(format!("no user found"))),
Err(_) => render_auth_page(Some(format!("invalid auth token"))),
Ok(None) => render_auth_page(Some("no user found".to_owned())),
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 {
let encoding = match self.encoding {
Some(ref encoding) => format!("enctype=\"{encoding}\"", encoding = encoding),
None => format!(""),
None => "".to_owned(),
};
format!(
"<form action=\"{path}\" method=\"{method}\" {encoding}>\n{elements}\n</form>\n",
@ -108,10 +108,12 @@ impl Input {
self
}
/*
pub fn with_content(mut self, val: &str) -> Self {
self.content = Some(val.to_owned());
self
}
*/
}
#[derive(Clone, Debug)]

View File

@ -1,23 +1,16 @@
#[macro_use]
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 futures_util::StreamExt;
use handlers::{file, handle_auth, handle_upload, thumbnail};
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
io::Read,
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
sync::Arc,
};
use tokio::sync::RwLock;
use warp::{filters::multipart::Part, Filter, Rejection};
use warp::{Filter, Rejection};
mod handlers;
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> {
cookies
.get("session")
.cloned()
.and_then(|session| Some(SessionToken::from(session)))
cookies.get("session").cloned().map(SessionToken::from)
}
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)?,
id: path
.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)?,
extension: path
.extension()
@ -146,7 +146,7 @@ impl FileHandle {
};
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 })
}
@ -168,7 +168,7 @@ impl FileHandle {
self.info.hash = self.hash_content(&content).as_string();
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()?;
@ -188,9 +188,9 @@ impl FileHandle {
}
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);
tn.save(&self.path.thumbnail_path())?;
tn.save(self.path.thumbnail_path())?;
Ok(())
}
@ -203,7 +203,7 @@ impl FileHandle {
fn load_content(path: &Path) -> Result<Vec<u8>, ReadFileError> {
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)?;
Ok(buf)
}

View File

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

View File

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