DDtKey / protect-endpoints

Authorization extension for popular web-frameworks to protect your endpoints
Apache License 2.0
211 stars 16 forks source link

how do in middleware use app_data? #77

Closed xcfvcg closed 8 months ago

xcfvcg commented 8 months ago

when i want read cookie and from redis read it time

DDtKey commented 8 months ago

Hi @Zheby!

Could you clarify, what framework do you use? actix-web?

If so, extractor interface is async fn extract(req: &ServiceRequest) -> Result<HashSet<String>, Error> Thus, ServiceRequest has a method app_data (documentation ref), does it work for you?

Probably I misunderstood something, in that case could you provide some MRE(pseudo-code) of what you want to achieve?

Thanks for using/trying the crate!

xcfvcg commented 8 months ago

hello @DDtKey ep i use

 let redis_url = format!("redis://{}:{}", 
            std::env::var("REDIS_HOST").unwrap(),
            std::env::var("REDIS_PORT").unwrap()
        );
        let client = rustis::client::Client::connect(redis_url).await.unwrap();

when i add client in route

 let auth = GrantsMiddleware::with_extractor(Middleware::extract);
 App::new()
            .app_data(web::Data::new(client.clone()))
           .wrap(auth)

Then, how should I access redis inside

DDtKey commented 8 months ago

You can access it with app_data (take a look at HttpRequest::app_data as well), right.

Something like that should work for you:

async fn extract(req: &ServiceRequest) -> Result<HashSet<String>, Error> {
  let client: &web::Data<rustis::client::Client> = req.app_data().expect("redis client must present in app_data"); // you can handle `Option` how you wish
  // ... you logic here
}

It's more about actix-web interface rather that extractor itself though. Let me know if it doesn't work for you

xcfvcg commented 8 months ago

Oh my god, I seem to have found a problem. This needs to be included with web::Data. I'm sorry to bother you, but your crate is very good and can make it easier for us to manage permissions.

DDtKey commented 8 months ago

No worries, glad to help!

your crate is very good and can make it easier for us to manage permissions.

Thank you! Don't hesitate to reach out with any questions