remove unnecessary context objects

This commit is contained in:
glyph 2022-01-13 13:16:38 +02:00
parent b0b21ad8a0
commit f4ad230d58
5 changed files with 186 additions and 358 deletions

View File

@ -1,14 +1,17 @@
use log::info;
use rocket::form::{Form, FromForm};
use rocket::http::{Cookie, CookieJar, Status};
use rocket::request::{self, FlashMessage, FromRequest, Request};
use rocket::response::{Flash, Redirect};
use rocket::serde::{Deserialize, Serialize};
use rocket::{get, post, Config};
use rocket_dyn_templates::Template;
use rocket::{
form::{Form, FromForm},
get,
http::{Cookie, CookieJar, Status},
post,
request::{self, FlashMessage, FromRequest, Request},
response::{Flash, Redirect},
serde::Deserialize,
Config,
};
use rocket_dyn_templates::{tera::Context, Template};
use peach_lib::error::PeachError;
use peach_lib::password_utils;
use peach_lib::{error::PeachError, password_utils};
use crate::error::PeachWebError;
use crate::utils::TemplateOrRedirect;
@ -66,37 +69,19 @@ impl<'r> FromRequest<'r> for Authenticated {
// HELPERS AND ROUTES FOR /login
#[derive(Debug, Serialize)]
pub struct LoginContext {
pub back: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
pub title: Option<String>,
}
impl LoginContext {
pub fn build() -> LoginContext {
LoginContext {
back: None,
flash_name: None,
flash_msg: None,
title: None,
}
}
}
#[get("/login")]
pub fn login(flash: Option<FlashMessage>) -> Template {
let mut context = LoginContext::build();
context.back = Some("/".to_string());
context.title = Some("Login".to_string());
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Login".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("login", &context)
Template::render("login", &context.into_json())
}
#[derive(Debug, Deserialize, FromForm)]
@ -116,8 +101,7 @@ pub fn verify_login_form(login_form: LoginForm) -> Result<(), PeachError> {
#[post("/login", data = "<login_form>")]
pub fn login_post(login_form: Form<LoginForm>, cookies: &CookieJar<'_>) -> TemplateOrRedirect {
let result = verify_login_form(login_form.into_inner());
match result {
match verify_login_form(login_form.into_inner()) {
Ok(_) => {
// if successful login, add a cookie indicating the user is authenticated
// and redirect to home page
@ -125,17 +109,18 @@ pub fn login_post(login_form: Form<LoginForm>, cookies: &CookieJar<'_>) -> Templ
// is just admin (this is arbitrary).
// If we had multiple users, we could put the user_id here.
cookies.add_private(Cookie::new(AUTH_COOKIE_KEY, ADMIN_USERNAME));
TemplateOrRedirect::Redirect(Redirect::to("/"))
}
Err(_) => {
// if unsuccessful login, render /login page again
let mut context = LoginContext::build();
context.back = Some("/".to_string());
context.title = Some("Login".to_string());
context.flash_name = Some("error".to_string());
let flash_msg = "Invalid password".to_string();
context.flash_msg = Some(flash_msg);
TemplateOrRedirect::Template(Template::render("login", &context))
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Login".to_string()));
context.insert("flash_name", &("error".to_string()));
context.insert("flash_msg", &("Invalid password".to_string()));
TemplateOrRedirect::Template(Template::render("login", &context.into_json()))
}
}
}
@ -159,44 +144,6 @@ pub struct ResetPasswordForm {
pub new_password2: String,
}
#[derive(Debug, Serialize)]
pub struct ResetPasswordContext {
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl ResetPasswordContext {
pub fn build() -> ResetPasswordContext {
ResetPasswordContext {
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
#[derive(Debug, Serialize)]
pub struct ChangePasswordContext {
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl ChangePasswordContext {
pub fn build() -> ChangePasswordContext {
ChangePasswordContext {
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
/// Verify, validate and save the submitted password. This function is publicly exposed for users who have forgotten their password.
pub fn save_reset_password_form(password_form: ResetPasswordForm) -> Result<(), PeachWebError> {
info!(
@ -218,81 +165,63 @@ pub fn save_reset_password_form(password_form: ResetPasswordForm) -> Result<(),
/// and is specifically for users who have forgotten their password.
#[get("/reset_password")]
pub fn reset_password(flash: Option<FlashMessage>) -> Template {
let mut context = ResetPasswordContext::build();
context.back = Some("/".to_string());
context.title = Some("Reset Password".to_string());
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Reset Password".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("settings/admin/reset_password", &context)
Template::render("settings/admin/reset_password", &context.into_json())
}
/// Password reset form request handler. This route is used by a user who is not logged in
/// and is specifically for users who have forgotten their password.
#[post("/reset_password", data = "<reset_password_form>")]
pub fn reset_password_post(reset_password_form: Form<ResetPasswordForm>) -> Template {
let result = save_reset_password_form(reset_password_form.into_inner());
match result {
Ok(_) => {
let mut context = ChangePasswordContext::build();
context.back = Some("/".to_string());
context.title = Some("Reset Password".to_string());
context.flash_name = Some("success".to_string());
let flash_msg = "New password is now saved. Return home to login".to_string();
context.flash_msg = Some(flash_msg);
Template::render("settings/admin/reset_password", &context)
}
Err(err) => {
let mut context = ChangePasswordContext::build();
// set back icon link to network route
context.back = Some("/".to_string());
context.title = Some("Reset Password".to_string());
context.flash_name = Some("error".to_string());
context.flash_msg = Some(format!("Failed to reset password: {}", err));
Template::render("settings/admin/reset_password", &context)
}
}
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Reset Password".to_string()));
let (flash_name, flash_msg) = match save_reset_password_form(reset_password_form.into_inner()) {
Ok(_) => (
"success".to_string(),
"New password is now saved. Return home to login".to_string(),
),
Err(err) => (
"error".to_string(),
format!("Failed to reset password: {}", err),
),
};
context.insert("flash_name", &Some(flash_name));
context.insert("flash_msg", &Some(flash_msg));
Template::render("settings/admin/reset_password", &context.into_json())
}
// HELPERS AND ROUTES FOR /send_password_reset
#[derive(Debug, Serialize)]
pub struct SendPasswordResetContext {
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl SendPasswordResetContext {
pub fn build() -> SendPasswordResetContext {
SendPasswordResetContext {
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
/// Page for users who have forgotten their password.
/// This route is used by a user who is not logged in
/// to initiate the sending of a new password reset.
#[get("/forgot_password")]
pub fn forgot_password_page(flash: Option<FlashMessage>) -> Template {
let mut context = SendPasswordResetContext::build();
context.back = Some("/".to_string());
context.title = Some("Send Password Reset".to_string());
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Send Password Reset".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("settings/admin/forgot_password", &context)
Template::render("settings/admin/forgot_password", &context.into_json())
}
/// Send password reset request handler. This route is used by a user who is not logged in
@ -301,27 +230,25 @@ pub fn forgot_password_page(flash: Option<FlashMessage>) -> Template {
#[post("/send_password_reset")]
pub fn send_password_reset_post() -> Template {
info!("++ send password reset post");
let result = password_utils::send_password_reset();
match result {
Ok(_) => {
let mut context = ChangePasswordContext::build();
context.back = Some("/".to_string());
context.title = Some("Send Password Reset".to_string());
context.flash_name = Some("success".to_string());
let flash_msg =
"A password reset link has been sent to the admin of this device".to_string();
context.flash_msg = Some(flash_msg);
Template::render("settings/admin/forgot_password", &context)
}
Err(err) => {
let mut context = ChangePasswordContext::build();
context.back = Some("/".to_string());
context.title = Some("Send Password Reset".to_string());
context.flash_name = Some("error".to_string());
context.flash_msg = Some(format!("Failed to send password reset link: {}", err));
Template::render("settings/admin/forgot_password", &context)
}
}
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Send Password Reset".to_string()));
let (flash_name, flash_msg) = match password_utils::send_password_reset() {
Ok(_) => (
"success".to_string(),
"A password reset link has been sent to the admin of this device".to_string(),
),
Err(err) => (
"error".to_string(),
format!("Failed to send password reset link: {}", err),
),
};
context.insert("flash_name", &Some(flash_name));
context.insert("flash_msg", &Some(flash_msg));
Template::render("settings/admin/forgot_password", &context.into_json())
}
// HELPERS AND ROUTES FOR /settings/change_password
@ -353,42 +280,40 @@ pub fn save_password_form(password_form: PasswordForm) -> Result<(), PeachWebErr
/// Change password request handler. This is used by a user who is already logged in.
#[get("/change_password")]
pub fn change_password(flash: Option<FlashMessage>, _auth: Authenticated) -> Template {
let mut context = ChangePasswordContext::build();
// set back icon link to network route
context.back = Some("/settings/admin".to_string());
context.title = Some("Change Password".to_string());
let mut context = Context::new();
context.insert("back", &Some("/settings/admin".to_string()));
context.insert("title", &Some("Change Password".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("settings/admin/change_password", &context)
Template::render("settings/admin/change_password", &context.into_json())
}
/// Change password form request handler. This route is used by a user who is already logged in.
#[post("/change_password", data = "<password_form>")]
pub fn change_password_post(password_form: Form<PasswordForm>, _auth: Authenticated) -> Template {
let result = save_password_form(password_form.into_inner());
match result {
Ok(_) => {
let mut context = ChangePasswordContext::build();
// set back icon link to network route
context.back = Some("/settings/admin".to_string());
context.title = Some("Change Password".to_string());
context.flash_name = Some("success".to_string());
context.flash_msg = Some("New password is now saved".to_string());
// template_dir is set in Rocket.toml
Template::render("settings/admin/change_password", &context)
}
Err(err) => {
let mut context = ChangePasswordContext::build();
// set back icon link to network route
context.back = Some("/settings/admin".to_string());
context.title = Some("Change Password".to_string());
context.flash_name = Some("error".to_string());
context.flash_msg = Some(format!("Failed to save new password: {}", err));
Template::render("settings/admin/change_password", &context)
}
}
let mut context = Context::new();
context.insert("back", &Some("/settings/admin".to_string()));
context.insert("title", &Some("Change Password".to_string()));
let (flash_name, flash_msg) = match save_password_form(password_form.into_inner()) {
Ok(_) => (
"success".to_string(),
"New password is now saved".to_string(),
),
Err(err) => (
"error".to_string(),
format!("Failed to save new password: {}", err),
),
};
context.insert("flash_name", &Some(flash_name));
context.insert("flash_msg", &Some(flash_msg));
Template::render("settings/admin/change_password", &context.into_json())
}

View File

@ -1,69 +1,33 @@
use rocket::{get, request::FlashMessage};
use rocket_dyn_templates::Template;
use serde::Serialize;
use rocket_dyn_templates::{tera::Context, Template};
use crate::routes::authentication::Authenticated;
// HELPERS AND ROUTES FOR / (HOME PAGE)
#[derive(Debug, Serialize)]
pub struct HomeContext {
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
pub title: Option<String>,
}
impl HomeContext {
pub fn build() -> HomeContext {
HomeContext {
flash_name: None,
flash_msg: None,
title: None,
}
}
}
#[get("/")]
pub fn home(_auth: Authenticated) -> Template {
let context = HomeContext {
flash_name: None,
flash_msg: None,
title: None,
};
Template::render("home", &context)
let mut context = Context::new();
context.insert("flash_name", &None::<()>);
context.insert("flash_msg", &None::<()>);
context.insert("title", &None::<()>);
Template::render("home", &context.into_json())
}
// HELPERS AND ROUTES FOR /help
#[derive(Debug, Serialize)]
pub struct HelpContext {
pub back: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
pub title: Option<String>,
}
impl HelpContext {
pub fn build() -> HelpContext {
HelpContext {
back: None,
flash_name: None,
flash_msg: None,
title: None,
}
}
}
#[get("/help")]
pub fn help(flash: Option<FlashMessage>) -> Template {
let mut context = HelpContext::build();
context.back = Some("/".to_string());
context.title = Some("Help".to_string());
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Help".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("help", &context)
Template::render("settings/menu", &context.into_json())
}

View File

@ -1,95 +1,69 @@
use rocket::serde::{Deserialize, Serialize};
use rocket::{
form::{Form, FromForm},
get, post,
request::FlashMessage,
response::{Flash, Redirect},
serde::Deserialize,
uri,
};
use rocket_dyn_templates::Template;
use rocket_dyn_templates::{tera::Context, Template};
use peach_lib::config_manager;
use peach_lib::config_manager::load_peach_config;
use crate::error::PeachWebError;
use crate::routes::authentication::Authenticated;
// HELPERS AND ROUTES FOR /settings/admin
#[derive(Debug, Serialize)]
pub struct AdminMenuContext {
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl AdminMenuContext {
pub fn build() -> AdminMenuContext {
AdminMenuContext {
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
/// Administrator settings menu.
#[get("/")]
pub fn admin_menu(flash: Option<FlashMessage>, _auth: Authenticated) -> Template {
let mut context = AdminMenuContext::build();
// set back icon link to settings route
context.back = Some("/settings".to_string());
context.title = Some("Administrator Settings".to_string());
let mut context = Context::new();
context.insert("back", &Some("/settings".to_string()));
context.insert("title", &Some("Administrator Settings".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("settings/admin/menu", &context)
Template::render("settings/admin/menu", &context.into_json())
}
// HELPERS AND ROUTES FOR /settings/admin/configure
#[derive(Debug, Serialize)]
pub struct ConfigureAdminContext {
pub ssb_admin_ids: Vec<String>,
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl ConfigureAdminContext {
pub fn build() -> ConfigureAdminContext {
let peach_config = load_peach_config().unwrap();
let ssb_admin_ids = peach_config.ssb_admin_ids;
ConfigureAdminContext {
ssb_admin_ids,
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
/// View and delete currently configured admin.
#[get("/configure")]
pub fn configure_admin(flash: Option<FlashMessage>, _auth: Authenticated) -> Template {
let mut context = ConfigureAdminContext::build();
// set back icon link to settings route
context.back = Some("/settings/admin".to_string());
context.title = Some("Configure Admin".to_string());
let mut context = Context::new();
context.insert("back", &Some("/settings/admin".to_string()));
context.insert("title", &Some("Configure Admin".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("settings/admin/configure_admin", &context)
// load the peach configuration vector
match config_manager::load_peach_config() {
Ok(config) => {
// retrieve the vector of ssb admin ids
let ssb_admin_ids = config.ssb_admin_ids;
context.insert("ssb_admin_ids", &ssb_admin_ids);
}
// if load fails, overwrite the flash_name and flash_msg
Err(e) => {
context.insert("flash_name", &Some("error".to_string()));
context.insert(
"flash_msg",
&Some(format!("Failed to load Peach config: {}", e)),
);
}
}
Template::render("settings/admin/configure_admin", &context.into_json())
}
// HELPERS AND ROUTES FOR /settings/admin/add
@ -99,25 +73,6 @@ pub struct AddAdminForm {
pub ssb_id: String,
}
#[derive(Debug, Serialize)]
pub struct AddAdminContext {
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl AddAdminContext {
pub fn build() -> AddAdminContext {
AddAdminContext {
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
pub fn save_add_admin_form(admin_form: AddAdminForm) -> Result<(), PeachWebError> {
let _result = config_manager::add_ssb_admin_id(&admin_form.ssb_id)?;
// if the previous line didn't throw an error then it was a success
@ -126,17 +81,18 @@ pub fn save_add_admin_form(admin_form: AddAdminForm) -> Result<(), PeachWebError
#[get("/add")]
pub fn add_admin(flash: Option<FlashMessage>, _auth: Authenticated) -> Template {
let mut context = AddAdminContext::build();
context.back = Some("/settings/admin/configure".to_string());
context.title = Some("Add Admin".to_string());
let mut context = Context::new();
context.insert("back", &Some("/settings/admin/configure".to_string()));
context.insert("title", &Some("Add Admin".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
// template_dir is set in Rocket.toml
Template::render("settings/admin/add_admin", &context)
Template::render("settings/admin/add_admin", &context.into_json())
}
#[post("/add", data = "<add_admin_form>")]

View File

@ -1,41 +1,22 @@
use rocket::{get, request::FlashMessage, serde::Serialize};
use rocket_dyn_templates::Template;
use rocket::{get, request::FlashMessage};
use rocket_dyn_templates::{tera::Context, Template};
use crate::routes::authentication::Authenticated;
// HELPERS AND ROUTES FOR /settings
#[derive(Debug, Serialize)]
pub struct SettingsMenuContext {
pub back: Option<String>,
pub title: Option<String>,
pub flash_name: Option<String>,
pub flash_msg: Option<String>,
}
impl SettingsMenuContext {
pub fn build() -> SettingsMenuContext {
SettingsMenuContext {
back: None,
title: None,
flash_name: None,
flash_msg: None,
}
}
}
/// View and delete currently configured admin.
#[get("/settings")]
pub fn settings_menu(flash: Option<FlashMessage>, _auth: Authenticated) -> Template {
let mut context = SettingsMenuContext::build();
// set back icon link to network route
context.back = Some("/".to_string());
context.title = Some("Settings".to_string());
let mut context = Context::new();
context.insert("back", &Some("/".to_string()));
context.insert("title", &Some("Settings".to_string()));
// check to see if there is a flash message to display
if let Some(flash) = flash {
// add flash message contents to the context object
context.flash_name = Some(flash.kind().to_string());
context.flash_msg = Some(flash.message().to_string());
context.insert("flash_name", &Some(flash.kind().to_string()));
context.insert("flash_msg", &Some(flash.message().to_string()));
};
Template::render("settings/menu", &context)
Template::render("settings/menu", &context.into_json())
}

View File

@ -1,5 +1,6 @@
use log::{debug, warn};
use std::collections::HashMap;
use log::{debug, warn};
use rocket::{
form::{Form, FromForm},
get, post,
@ -9,14 +10,14 @@ use rocket::{
uri, UriDisplayQuery,
};
use rocket_dyn_templates::Template;
use std::collections::HashMap;
use peach_lib::network_client;
use peach_lib::network_client::{AccessPoint, Networks, Scan};
use peach_lib::stats_client::Traffic;
use peach_lib::{
// TODO: replace this with peach_network::network
network_client::{AccessPoint, Networks, Scan},
stats_client::Traffic,
};
use crate::routes::authentication::Authenticated;
use crate::utils::monitor;
use crate::utils::monitor::{Alert, Data, Threshold};
// STRUCTS USED BY NETWORK ROUTES
@ -575,6 +576,7 @@ pub fn deploy_client(_auth: Authenticated) -> Flash<Redirect> {
#[get("/wifi/add")]
pub fn add_wifi(flash: Option<FlashMessage>, _auth: Authenticated) -> Template {
// TODO: use simple context (no need to build entire NetworkContext)
let mut context = NetworkContext::build();
// set back icon link to network route
context.back = Some("/settings/network".to_string());