-
Notifications
You must be signed in to change notification settings - Fork 138
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
plume-models: convert admin & api-tokens to async
n.b.: I do *not* like the error handling in api_tokens 😒️
- Loading branch information
Showing
2 changed files
with
49 additions
and
42 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,38 +1,42 @@ | ||
use crate::users::User; | ||
use rocket::{ | ||
http::Status, | ||
request::{self, FromRequest, Request}, | ||
request::{self, FromRequestAsync, Request}, | ||
Outcome, | ||
}; | ||
|
||
/// Wrapper around User to use as a request guard on pages reserved to admins. | ||
pub struct Admin(pub User); | ||
|
||
impl<'a, 'r> FromRequest<'a, 'r> for Admin { | ||
impl<'a, 'r> FromRequestAsync<'a, 'r> for Admin { | ||
type Error = (); | ||
|
||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Admin, ()> { | ||
let user = request.guard::<User>()?; | ||
if user.is_admin() { | ||
Outcome::Success(Admin(user)) | ||
} else { | ||
Outcome::Failure((Status::Unauthorized, ())) | ||
} | ||
fn from_request(request: &'a Request<'r>) -> request::FromRequestFuture<'a, Self, Self::Error> { | ||
Box::pin(async move { | ||
let user = try_outcome!(request.guard::<User>()); | ||
if user.is_admin() { | ||
Outcome::Success(Admin(user)) | ||
} else { | ||
Outcome::Failure((Status::Unauthorized, ())) | ||
} | ||
}) | ||
} | ||
} | ||
|
||
/// Same as `Admin` but for moderators. | ||
pub struct Moderator(pub User); | ||
|
||
impl<'a, 'r> FromRequest<'a, 'r> for Moderator { | ||
impl<'a, 'r> FromRequestAsync<'a, 'r> for Moderator { | ||
type Error = (); | ||
|
||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Moderator, ()> { | ||
let user = request.guard::<User>()?; | ||
if user.is_moderator() { | ||
Outcome::Success(Moderator(user)) | ||
} else { | ||
Outcome::Failure((Status::Unauthorized, ())) | ||
} | ||
fn from_request(request: &'a Request<'r>) -> request::FromRequestFuture<'a, Self, Self::Error> { | ||
Box::pin(async move { | ||
let user = try_outcome!(request.guard::<User>()); | ||
if user.is_moderator() { | ||
Outcome::Success(Moderator(user)) | ||
} else { | ||
Outcome::Failure((Status::Unauthorized, ())) | ||
} | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters