Role based Auth #1792
Answered
by
davidpdrsn
Gaelik-git
asked this question in
Q&A
Role based Auth
#1792
-
I would like to have a simple way of having role based auth for my endpoint. I found the pub struct User {
pub id: u8,
pub roles: Vec<Role>,
}
#[async_trait]
impl<S> FromRequestParts<S> for User
where
S: Send + Sync,
{ ... }
pub async fn health(user: User) -> impl IntoResponse {
(StatusCode::OK, ())
} I was also able to make it work with a simple wrapper to check one role #[derive(Debug, PartialEq)]
pub struct Admin;
#[derive(Debug, PartialEq)]
pub struct Read;
#[derive(Debug, PartialEq)]
pub enum Role {
Admin(Admin),
Reader(Reader),
}
trait RoleCheck {
fn can_access(role: &Role) -> bool;
}
impl RoleCheck for Admin {
fn can_access(role: &Role) -> bool {
match role {
Role::Admin(_) => true,
_ => false,
}
}
}
pub struct UserWithRole<T> {
role: std::marker::PhantomData<T>,
inner: User,
}
#[async_trait]
impl<T, S> FromRequestParts<S> for UserWithRole<T>
where
S: Send + Sync,
T: RoleCheck,
{ ... }
pub async fn health(user: UserWithRole<Admin>) -> impl IntoResponse {
(StatusCode::OK, ())
} But it there a way to create something like so I could do pub async fn health(user: UserWithRoles<[Admin, Reader]>) -> impl IntoResponse {
(StatusCode::OK, ())
}
pub async fn info(user: UserWithAnyRole<[Admin, Reader]>) -> impl IntoResponse {
(StatusCode::OK, ())
} |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Feb 27, 2023
Replies: 1 comment 1 reply
-
Maybe you can use a tuple |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Gaelik-git
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe you can use a tuple
UserWithAnyRole<(Admin, Reader)>
. Can't putAdmin
andReader
into an array since they don't have the same type.