errors: use anyhow::Context everywhere

This commit is contained in:
Valentin Tolmer 2021-08-26 21:56:42 +02:00 committed by nitnelave
parent a08b9a556d
commit 83ed58bff2
5 changed files with 23 additions and 27 deletions

View File

@ -1,5 +1,5 @@
use crate::cookies::set_cookie; use crate::cookies::set_cookie;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Context, Result};
use lldap_model::*; use lldap_model::*;
use yew::callback::Callback; use yew::callback::Callback;
@ -33,7 +33,7 @@ where
Callback::once(move |response: Response<Result<Resp>>| { Callback::once(move |response: Response<Result<Resp>>| {
let (meta, maybe_data) = response.into_parts(); let (meta, maybe_data) = response.into_parts();
let message = maybe_data let message = maybe_data
.map_err(|e| anyhow!("Could not reach server: {}", e)) .context("Could not reach server")
.and_then(|data| handler(meta.status, data)); .and_then(|data| handler(meta.status, data));
callback.emit(message) callback.emit(message)
}) })
@ -100,7 +100,7 @@ where
callback, callback,
move |status: http::StatusCode, data: String| { move |status: http::StatusCode, data: String| {
if status.is_success() { if status.is_success() {
serde_json::from_str(&data).map_err(|e| anyhow!("Could not parse response: {}", e)) serde_json::from_str(&data).context("Could not parse response")
} else { } else {
Err(anyhow!("{}[{}]: {}", error_message, status, data)) Err(anyhow!("{}[{}]: {}", error_message, status, data))
} }
@ -148,7 +148,7 @@ impl HostService {
|status, data: String| { |status, data: String| {
if status.is_success() { if status.is_success() {
get_claims_from_jwt(&data) get_claims_from_jwt(&data)
.map_err(|e| anyhow!("Could not parse response: {}", e)) .context("Could not parse response")
.and_then(|jwt_claims| { .and_then(|jwt_claims| {
let is_admin = jwt_claims.groups.contains("lldap_admin"); let is_admin = jwt_claims.groups.contains("lldap_admin");
set_cookie("user_id", &jwt_claims.user, &jwt_claims.exp) set_cookie("user_id", &jwt_claims.user, &jwt_claims.exp)
@ -156,7 +156,7 @@ impl HostService {
set_cookie("is_admin", &is_admin.to_string(), &jwt_claims.exp) set_cookie("is_admin", &is_admin.to_string(), &jwt_claims.exp)
}) })
.map(|_| (jwt_claims.user.clone(), is_admin)) .map(|_| (jwt_claims.user.clone(), is_admin))
.map_err(|e| anyhow!("Error clearing cookie: {}", e)) .context("Error clearing cookie")
}) })
} else { } else {
Err(anyhow!( Err(anyhow!(

View File

@ -1,5 +1,5 @@
use crate::api::HostService; use crate::api::HostService;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Context, Result};
use lldap_model::*; use lldap_model::*;
use yew::prelude::*; use yew::prelude::*;
use yew::services::{fetch::FetchTask, ConsoleService}; use yew::services::{fetch::FetchTask, ConsoleService};
@ -48,7 +48,7 @@ impl CreateUserForm {
}; };
self._task = Some( self._task = Some(
HostService::create_user(req, self.link.callback(Msg::CreateUserResponse)) HostService::create_user(req, self.link.callback(Msg::CreateUserResponse))
.map_err(|e| anyhow!("Error trying to create user: {}", e))?, .context("Error trying to create user")?,
); );
} }
Msg::CreateUserResponse(r) => { Msg::CreateUserResponse(r) => {
@ -73,7 +73,7 @@ impl CreateUserForm {
req, req,
self.link.callback(Msg::RegistrationStartResponse), self.link.callback(Msg::RegistrationStartResponse),
) )
.map_err(|e| anyhow!("Error trying to create user: {}", e))?, .context("Error trying to create user")?,
); );
} else { } else {
self.update(Msg::SuccessfulCreation); self.update(Msg::SuccessfulCreation);
@ -97,7 +97,7 @@ impl CreateUserForm {
req, req,
self.link.callback(Msg::RegistrationFinishResponse), self.link.callback(Msg::RegistrationFinishResponse),
) )
.map_err(|e| anyhow!("Error trying to register user: {}", e))?, .context("Error trying to register user")?,
); );
} }
Msg::RegistrationFinishResponse(response) => { Msg::RegistrationFinishResponse(response) => {

View File

@ -1,5 +1,5 @@
use crate::api::HostService; use crate::api::HostService;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Context, Result};
use lldap_model::*; use lldap_model::*;
use wasm_bindgen::JsCast; use wasm_bindgen::JsCast;
use yew::prelude::*; use yew::prelude::*;
@ -61,9 +61,8 @@ impl LoginForm {
let password = get_form_field("password") let password = get_form_field("password")
.ok_or_else(|| anyhow!("Could not get password from form"))?; .ok_or_else(|| anyhow!("Could not get password from form"))?;
let mut rng = rand::rngs::OsRng; let mut rng = rand::rngs::OsRng;
let login_start_request = let login_start_request = opaque::client::login::start_login(&password, &mut rng)
opaque::client::login::start_login(&password, &mut rng) .context("Could not initialize login")?;
.map_err(|e| anyhow!("Could not initialize login: {}", e))?;
self.login_start = Some(login_start_request.state); self.login_start = Some(login_start_request.state);
let req = login::ClientLoginStartRequest { let req = login::ClientLoginStartRequest {
username, username,

View File

@ -1,4 +1,4 @@
use anyhow::{anyhow, Result}; use anyhow::{Context, Result};
use figment::{ use figment::{
providers::{Env, Format, Serialized, Toml}, providers::{Env, Format, Serialized, Toml},
Figment, Figment,
@ -93,19 +93,16 @@ fn get_server_setup(file_path: &str) -> Result<ServerSetup> {
use std::path::Path; use std::path::Path;
let path = Path::new(file_path); let path = Path::new(file_path);
if path.exists() { if path.exists() {
let bytes = std::fs::read(file_path) let bytes =
.map_err(|e| anyhow!("Could not read key file `{}`: {}", file_path, e))?; std::fs::read(file_path).context(format!("Could not read key file `{}`", file_path))?;
Ok(ServerSetup::deserialize(&bytes)?) Ok(ServerSetup::deserialize(&bytes)?)
} else { } else {
let mut rng = rand::rngs::OsRng; let mut rng = rand::rngs::OsRng;
let server_setup = ServerSetup::new(&mut rng); let server_setup = ServerSetup::new(&mut rng);
std::fs::write(path, server_setup.serialize()).map_err(|e| { std::fs::write(path, server_setup.serialize()).context(format!(
anyhow!( "Could not write the generated server setup to file `{}`",
"Could not write the generated server setup to file `{}`: {}", file_path,
file_path, ))?;
e
)
})?;
Ok(server_setup) Ok(server_setup)
} }
} }

View File

@ -9,7 +9,7 @@ use crate::{
infra::{cli::*, configuration::Configuration, db_cleaner::Scheduler}, infra::{cli::*, configuration::Configuration, db_cleaner::Scheduler},
}; };
use actix::Actor; use actix::Actor;
use anyhow::{anyhow, Result}; use anyhow::{Context, Result};
use futures_util::TryFutureExt; use futures_util::TryFutureExt;
use log::*; use log::*;
@ -24,20 +24,20 @@ async fn create_admin_user(handler: &SqlBackendHandler, config: &Configuration)
}) })
.and_then(|_| register_password(handler, &config.ldap_user_dn, &config.ldap_user_pass)) .and_then(|_| register_password(handler, &config.ldap_user_dn, &config.ldap_user_pass))
.await .await
.map_err(|e| anyhow!("Error creating admin user: {}", e))?; .context("Error creating admin user")?;
let admin_group_id = handler let admin_group_id = handler
.create_group(lldap_model::CreateGroupRequest { .create_group(lldap_model::CreateGroupRequest {
display_name: "lldap_admin".to_string(), display_name: "lldap_admin".to_string(),
}) })
.await .await
.map_err(|e| anyhow!("Error creating admin group: {}", e))?; .context("Error creating admin group")?;
handler handler
.add_user_to_group(lldap_model::AddUserToGroupRequest { .add_user_to_group(lldap_model::AddUserToGroupRequest {
user_id: config.ldap_user_dn.clone(), user_id: config.ldap_user_dn.clone(),
group_id: admin_group_id, group_id: admin_group_id,
}) })
.await .await
.map_err(|e| anyhow!("Error adding admin user to group: {}", e)) .context("Error adding admin user to group")
} }
async fn run_server(config: Configuration) -> Result<()> { async fn run_server(config: Configuration) -> Result<()> {