ezidam: guards to check if setup is complete or not

This commit is contained in:
Philippe Loctaux 2023-03-05 23:34:47 +01:00
parent bb3e4dfd40
commit c95800330a
4 changed files with 74 additions and 0 deletions

View file

@ -0,0 +1,5 @@
mod completed_setup;
mod need_setup;
pub use completed_setup::CompletedSetup;
pub use need_setup::NeedSetup;

View file

@ -0,0 +1,34 @@
use crate::database::Database;
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome};
use rocket::Request;
use users::User;
#[derive(Debug)]
pub enum Error {
GetDatabase,
Request(users::Error),
}
pub struct CompletedSetup;
#[rocket::async_trait]
impl<'r> FromRequest<'r> for CompletedSetup {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let db = match request.guard::<&Database>().await {
Outcome::Success(database) => database,
Outcome::Failure(e) => return Outcome::Failure((e.0, Error::GetDatabase)),
Outcome::Forward(f) => return Outcome::Forward(f),
};
match User::get_initial_admin(&**db).await {
Ok(initial_admin) => match initial_admin {
Some(_) => Outcome::Success(CompletedSetup),
None => Outcome::Forward(()),
},
Err(e) => Outcome::Failure((Status::InternalServerError, Error::Request(e))),
}
}
}

View file

@ -0,0 +1,34 @@
use crate::database::Database;
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome};
use rocket::Request;
use users::User;
#[derive(Debug)]
pub enum Error {
GetDatabase,
Request(users::Error),
}
pub struct NeedSetup;
#[rocket::async_trait]
impl<'r> FromRequest<'r> for NeedSetup {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let db = match request.guard::<&Database>().await {
Outcome::Success(database) => database,
Outcome::Failure(e) => return Outcome::Failure((e.0, Error::GetDatabase)),
Outcome::Forward(f) => return Outcome::Forward(f),
};
match User::get_initial_admin(&**db).await {
Ok(initial_admin) => match initial_admin {
Some(_) => Outcome::Forward(()),
None => Outcome::Success(NeedSetup),
},
Err(e) => Outcome::Failure((Status::InternalServerError, Error::Request(e))),
}
}
}

View file

@ -3,6 +3,7 @@ use rocket::{Build, Rocket};
mod database;
mod error;
mod file_from_bytes;
mod guards;
mod page;
mod response_timer;
mod routes;