Skip to content

Commit

Permalink
dev: fix remaning clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
da2ce7 committed May 10, 2023
1 parent 493adbb commit da91f97
Show file tree
Hide file tree
Showing 29 changed files with 118 additions and 68 deletions.
6 changes: 3 additions & 3 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::config::Configuration;
use crate::databases::database::Database;
use crate::errors::ServiceError;
use crate::models::user::{UserClaims, UserCompact};
use crate::utils::clock::current_time;
use crate::utils::clock;

pub struct AuthorizationService {
cfg: Arc<Configuration>,
Expand All @@ -26,7 +26,7 @@ impl AuthorizationService {
// create JWT that expires in two weeks
let key = settings.auth.secret_key.as_bytes();
// TODO: create config option for setting the token validity in seconds
let exp_date = current_time() + 1_209_600; // two weeks from now
let exp_date = clock::now() + 1_209_600; // two weeks from now

let claims = UserClaims { user, exp: exp_date };

Expand All @@ -47,7 +47,7 @@ impl AuthorizationService {
&Validation::new(Algorithm::HS256),
) {
Ok(token_data) => {
if token_data.claims.exp < current_time() {
if token_data.claims.exp < clock::now() {
return Err(ServiceError::TokenExpired);
}
Ok(token_data.claims)
Expand Down
4 changes: 2 additions & 2 deletions src/bin/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
//! It updates the application from version v1.0.0 to v2.0.0.
//! You can execute it with: `cargo run --bin upgrade ./data.db ./data_v2.db ./uploads`

use torrust_index_backend::upgrades::from_v1_0_0_to_v2_0_0::upgrader::run_upgrader;
use torrust_index_backend::upgrades::from_v1_0_0_to_v2_0_0::upgrader::run;

#[actix_web::main]
async fn main() {
run_upgrader().await;
run().await;
}
2 changes: 1 addition & 1 deletion src/console/commands/import_tracker_statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub async fn import(_args: &Arguments) {
let database = Arc::new(
database::connect(&settings.database.connect_url)
.await
.expect("Database error."),
.expect("unable to connect to db"),
);

let tracker_service = Arc::new(Service::new(cfg.clone(), database.clone()).await);
Expand Down
32 changes: 22 additions & 10 deletions src/databases/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,31 +63,43 @@ pub enum Error {
TorrentTitleAlreadyExists,
}

/// Connect to a database.
/// Get the Driver of the Database from the Connection String
///
/// # Errors
///
/// This function will return an `Error::UnrecognizedDatabaseDriver` if unable to match database type.
pub async fn connect(db_path: &str) -> Result<Box<dyn Database>, Error> {
pub fn get_driver(db_path: &str) -> Result<Driver, Error> {
match &db_path.chars().collect::<Vec<char>>() as &[char] {
['s', 'q', 'l', 'i', 't', 'e', ..] => {
let db = Sqlite::new(db_path).await;
Ok(Box::new(db))
}
['m', 'y', 's', 'q', 'l', ..] => {
let db = Mysql::new(db_path).await;
Ok(Box::new(db))
}
['s', 'q', 'l', 'i', 't', 'e', ..] => Ok(Driver::Sqlite3),
['m', 'y', 's', 'q', 'l', ..] => Ok(Driver::Mysql),
_ => Err(Error::UnrecognizedDatabaseDriver),
}
}

/// Connect to a database.
///
/// # Errors
///
/// This function will return an `Error::UnrecognizedDatabaseDriver` if unable to match database type.
pub async fn connect(db_path: &str) -> Result<Box<dyn Database>, Error> {
let db_driver = self::get_driver(db_path)?;

Ok(match db_driver {
self::Driver::Sqlite3 => Box::new(Sqlite::new(db_path).await),
self::Driver::Mysql => Box::new(Mysql::new(db_path).await),
})
}

/// Trait for database implementations.
#[async_trait]
pub trait Database: Sync + Send {
/// Return current database driver.
fn get_database_driver(&self) -> Driver;

async fn new(db_path: &str) -> Self
where
Self: Sized;

/// Add new user and return the newly inserted `user_id`.
async fn insert_user_and_get_id(&self, username: &str, email: &str, password: &str) -> Result<i64, Error>;

Expand Down
24 changes: 11 additions & 13 deletions src/databases/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,20 @@ use crate::models::torrent::TorrentListing;
use crate::models::torrent_file::{DbTorrentAnnounceUrl, DbTorrentFile, DbTorrentInfo, Torrent, TorrentFile};
use crate::models::tracker_key::TrackerKey;
use crate::models::user::{User, UserAuthentication, UserCompact, UserProfile};
use crate::utils::clock::current_time;
use crate::utils::hex::bytes_to_hex;
use crate::utils::clock;
use crate::utils::hex::from_bytes;

pub struct Mysql {
pub pool: MySqlPool,
}

impl Mysql {
pub async fn new(database_url: &str) -> Self {
#[async_trait]
impl Database for Mysql {
fn get_database_driver(&self) -> Driver {
Driver::Mysql
}

async fn new(database_url: &str) -> Self {
let db = MySqlPoolOptions::new()
.connect(database_url)
.await
Expand All @@ -32,13 +37,6 @@ impl Mysql {

Self { pool: db }
}
}

#[async_trait]
impl Database for Mysql {
fn get_database_driver(&self) -> Driver {
Driver::Mysql
}

async fn insert_user_and_get_id(&self, username: &str, email: &str, password_hash: &str) -> Result<i64, database::Error> {
// open pool connection
Expand Down Expand Up @@ -142,7 +140,7 @@ impl Database for Mysql {
async fn get_user_tracker_key(&self, user_id: i64) -> Option<TrackerKey> {
const HOUR_IN_SECONDS: i64 = 3600;

let current_time_plus_hour = i64::try_from(current_time()).unwrap().saturating_add(HOUR_IN_SECONDS);
let current_time_plus_hour = i64::try_from(clock::now()).unwrap().saturating_add(HOUR_IN_SECONDS);

// get tracker key that is valid for at least one hour from now
query_as::<_, TrackerKey>("SELECT tracker_key AS 'key', date_expiry AS valid_until FROM torrust_tracker_keys WHERE user_id = ? AND date_expiry > ? ORDER BY date_expiry DESC")
Expand Down Expand Up @@ -401,7 +399,7 @@ impl Database for Mysql {

// torrent file can only hold a pieces key or a root hash key: http://www.bittorrent.org/beps/bep_0030.html
let (pieces, root_hash): (String, bool) = if let Some(pieces) = &torrent.info.pieces {
(bytes_to_hex(pieces.as_ref()), false)
(from_bytes(pieces.as_ref()), false)
} else {
let root_hash = torrent.info.root_hash.as_ref().ok_or(database::Error::Error)?;
(root_hash.to_string(), true)
Expand Down
24 changes: 11 additions & 13 deletions src/databases/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,20 @@ use crate::models::torrent::TorrentListing;
use crate::models::torrent_file::{DbTorrentAnnounceUrl, DbTorrentFile, DbTorrentInfo, Torrent, TorrentFile};
use crate::models::tracker_key::TrackerKey;
use crate::models::user::{User, UserAuthentication, UserCompact, UserProfile};
use crate::utils::clock::current_time;
use crate::utils::hex::bytes_to_hex;
use crate::utils::clock;
use crate::utils::hex::from_bytes;

pub struct Sqlite {
pub pool: SqlitePool,
}

impl Sqlite {
pub async fn new(database_url: &str) -> Self {
#[async_trait]
impl Database for Sqlite {
fn get_database_driver(&self) -> Driver {
Driver::Sqlite3
}

async fn new(database_url: &str) -> Self {
let db = SqlitePoolOptions::new()
.connect(database_url)
.await
Expand All @@ -32,13 +37,6 @@ impl Sqlite {

Self { pool: db }
}
}

#[async_trait]
impl Database for Sqlite {
fn get_database_driver(&self) -> Driver {
Driver::Sqlite3
}

async fn insert_user_and_get_id(&self, username: &str, email: &str, password_hash: &str) -> Result<i64, database::Error> {
// open pool connection
Expand Down Expand Up @@ -138,7 +136,7 @@ impl Database for Sqlite {
const HOUR_IN_SECONDS: i64 = 3600;

// casting current_time() to i64 will overflow in the year 2262
let current_time_plus_hour = i64::try_from(current_time()).unwrap().saturating_add(HOUR_IN_SECONDS);
let current_time_plus_hour = i64::try_from(clock::now()).unwrap().saturating_add(HOUR_IN_SECONDS);

// get tracker key that is valid for at least one hour from now
query_as::<_, TrackerKey>("SELECT tracker_key AS key, date_expiry AS valid_until FROM torrust_tracker_keys WHERE user_id = $1 AND date_expiry > $2 ORDER BY date_expiry DESC")
Expand Down Expand Up @@ -391,7 +389,7 @@ impl Database for Sqlite {

// torrent file can only hold a pieces key or a root hash key: http://www.bittorrent.org/beps/bep_0030.html
let (pieces, root_hash): (String, bool) = if let Some(pieces) = &torrent.info.pieces {
(bytes_to_hex(pieces.as_ref()), false)
(from_bytes(pieces.as_ref()), false)
} else {
let root_hash = torrent.info.root_hash.as_ref().ok_or(database::Error::Error)?;
(root_hash.to_string(), true)
Expand Down
4 changes: 2 additions & 2 deletions src/mailer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};

use crate::config::Configuration;
use crate::errors::ServiceError;
use crate::utils::clock::current_time;
use crate::utils::clock;

pub struct Service {
cfg: Arc<Configuration>,
Expand Down Expand Up @@ -137,7 +137,7 @@ impl Service {
let claims = VerifyClaims {
iss: String::from("email-verification"),
sub: user_id,
exp: current_time() + 315_569_260, // 10 years from now
exp: clock::now() + 315_569_260, // 10 years from now
};

let token = encode(&Header::default(), &claims, &EncodingKey::from_secret(key)).unwrap();
Expand Down
8 changes: 4 additions & 4 deletions src/models/torrent_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde_bytes::ByteBuf;
use sha1::{Digest, Sha1};

use crate::config::Configuration;
use crate::utils::hex::{bytes_to_hex, hex_to_bytes};
use crate::utils::hex::{from_bytes, into_bytes};

#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
pub struct TorrentNode(String, i64);
Expand Down Expand Up @@ -46,7 +46,7 @@ impl TorrentInfo {
pub fn get_pieces_as_string(&self) -> String {
match &self.pieces {
None => String::new(),
Some(byte_buf) => bytes_to_hex(byte_buf.as_ref()),
Some(byte_buf) => from_bytes(byte_buf.as_ref()),
}
}

Expand Down Expand Up @@ -121,7 +121,7 @@ impl Torrent {
if torrent_info.root_hash > 0 {
info.root_hash = Some(torrent_info.pieces);
} else {
let pieces = hex_to_bytes(&torrent_info.pieces).expect("variable `torrent_info.pieces` is not a valid hex string");
let pieces = into_bytes(&torrent_info.pieces).expect("variable `torrent_info.pieces` is not a valid hex string");
info.pieces = Some(ByteBuf::from(pieces));
}

Expand Down Expand Up @@ -191,7 +191,7 @@ impl Torrent {

#[must_use]
pub fn info_hash(&self) -> String {
bytes_to_hex(&self.calculate_info_hash_as_bytes())
from_bytes(&self.calculate_info_hash_as_bytes())
}

#[must_use]
Expand Down
4 changes: 2 additions & 2 deletions src/routes/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::errors::{ServiceError, ServiceResult};
use crate::mailer::VerifyClaims;
use crate::models::response::{OkResponse, TokenResponse};
use crate::models::user::UserAuthentication;
use crate::utils::clock::current_time;
use crate::utils::clock;
use crate::utils::regex::validate_email_address;

pub fn init(cfg: &mut web::ServiceConfig) {
Expand Down Expand Up @@ -251,7 +251,7 @@ pub async fn renew_token(payload: web::Json<Token>, app_data: WebAppData) -> Ser
let user_compact = app_data.database.get_user_compact_from_id(claims.user.user_id).await?;

// renew token if it is valid for less than one week
let token = match claims.exp - current_time() {
let token = match claims.exp - clock::now() {
x if x < ONE_WEEK_IN_SECONDS => app_data.auth.sign_jwt(user_compact.clone()).await,
_ => payload.token.clone(),
};
Expand Down
2 changes: 2 additions & 0 deletions src/upgrades/from_v1_0_0_to_v2_0_0/databases/sqlite_v1_0_0.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::missing_errors_doc)]

use serde::{Deserialize, Serialize};
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::{query_as, SqlitePool};
Expand Down
3 changes: 3 additions & 0 deletions src/upgrades/from_v1_0_0_to_v2_0_0/databases/sqlite_v2_0_0.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::missing_errors_doc)]

use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::sqlite::{SqlitePoolOptions, SqliteQueryResult};
Expand Down Expand Up @@ -257,6 +259,7 @@ impl SqliteDatabaseV2_0_0 {
.map(|v| v.last_insert_rowid())
}

#[allow(clippy::missing_panics_doc)]
pub async fn delete_all_database_rows(&self) -> Result<(), database::Error> {
query("DELETE FROM torrust_categories").execute(&self.pool).await.unwrap();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::Arc;
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v1_0_0::SqliteDatabaseV1_0_0;
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v2_0_0::{CategoryRecordV2, SqliteDatabaseV2_0_0};

#[allow(clippy::missing_panics_doc)]
pub async fn transfer_categories(source_database: Arc<SqliteDatabaseV1_0_0>, target_database: Arc<SqliteDatabaseV2_0_0>) {
println!("Transferring categories ...");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::missing_errors_doc)]

use std::sync::Arc;
use std::{error, fs};

Expand All @@ -6,6 +8,8 @@ use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v1_0_0::SqliteData
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v2_0_0::{SqliteDatabaseV2_0_0, TorrentRecordV2};
use crate::utils::parse_torrent::decode_torrent;

#[allow(clippy::missing_panics_doc)]
#[allow(clippy::too_many_lines)]
pub async fn transfer_torrents(
source_database: Arc<SqliteDatabaseV1_0_0>,
target_database: Arc<SqliteDatabaseV2_0_0>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::Arc;
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v1_0_0::SqliteDatabaseV1_0_0;
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v2_0_0::SqliteDatabaseV2_0_0;

#[allow(clippy::missing_panics_doc)]
pub async fn transfer_tracker_keys(source_database: Arc<SqliteDatabaseV1_0_0>, target_database: Arc<SqliteDatabaseV2_0_0>) {
println!("Transferring tracker keys ...");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::Arc;
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v1_0_0::SqliteDatabaseV1_0_0;
use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::sqlite_v2_0_0::SqliteDatabaseV2_0_0;

#[allow(clippy::missing_panics_doc)]
pub async fn transfer_users(
source_database: Arc<SqliteDatabaseV1_0_0>,
target_database: Arc<SqliteDatabaseV2_0_0>,
Expand Down
2 changes: 1 addition & 1 deletion src/upgrades/from_v1_0_0_to_v2_0_0/upgrader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ fn parse_args() -> Arguments {
}
}

pub async fn run_upgrader() {
pub async fn run() {
let now = datetime_iso_8601();
upgrade(&parse_args(), &now).await;
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/clock.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#[must_use]
pub fn current_time() -> u64 {
pub fn now() -> u64 {
u64::try_from(chrono::prelude::Utc::now().timestamp()).expect("timestamp should be positive")
}
9 changes: 7 additions & 2 deletions src/utils/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fmt::Write;
use std::num::ParseIntError;

#[must_use]
pub fn bytes_to_hex(bytes: &[u8]) -> String {
pub fn from_bytes(bytes: &[u8]) -> String {
let mut s = String::with_capacity(2 * bytes.len());

for byte in bytes {
Expand All @@ -12,7 +12,12 @@ pub fn bytes_to_hex(bytes: &[u8]) -> String {
s
}

pub fn hex_to_bytes(s: &str) -> Result<Vec<u8>, ParseIntError> {
/// Encodes a String into Hex Bytes
///
/// # Errors
///
/// This function will return an error if unable to encode into Hex
pub fn into_bytes(s: &str) -> Result<Vec<u8>, ParseIntError> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16))
Expand Down
Loading

0 comments on commit da91f97

Please sign in to comment.