refactor: apply clippy recommendations

This commit is contained in:
Matthieu Bessat 2024-11-12 14:29:27 +01:00
parent 7a06c33b99
commit fbbe6719b6
10 changed files with 20 additions and 25 deletions

View file

@ -208,12 +208,9 @@ pub async fn perform_authorize(
.bind(authorization.created_at.to_rfc3339_opts(SecondsFormat::Millis, true)) .bind(authorization.created_at.to_rfc3339_opts(SecondsFormat::Millis, true))
.execute(&app_state.db) .execute(&app_state.db)
.await; .await;
match res { if let Err(err) = res {
Err(err) => {
error!("Failed to save authorization in DB. {}", err); error!("Failed to save authorization in DB. {}", err);
return (StatusCode::INTERNAL_SERVER_ERROR, Html("Internal server error: Failed to process authorization form.")).into_response(); return (StatusCode::INTERNAL_SERVER_ERROR, Html("Internal server error: Failed to process authorization form.")).into_response();
},
_ => {}
} }
info!("Created authorization {}", &authorization.id); info!("Created authorization {}", &authorization.id);

View file

@ -98,7 +98,7 @@ pub async fn perform_login(
headers.insert("Set-Cookie", HeaderValue::from_str(&jwt_cookie).unwrap()); headers.insert("Set-Cookie", HeaderValue::from_str(&jwt_cookie).unwrap());
// TODO: check redirection for arbitrary URL, enforce relative path // TODO: check redirection for arbitrary URL, enforce relative path
headers.insert("Location", HeaderValue::from_str( headers.insert("Location", HeaderValue::from_str(
&query_params.redirect_to.unwrap_or(format!("/me")) &query_params.redirect_to.unwrap_or("/me".to_string())
).unwrap()); ).unwrap());
( (

View file

@ -1,4 +1,4 @@
use anyhow::{anyhow, Context, Result}; use anyhow::{Context, Result};
use sqlx::{sqlite::{SqliteConnectOptions, SqlitePoolOptions}, Pool, Sqlite, ConnectOptions}; use sqlx::{sqlite::{SqliteConnectOptions, SqlitePoolOptions}, Pool, Sqlite, ConnectOptions};
use std::str::FromStr; use std::str::FromStr;

View file

@ -17,9 +17,9 @@ use log::info;
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
use models::config::{AppSecrets, Config}; use models::config::{AppSecrets, Config};
pub const DEFAULT_DB_PATH: &'static str = &"/var/lib/autotasker/autotasker.db"; pub const DEFAULT_DB_PATH: &str = "/var/lib/autotasker/autotasker.db";
pub const DEFAULT_ASSETS_PATH: &'static str = &"/usr/local/lib/autotasker/assets"; pub const DEFAULT_ASSETS_PATH: &str = "/usr/local/lib/autotasker/assets";
pub const DEFAULT_CONFIG_PATH: &'static str = &"/etc/autotasker/config.yaml"; pub const DEFAULT_CONFIG_PATH: &str = "/etc/autotasker/config.yaml";
fn get_config(path: String) -> Result<Config> { fn get_config(path: String) -> Result<Config> {
let inp_def_yaml = fs::read_to_string(path) let inp_def_yaml = fs::read_to_string(path)
@ -45,7 +45,7 @@ async fn get_app_context(start_app_config: StartAppConfig) -> Result<(Config, Ap
let database_path = &start_app_config.database_path.unwrap_or(DEFAULT_DB_PATH.to_string()); let database_path = &start_app_config.database_path.unwrap_or(DEFAULT_DB_PATH.to_string());
info!("Using database file at {}", database_path); info!("Using database file at {}", database_path);
let pool = prepare_database(&database_path).await.context("Could not prepare db.")?; let pool = prepare_database(database_path).await.context("Could not prepare db.")?;
let config_path = start_app_config.config_path.unwrap_or(DEFAULT_CONFIG_PATH.to_string()); let config_path = start_app_config.config_path.unwrap_or(DEFAULT_CONFIG_PATH.to_string());
info!("Using config file at {}", &config_path); info!("Using config file at {}", &config_path);

View file

@ -99,7 +99,7 @@ pub async fn enforce_jwt_auth_middleware(
); );
} }
}; };
let token_claims: AppUserTokenClaims = match verify_token(&app_state.secrets, &jwt) { let token_claims: AppUserTokenClaims = match verify_token(&app_state.secrets, jwt) {
Ok(val) => val, Ok(val) => val,
Err(_e) => { Err(_e) => {
return Err( return Err(

View file

@ -1,6 +1,5 @@
use std::collections::HashMap;
use axum::{extract::{OriginalUri, Query, Request, State}, http::{HeaderMap, HeaderValue, StatusCode}, middleware::Next, response::{Html, IntoResponse, Redirect, Response}, Extension}; use axum::{extract::{OriginalUri, Request, State}, http::StatusCode, middleware::Next, response::{Html, IntoResponse, Redirect, Response}, Extension};
use axum_extra::extract::CookieJar; use axum_extra::extract::CookieJar;
use crate::{ use crate::{
@ -24,7 +23,7 @@ pub async fn auth_middleware(
return Ok(next.run(req).await) return Ok(next.run(req).await)
} }
}; };
let token_claims: UserTokenClaims = match verify_token(&app_state.secrets, &jwt) { let token_claims: UserTokenClaims = match verify_token(&app_state.secrets, jwt) {
Ok(val) => val, Ok(val) => val,
Err(_e) => { Err(_e) => {
return Err( return Err(

View file

@ -39,7 +39,7 @@ impl TemplateRenderer {
return res return res
} }
*res.status_mut() = status; *res.status_mut() = status;
return res; res
} }
} }

View file

@ -6,7 +6,7 @@ use crate::models::{authorization::AuthorizationScope, config::Application};
pub fn verify_redirect_uri(app: &Application, input_redirect_uri: &str) -> bool { pub fn verify_redirect_uri(app: &Application, input_redirect_uri: &str) -> bool {
app.allowed_redirect_uris app.allowed_redirect_uris
.iter() .iter()
.find(|uri| **uri == input_redirect_uri).is_some() .any(|uri| *uri == input_redirect_uri)
} }
pub fn parse_scope(scope_str: &str) -> Result<Vec<AuthorizationScope>> { pub fn parse_scope(scope_str: &str) -> Result<Vec<AuthorizationScope>> {

View file

@ -1,6 +1,5 @@
use fully_pub::fully_pub;
use anyhow::Result; use anyhow::Result;
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey}; use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
use crate::models::config::AppSecrets; use crate::models::config::AppSecrets;
@ -10,16 +9,16 @@ pub fn create_token<T: Serialize>(secrets: &AppSecrets, claims: T) -> String {
let token = encode( let token = encode(
&Header::default(), &Header::default(),
&claims, &claims,
&EncodingKey::from_secret(&secrets.jwt_secret.as_bytes()) &EncodingKey::from_secret(secrets.jwt_secret.as_bytes())
).expect("Create token"); ).expect("Create token");
return token; token
} }
pub fn verify_token<T: DeserializeOwned>(secrets: &AppSecrets, jwt: &str) -> Result<T> { pub fn verify_token<T: DeserializeOwned>(secrets: &AppSecrets, jwt: &str) -> Result<T> {
let token_data = decode::<T>( let token_data = decode::<T>(
&jwt, jwt,
&DecodingKey::from_secret(&secrets.jwt_secret.as_bytes()), &DecodingKey::from_secret(secrets.jwt_secret.as_bytes()),
&Validation::new(Algorithm::HS256) &Validation::new(Algorithm::HS256)
)?; )?;

View file

@ -56,7 +56,7 @@ pub fn parse_basic_auth(header_value: &str) -> Result<(String, String)> {
let components: Vec<&str> = basic_auth_str.split(':').collect(); let components: Vec<&str> = basic_auth_str.split(':').collect();
Ok(( Ok((
components.get(0).ok_or(anyhow!("Expected username in encoded Authorization header value."))?.to_string(), components.first().ok_or(anyhow!("Expected username in encoded Authorization header value."))?.to_string(),
components.get(1).ok_or(anyhow!("Expected password in encoded Authorization header value."))?.to_string() components.get(1).ok_or(anyhow!("Expected password in encoded Authorization header value."))?.to_string()
)) ))