2020-01-21 07:02:03 +01:00
|
|
|
use crate::users::User;
|
2018-11-24 12:44:17 +01:00
|
|
|
use rocket::{
|
|
|
|
http::Status,
|
2020-01-23 19:41:46 +01:00
|
|
|
request::{self, FromRequestAsync, Request},
|
2018-11-24 12:44:17 +01:00
|
|
|
Outcome,
|
|
|
|
};
|
2018-07-27 19:05:36 +02:00
|
|
|
|
|
|
|
/// Wrapper around User to use as a request guard on pages reserved to admins.
|
|
|
|
pub struct Admin(pub User);
|
|
|
|
|
2020-01-23 19:41:46 +01:00
|
|
|
impl<'a, 'r> FromRequestAsync<'a, 'r> for Admin {
|
2018-07-27 19:05:36 +02:00
|
|
|
type Error = ();
|
|
|
|
|
2020-01-23 19:41:46 +01:00
|
|
|
fn from_request(request: &'a Request<'r>) -> request::FromRequestFuture<'a, Self, Self::Error> {
|
|
|
|
Box::pin(async move {
|
2020-01-25 23:37:44 +01:00
|
|
|
let user = try_outcome!(User::from_request(request).await);
|
2020-01-23 19:41:46 +01:00
|
|
|
if user.is_admin() {
|
|
|
|
Outcome::Success(Admin(user))
|
|
|
|
} else {
|
|
|
|
Outcome::Failure((Status::Unauthorized, ()))
|
|
|
|
}
|
|
|
|
})
|
2018-07-27 19:05:36 +02:00
|
|
|
}
|
|
|
|
}
|
2019-09-13 12:28:36 +02:00
|
|
|
|
|
|
|
/// Same as `Admin` but for moderators.
|
|
|
|
pub struct Moderator(pub User);
|
|
|
|
|
2020-01-23 19:41:46 +01:00
|
|
|
impl<'a, 'r> FromRequestAsync<'a, 'r> for Moderator {
|
2019-09-13 12:28:36 +02:00
|
|
|
type Error = ();
|
|
|
|
|
2020-01-23 19:41:46 +01:00
|
|
|
fn from_request(request: &'a Request<'r>) -> request::FromRequestFuture<'a, Self, Self::Error> {
|
|
|
|
Box::pin(async move {
|
2020-01-25 23:37:44 +01:00
|
|
|
let user = try_outcome!(User::from_request(request).await);
|
2020-01-23 19:41:46 +01:00
|
|
|
if user.is_moderator() {
|
|
|
|
Outcome::Success(Moderator(user))
|
|
|
|
} else {
|
|
|
|
Outcome::Failure((Status::Unauthorized, ()))
|
|
|
|
}
|
|
|
|
})
|
2019-09-13 12:28:36 +02:00
|
|
|
}
|
|
|
|
}
|