Skip to content

Commit

Permalink
Merge pull request #224 from SamTV12345/improve/errors
Browse files Browse the repository at this point in the history
Improve/errors
  • Loading branch information
SamTV12345 authored Jul 15, 2023
2 parents 4212eed + bf33da1 commit cb9cfc5
Show file tree
Hide file tree
Showing 52 changed files with 1,429 additions and 1,385 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ sysinfo = {version = "0.29.4", features = ["serde"]}
fs_extra = "1.3.0"
serde_json = "1.0.100"
dotenv = "0.15.0"
thiserror = "1.0.40"
sha1 = "0.10.5"
sha256 = "1.1.3"
deunicode = "1.3.3"
Expand Down
9 changes: 5 additions & 4 deletions src/auth_middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,9 @@ impl<S, B> AuthFilterMiddleware<S> where B: 'static + MessageBody, S: 'static +
Ok(auth) => {
let (username, password) = AuthFilter::extract_basic_auth(auth);
let res = req.app_data::<web::Data<DbPool>>().unwrap();
let found_user = User::find_by_username(username.as_str(), &mut *res.get().unwrap());
if found_user.is_none() {
let found_user = User::find_by_username(username.as_str(), &mut *res.get().unwrap
());
if found_user.is_err() {
return Box::pin(ok(req.error_response(ErrorUnauthorized("Unauthorized"))
.map_into_right_body()))
}
Expand Down Expand Up @@ -209,7 +210,7 @@ impl<S, B> AuthFilterMiddleware<S> where B: 'static + MessageBody, S: 'static +
let service = Rc::clone(&self.service);

match found_user {
Some(user) => {
Ok(user) => {
req.extensions_mut().insert(user);
async move {
service
Expand All @@ -219,7 +220,7 @@ impl<S, B> AuthFilterMiddleware<S> where B: 'static + MessageBody, S: 'static +
}
.boxed_local()
},
None => {
Err(_) => {
// User is authenticated so we can onboard him if he is new
let user = User::insert_user(&mut User {
id: 0,
Expand Down
39 changes: 19 additions & 20 deletions src/command_line_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::service::podcast_episode_service::PodcastEpisodeService;
use crate::service::rust_service::PodcastService;
use crate::models::podcast_history_item::PodcastHistoryItem;
use crate::models::podcasts::Podcast;
use crate::utils::error::CustomError;


pub fn start_command_line(mut args: Args){
Expand Down Expand Up @@ -47,11 +48,11 @@ pub fn start_command_line(mut args: Args){
let replaced_feed = rss_feed.replace("'", "").replace(" ","");
println!("Refreshing podcast {}", replaced_feed);

let podcast = Podcast::get_podcast_by_rss_feed(replaced_feed, conn);
let podcast = Podcast::get_podcast_by_rss_feed(replaced_feed, conn).expect("Error getting podcast");

let mut podcast_episode_service = PodcastEpisodeService::new();
podcast_episode_service.insert_podcast_episodes(conn, podcast.clone());
podcast_service.schedule_episode_download( podcast,None, conn);
podcast_episode_service.insert_podcast_episodes(conn, podcast.clone()).unwrap();
podcast_service.schedule_episode_download( podcast,None, conn).unwrap();

}
"refresh-all"=> {
Expand All @@ -62,8 +63,9 @@ pub fn start_command_line(mut args: Args){
println!("Refreshing podcast {}", podcast.name);

let mut podcast_episode_service = PodcastEpisodeService::new();
podcast_episode_service.insert_podcast_episodes(&mut establish_connection(), podcast.clone());
podcast_service.schedule_episode_download( podcast,None, conn);
podcast_episode_service.insert_podcast_episodes(&mut establish_connection
(), podcast.clone()).unwrap();
podcast_service.schedule_episode_download( podcast,None, conn).unwrap();
}
}
"list"=>{
Expand Down Expand Up @@ -96,7 +98,7 @@ pub fn start_command_line(mut args: Args){
println!("User management");
match args.nth(0).unwrap().as_str() {
"add"=> {
let mut user = read_user_account();
let mut user = read_user_account().unwrap();


println!("Should a user with the following settings be applied {:?}",user);
Expand Down Expand Up @@ -163,14 +165,10 @@ pub fn start_command_line(mut args: Args){
&mut username);
username = trim_string(username);
println!(">{}<", username);
match User::find_by_username(username.as_str(), &mut establish_connection()){
Some(user)=>{
do_user_update(user)
},
None=>{
println!("Username not found")
}
}
let user = User::find_by_username(username.as_str(), &mut
establish_connection()).unwrap();

do_user_update(user)

}
"list"=> {
Expand Down Expand Up @@ -211,7 +209,7 @@ fn list_users() -> Vec<UserWithoutPassword> {
}


pub fn read_user_account()->User{
pub fn read_user_account()->Result<User, CustomError>{
let mut username = String::new();
let password;

Expand All @@ -220,11 +218,12 @@ pub fn read_user_account()->User{
}).join(", ");
retry_read("Enter your username: ", &mut username);

let user_exists = User::find_by_username(&username, &mut establish_connection()).is_some();
if user_exists{
println!("User already exists");
exit(1);
let user = User::find_by_username(&username, &mut establish_connection());

if user.is_err() {
println!("User does not exist");
}

password = retry_read_secret("Enter your password: ");
let assigned_role = retry_read_role(&format!("Select your role {}",&role));

Expand All @@ -237,7 +236,7 @@ pub fn read_user_account()->User{
created_at: get_current_timestamp_str(),
};

user
Ok(user)
}

pub fn retry_read(prompt: &str, input: &mut String){
Expand Down
2 changes: 0 additions & 2 deletions src/constants/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ pub struct PartialSettings {
pub podcast_prefill: i32,
}

pub const ERROR_LOGIN_MESSAGE: &str = "User either not found or password is incorrect";

pub const TELEGRAM_BOT_TOKEN: &str = "TELEGRAM_BOT_TOKEN";
pub const TELEGRAM_BOT_CHAT_ID: &str = "TELEGRAM_BOT_CHAT_ID";
pub const TELEGRAM_API_ENABLED: &str = "TELEGRAM_API_ENABLED";
Expand Down
17 changes: 9 additions & 8 deletions src/controllers/notification_controller.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use actix_web::web::Data;
use actix_web::{get, put, web, HttpResponse, Responder};
use actix_web::{get, put, web, HttpResponse};
use std::sync::Mutex;
use crate::{DbPool};

use crate::mutex::LockResultExt;
use crate::service::notification_service::NotificationService;
use crate::utils::error::CustomError;

#[utoipa::path(
context_path="/api/v1",
Expand All @@ -13,11 +15,11 @@ tag="notifications"
)]
#[get("/notifications/unread")]
pub async fn get_unread_notifications(notification_service: Data<Mutex<NotificationService>>, conn: Data<DbPool> ) ->
impl Responder {
Result<HttpResponse, CustomError> {
let notifications = notification_service
.lock().ignore_poison()
.get_unread_notifications(&mut conn.get().unwrap());
HttpResponse::Ok().json(notifications.unwrap())
.get_unread_notifications(&mut conn.get().unwrap())?;
Ok(HttpResponse::Ok().json(notifications))
}

#[derive(Deserialize)]
Expand All @@ -35,11 +37,10 @@ tag="notifications"
pub async fn dismiss_notifications(
id: web::Json<NotificationId>,
notification_service: Data<Mutex<NotificationService>>, conn: Data<DbPool>
) -> impl Responder {
) -> Result<HttpResponse,CustomError> {
notification_service.lock()
.ignore_poison()
.update_status_of_notification(id.id, "dismissed",
&mut conn.get().unwrap())
.expect("Error dismissing notification");
HttpResponse::Ok()
&mut conn.get().unwrap())?;
Ok(HttpResponse::Ok().body(""))
}
Loading

0 comments on commit cb9cfc5

Please sign in to comment.