Skip to content

Upgrade the third-party library version and fix unit test error #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,383 changes: 1,478 additions & 1,905 deletions Cargo.lock

Large diffs are not rendered by default.

46 changes: 26 additions & 20 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,48 @@
name = "rust_actix_example"
version = "0.1.0"
authors = ["David DiMaria <[email protected]>"]
edition = "2018"
edition = "2021"
rust-version = "1.68"

[dependencies]
actix = "0.9.0"
actix-cors = "0.2.0"
actix-files = "0.2.1"
actix-identity = "0.2.1"
actix-redis = "0.8.0"
actix-rt = "1"
actix-service = "1.0.5"
actix-web = "2"
actix-web = "4.3.1"
actix-rt = "2.8.0"
actix-service = "2.0.2"
actix-cors = "0.6.4"
actix = "0.13.1"
actix-files = "0.6.2"
actix-identity = "0.6.0"
actix-session = {version = "0.8", features = ["cookie-session"] }
actix-redis = "0.13"
argon2rs = "0.2.1"

chrono = { version = "0.4", features = ["serde"] }
derive_more = "0.15"
diesel = { version = "1.4.0", features = ["chrono", "mysql", "postgres", "sqlite", "r2d2", "uuidv07"] }
dotenv = "0.14"
derive_more = "0.99"
diesel = { version = "2.1", features = ["chrono", "mysql", "postgres", "sqlite", "r2d2", "uuid"] }
dotenv = "0.15"
envy = "0.4"
env_logger = "0.6"
env_logger = "0.10"
futures = "0.3.1"
jsonwebtoken = "7"
jsonwebtoken = "9"
lazy_static = "1.4"
listenfd = "0.3"
listenfd = "1"
log = "0.4"
once_cell = "1"
rayon = "1.0"
redis-async = "0.6.1"
redis-async = "0.16"
r2d2 = "0.8"
r2d2-diesel = "1.0.0"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
uuid = { version = "0.7", features = ["serde", "v4"] }
validator = "0.8.0"
validator_derive = "0.8.0"
uuid = { version = "1", features = ["serde", "v4"] }
validator = "0.16.0"
validator_derive = "0.16.0"

rust-argon2 = "2"

[dev-dependencies]
actix-http-test = "0.2.0"
actix-http-test = "3.1"

[features]
cockroach = []
Expand Down
29 changes: 14 additions & 15 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::config::CONFIG;
use crate::errors::ApiError;
use actix_identity::{CookieIdentityPolicy, IdentityService};
use argon2rs::argon2i_simple;
use chrono::{Duration, Utc};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
Expand All @@ -25,7 +24,7 @@ impl PrivateClaim {

/// Create a json web token (JWT)
pub fn create_jwt(private_claim: PrivateClaim) -> Result<String, ApiError> {
let encoding_key = EncodingKey::from_secret(&CONFIG.jwt_key.as_ref());
let encoding_key = EncodingKey::from_secret(CONFIG.jwt_key.as_ref());
encode(
&Header::default(),
&private_claim,
Expand All @@ -35,8 +34,8 @@ pub fn create_jwt(private_claim: PrivateClaim) -> Result<String, ApiError> {
}

/// Decode a json web token (JWT)
pub fn decode_jwt(token: &str) -> Result<PrivateClaim, ApiError> {
let decoding_key = DecodingKey::from_secret(&CONFIG.jwt_key.as_ref());
pub fn _decode_jwt(token: &str) -> Result<PrivateClaim, ApiError> {
let decoding_key = DecodingKey::from_secret(CONFIG.jwt_key.as_ref());
decode::<PrivateClaim>(token, &decoding_key, &Validation::default())
.map(|data| data.claims)
.map_err(|e| ApiError::CannotDecodeJwtToken(e.to_string()))
Expand All @@ -47,21 +46,21 @@ pub fn decode_jwt(token: &str) -> Result<PrivateClaim, ApiError> {
/// Uses the argon2i algorithm.
/// auth_salt is environment-configured.
pub fn hash(password: &str) -> String {
argon2i_simple(&password, &CONFIG.auth_salt)
argon2i_simple(password, &CONFIG.auth_salt)
.iter()
.map(|b| format!("{:02x}", b))
.collect()
}

/// Gets the identidy service for injection into an Actix app
pub fn get_identity_service() -> IdentityService<CookieIdentityPolicy> {
IdentityService::new(
CookieIdentityPolicy::new(&CONFIG.session_key.as_ref())
.name(&CONFIG.session_name)
.max_age_time(chrono::Duration::minutes(CONFIG.session_timeout))
.secure(CONFIG.session_secure),
)
}
// / Gets the identidy service for injection into an Actix app
// pub fn get_identity_service() -> IdentityService<CookieIdentityPolicy> {
// IdentityService::new(
// CookieIdentityPolicy::new(&CONFIG.session_key.as_ref())
// .name(&CONFIG.session_name)
// .max_age_time(chrono::Duration::minutes(CONFIG.session_timeout))
// .secure(CONFIG.session_secure),
// )
// }

#[cfg(test)]
pub mod tests {
Expand Down Expand Up @@ -94,7 +93,7 @@ pub mod tests {
fn it_decodes_a_jwt() {
let private_claim = PrivateClaim::new(Uuid::new_v4(), EMAIL.into());
let jwt = create_jwt(private_claim.clone()).unwrap();
let decoded = decode_jwt(&jwt).unwrap();
let decoded = _decode_jwt(&jwt).unwrap();
assert_eq!(private_claim, decoded);
}
}
8 changes: 4 additions & 4 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub type Cache = Data<Addr<RedisActor>>;

/// Retrieve an entry in redis
#[allow(dead_code)]
pub async fn get<'a>(redis: Cache, key: &'a str) -> Result<String, ApiError> {
pub async fn get(redis: Cache, key: &str) -> Result<String, ApiError> {
let command = resp_array!["GET", key];
send(redis, command).await
}
Expand All @@ -23,15 +23,15 @@ pub async fn set<'a>(redis: Cache, key: &'a str, value: &'a str) -> Result<Strin

/// Delete an entry in redis
#[allow(dead_code)]
pub async fn delete<'a>(redis: Cache, key: &'a str) -> Result<String, ApiError> {
pub async fn delete(redis: Cache, key: &str) -> Result<String, ApiError> {
let command = resp_array!["DEL", key];
send(redis, command).await
}

/// Send a command to the redis actor
async fn send<'a>(redis: Cache, command: RespValue) -> Result<String, ApiError> {
let error_message = format!("Could not send {:?} command to Redis", command);
let error = ApiError::CacheError(error_message.into());
let error = ApiError::CacheError(error_message);
let response = redis.send(Command(command)).await.map_err(|_| error)?;
match response {
Ok(message) => Ok::<String, _>(FromResp::from_resp(message).unwrap_or("".into())),
Expand All @@ -44,7 +44,7 @@ pub fn add_cache(cfg: &mut ServiceConfig) {
if !&CONFIG.redis_url.is_empty() {
// Start a new supervisor with redis actor
let cache = RedisActor::start(&CONFIG.redis_url);
cfg.data(cache);
cfg.app_data(cache);
}
}

Expand Down
15 changes: 8 additions & 7 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
//! Database-related functions
use crate::config::{Config, CONFIG};
use actix_web::web;
use actix_web::web::{self, Data};
use diesel::{
mysql::MysqlConnection,
pg::PgConnection,
r2d2::{ConnectionManager, PoolError},
sqlite::SqliteConnection,
Connection,
};
use log::info;

#[serde(untagged)]
#[derive(Clone, Deserialize, Debug, PartialEq)]
#[serde(field_identifier, rename_all = "lowercase")]
pub enum DatabaseConnection {
Expand Down Expand Up @@ -65,18 +65,19 @@ impl InferPool {

pub fn init_pool<T>(config: Config) -> Result<Pool<T>, PoolError>
where
T: Connection + 'static,
T: Connection + 'static + diesel::r2d2::R2D2Connection,
{
let manager = ConnectionManager::<T>::new(config.database_url);
Pool::builder().build(manager)
}

pub fn add_pool(cfg: &mut web::ServiceConfig) {
info!("config database pool");
let pool = InferPool::init_pool(CONFIG.clone()).expect("Failed to create connection pool");
match pool {
InferPool::Cockroach(cockroach_pool) => cfg.data(cockroach_pool),
InferPool::Mysql(mysql_pool) => cfg.data(mysql_pool),
InferPool::Postgres(postgres_pool) => cfg.data(postgres_pool),
InferPool::Sqlite(sqlite_pool) => cfg.data(sqlite_pool),
InferPool::Cockroach(cockroach_pool) => cfg.app_data(Data::new(cockroach_pool)),
InferPool::Mysql(mysql_pool) => cfg.app_data(Data::new(mysql_pool)),
InferPool::Postgres(postgres_pool) => cfg.app_data(Data::new(postgres_pool)),
InferPool::Sqlite(sqlite_pool) => cfg.app_data(Data::new(sqlite_pool)),
};
}
29 changes: 16 additions & 13 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use actix_web::{
error::{BlockingError, ResponseError},
http::StatusCode,
HttpResponse,
HttpResponse, Error,
};
use derive_more::Display;
use diesel::{
r2d2::PoolError,
result::{DatabaseErrorKind, Error as DBError},
};
use uuid::parser::ParseError;
use uuid::Error as ParseError;

#[derive(Debug, Display, PartialEq)]
#[allow(dead_code)]
Expand Down Expand Up @@ -38,16 +38,16 @@ impl ResponseError for ApiError {
fn error_response(&self) -> HttpResponse {
match self {
ApiError::BadRequest(error) => {
HttpResponse::BadRequest().json::<ErrorResponse>(error.into())
HttpResponse::BadRequest().json(error)
}
ApiError::NotFound(message) => {
HttpResponse::NotFound().json::<ErrorResponse>(message.into())
HttpResponse::NotFound().json(message)
}
ApiError::ValidationError(errors) => {
HttpResponse::UnprocessableEntity().json::<ErrorResponse>(errors.to_vec().into())
HttpResponse::UnprocessableEntity().json(errors.to_vec())
}
ApiError::Unauthorized(error) => {
HttpResponse::Unauthorized().json::<ErrorResponse>(error.into())
HttpResponse::Unauthorized().json(error)
}
_ => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR),
}
Expand Down Expand Up @@ -102,12 +102,15 @@ impl From<ParseError> for ApiError {
}
}

/// Convert Thread BlockingErrors to ApiErrors
impl From<BlockingError<ApiError>> for ApiError {
fn from(error: BlockingError<ApiError>) -> ApiError {
match error {
BlockingError::Error(api_error) => api_error,
BlockingError::Canceled => ApiError::BlockingError("Thread blocking error".into()),
}
// / Convert Thread BlockingErrors to ApiErrors
impl From<BlockingError> for ApiError {
fn from(error: BlockingError) -> ApiError {
ApiError::InternalServerError(error.to_string())
}
}

impl From<Error> for ApiError{
fn from(value: Error) -> Self {
ApiError::InternalServerError(value.to_string())
}
}
Loading