set auth request guard from managed state
This commit is contained in:
parent
680044cba8
commit
f3ddbcf07c
|
@ -7,7 +7,6 @@ use rocket::{
|
|||
request::{self, FlashMessage, FromRequest, Request},
|
||||
response::{Flash, Redirect},
|
||||
serde::Deserialize,
|
||||
Config,
|
||||
};
|
||||
use rocket_dyn_templates::{tera::Context, Template};
|
||||
|
||||
|
@ -15,6 +14,8 @@ use peach_lib::{error::PeachError, password_utils};
|
|||
|
||||
use crate::error::PeachWebError;
|
||||
use crate::utils::TemplateOrRedirect;
|
||||
//use crate::DisableAuth;
|
||||
use crate::RocketConfig;
|
||||
|
||||
// HELPERS AND STRUCTS FOR AUTHENTICATION WITH COOKIES
|
||||
|
||||
|
@ -42,26 +43,30 @@ impl<'r> FromRequest<'r> for Authenticated {
|
|||
type Error = LoginError;
|
||||
|
||||
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
// check for `disable_auth` config value; set to `false` if unset
|
||||
// can be set via the `ROCKET_DISABLE_AUTH` environment variable
|
||||
// - env var, if set, takes precedence over value defined in `Rocket.toml`
|
||||
let authentication_is_disabled: bool = match Config::figment().find_value("disable_auth") {
|
||||
// deserialize the boolean value; set to `false` if an error is encountered
|
||||
Ok(value) => value.deserialize().unwrap_or(false),
|
||||
Err(_) => false,
|
||||
};
|
||||
if authentication_is_disabled {
|
||||
let auth = Authenticated {};
|
||||
request::Outcome::Success(auth)
|
||||
} else {
|
||||
let authenticated = req
|
||||
.cookies()
|
||||
.get_private(AUTH_COOKIE_KEY)
|
||||
.and_then(|cookie| cookie.value().parse().ok())
|
||||
.map(|_value: String| Authenticated {});
|
||||
match authenticated {
|
||||
Some(auth) => request::Outcome::Success(auth),
|
||||
None => request::Outcome::Failure((Status::Forbidden, LoginError::UserNotLoggedIn)),
|
||||
// retrieve auth state from managed state (returns `Option<bool>`).
|
||||
// this value is read from the Rocket.toml config file on start-up
|
||||
let authentication_is_disabled = req
|
||||
.rocket()
|
||||
.state::<RocketConfig>()
|
||||
.map(|config| (&config.disable_auth));
|
||||
|
||||
match authentication_is_disabled {
|
||||
Some(true) => {
|
||||
let auth = Authenticated {};
|
||||
request::Outcome::Success(auth)
|
||||
}
|
||||
_ => {
|
||||
let authenticated = req
|
||||
.cookies()
|
||||
.get_private(AUTH_COOKIE_KEY)
|
||||
.and_then(|cookie| cookie.value().parse().ok())
|
||||
.map(|_value: String| Authenticated {});
|
||||
match authenticated {
|
||||
Some(auth) => request::Outcome::Success(auth),
|
||||
None => {
|
||||
request::Outcome::Failure((Status::Forbidden, LoginError::UserNotLoggedIn))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue