poem-grants

poem-grants

Extension for [poem] to validate user permissions.

CI Crates.io Downloads Badge crates.io Documentation dependency status Apache 2.0 or MIT licensed

To check user access to specific services, you can use built-in proc-macro, PermissionGuard or manual.

The library can also be integrated with third-party solutions or your custom middlewares (like [jwt-auth] example).

Provides a complete analogue of the [actix-web-grants].

NOTE: [poem-openapi] support is still in development.

How to use

  1. Declare your own permission extractor

The easiest way is to declare a function with the following signature (trait is already implemented for such Fn): rust,ignore // You can use custom type instead of String async fn extract(req: &poem::Request) -> poem::Result<Vec<String>>

  1. Add middleware to your application using the extractor defined in step 1

rust,ignore Route::new() .at("/endpoint", your_endpoint) .with(GrantsMiddleware::with_extractor(extract))

Steps 1 and 2 can be replaced by custom middleware or integration with another libraries. Take a look at an jwt-auth example

  1. Protect your endpoints in any convenient way from the examples below:

Example of proc-macro way protection

```rust,no_run use poem::{Response, http::StatusCode};

[poemgrants::haspermissions("OPREADSECURED_INFO")]

async fn macrosecured() -> Response { Response::builder().status(StatusCode::OK).body("ADMINRESPONSE") } ```

Example of ABAC-like protection and custom permission type

Here is an example using the type and secure attributes. But these are independent features.

secure allows you to include some checks in the macro based on function params.

type allows you to use a custom type for the roles and permissions (then the middleware needs to be configured). Take a look at an enum-role example

```rust,ignore use poem::{Response, http::StatusCode, web}; use enums::Role::{self, ADMIN}; use dto::User;

[poemgrants::hasrole("ADMIN", type = "Role", secure = "*user_id == user.id")]

async fn macrosecured(userid: web::Path, user: web::Data) -> Response { Response::builder().status(StatusCode::OK).body("some secured response") } ```

Example of manual way protection

```rust,norun use poem::{Response, http::StatusCode}; use poemgrants::permissions::{AuthDetails, PermissionsCheck};

[poem::handler]

async fn manualsecure(details: AuthDetails) -> Response { if details.haspermission("ROLEADMIN") { return Response::builder().status(StatusCode::OK).body("ADMINRESPONSE"); } Response::builder().status(StatusCode::OK).body("OTHER_RESPONSE") } ```

You can find more [examples] in the git repository folder and [documentation].

Supported poem versions