lfglabs-dev / api.starknet.quest

starknet.quest rust backend
7 stars 28 forks source link

Replace admin auth macro by middleware #245

Closed Marchand-Nicolas closed 2 months ago

Marchand-Nicolas commented 2 months ago

Currently, any admin route starts by calling a macro

let user = check_authorization!(headers, &state.conf.auth.secret_key.as_ref()) as String;

to check the token validity. We would like to replace this system by a middleware.

You can find an example you can reuse here: https://gist.github.com/Marchand-Nicolas/e37b14c5d8e5d04492067ea8320fe7e4 Do not hesitate to ask for more examples/help to implement the above code.

ScottyDavies commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

I am front end developer with 6 years experience. i have worked with microsoft on several projects, this will be my first time contributing to the hackathon and i am ready to work

How I plan on tackling this issue

I would approach this issue with following steps Implement the Middleware: Create an auth_middleware function that takes the request, application state, and next middleware as parameters. In the middleware, check if the "Authorization" header is present and starts with "Bearer ". Extract the JWT from the "Authorization" header. Check if the JWT is not blacklisted by checking the jwt_blacklist in the application state. Decode the JWT using the configured jwt_decoding_key and validate the signature. If the JWT is valid, store the claims from the token in the request extensions. Call the next middleware or route handler. If the JWT is invalid or missing, return an unauthorized response. Register the Middleware: Register the auth_middleware as a global middleware for the application. This can be done by using the middleware function provided by your web framework (e.g., Axum) and passing the auth_middleware function. Update the Route Handlers: In the route handlers that require authorization, access the claims from the request extensions instead of using the check_authorization! macro. This allows you to reuse the authentication logic across multiple routes and simplifies the route handler implementation. Handle Different Authentication Failures: The middleware should handle different types of authentication failures, such as missing authorization header, blacklisted token, and invalid token. For each failure case, the middleware should return an appropriate unauthorized response with a descriptive error message.

Dprof-in-tech commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

As an experienced Full Stack Blockchain Developer, I'm excited to contribute my expertise to Edition 7 of the OnlyDust hackathons. With a strong background in Next.js, TypeScript, JavaScript, React, Node.js, Solidity, and Cairo, I've honed my technical skills across the blockchain development landscape. My journey with OnlyDust began at Edition 2, and I've since made 28 contributions across 11 projects. This extensive experience on the platform has allowed me to develop a keen understanding of delivering high-quality solutions under tight deadlines. I bring a unique blend of technical prowess and user-centric design to every project, whether I'm crafting immersive 3D experiences or developing innovative smart contracts. My track record demonstrates my ability to adapt quickly and contribute effectively to diverse challenges. I'm confident in my capacity to tackle new problems and drive innovation in the blockchain space. As we embark on Edition 7, I'm eager to leverage my hackathon experience and technical skills to push the boundaries of what's possible in blockchain development. With a passion for creating cutting-edge solutions, I'm excited to collaborate with the OnlyDust community and contribute to the advancement of the blockchain ecosystem.

How I plan on tackling this issue

i have experience building and managing authentication in nextjs applications using a middleware and i would love to contribute to starknet quest by solving this issue

Mystic-Nayy commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

I am a web3/frontend developer

How I plan on tackling this issue

  1. Implement Middleware: Replace the existing macro check_authorization! with a custom middleware that validates the token. Reuse the example provided in the gist as a reference for creating the middleware.

  2. Refactor Admin Routes: Modify the admin routes to use the new middleware for authorization instead of the macro.

  3. Test and Validate: Ensure the middleware correctly checks the token validity and that all admin routes function as expected with the new system.

Ugo-X commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

I am a Full Stack blockchain Developer with expertise in Next.js, Nest.js, TypeScript, JavaScript, React, Node.js, Three.js, and Solidity. My journey with OnlyDust hackathons began at Edition 1, and I've since made 47 contributions across 11 projects. With my extensive experience on the OnlyDust platform (profile: https://app.onlydust.com/u/Ugo-X), I've honed my skills in delivering quality solutions under pressure. I bring a unique blend of technical proficiency and user-focused design to every project, whether it's crafting immersive 3D experiences or developing smart contracts. My track record shows I can adapt quickly and contribute effectively to diverse challenges. As we surf through Edition 7, I'm excited to leverage my skills and hackathon experience to push the boundaries of blockchain development. I'm confident in my ability to tackle new challenges and drive innovation in this space.

How I plan on tackling this issue

I will migrate token authorization from a macro to a middleware using these steps:

  1. Create Authorization Middleware:

    • Design a Rust structure representing the middleware.
    • Include a function for token verification using a suitable library (e.g., JWT library).
  2. Integrate Middleware:

    • Register the middleware during application initialization using your framework's method (e.g., Rocket's attach or Axum's layer).
  3. Request Interception:

    • The middleware will intercept incoming requests before they reach admin routes.
  4. Token Verification:

    • Inside the middleware, extract the authorization token from request headers.
    • Validate the token's signature against the secret key from your configuration.
  5. Error Handling:

    • Implement error handling within the middleware for invalid tokens (e.g., return unauthorized status code).
  6. Admin Route Access:

    • After successful verification by the middleware, the request proceeds to the admin route.
  7. Example and Testing:

This approach offers better modularity and simplifies future authorization logic changes.

thesledge04 commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

I have a solid background in server-side development and middleware integration, particularly in implementing and managing authentication and authorization mechanisms. My experience includes working with various web frameworks and languages, where I’ve replaced or refactored existing authentication systems to improve security and maintainability.

In previous projects, I’ve successfully implemented middleware for handling authentication and authorization. This often involves intercepting requests, validating tokens, and ensuring that only authorized users can access specific routes. By moving from a macro-based approach to middleware, I can streamline the authorization process, making it more modular and easier to manage across the application.

For example, I’ve worked with middleware in frameworks like Express.js for Node.js and Actix for Rust, where I configured middleware to handle authentication checks efficiently. This involved setting up middleware functions to process requests before they reach the route handlers, ensuring that authentication logic is centralized and reusable.

To replace the current macro-based system with middleware, I would leverage my expertise to:

Define Middleware: Create middleware that intercepts requests and performs token validation using the provided secret key. Integrate Middleware: Integrate the middleware into the application’s routing system so that it applies to all relevant admin routes. Test Thoroughly: Ensure that the middleware handles various scenarios correctly, including valid and invalid tokens, and edge cases like expired tokens.

How I plan on tackling this issue

  1. Understand the Existing System: Review the current macro check_authorization! to understand how it validates tokens and retrieves user information. Identify where and how this macro is used across your admin routes.
  2. Create Middleware for Authorization: Implement middleware that handles the token validation process. Middleware will intercept requests before they reach the route handlers and ensure that the user is authorized. Example in Rust with Actix-web: Define the Middleware:

rust Copy code use actix_service::ServiceRequest; use actix_web::{Error, HttpResponse}; use actix_web::dev::ServiceResponse; use futures::future::{ok, Ready}; use futures::Future; use std::pin::Pin;

async fn check_authorization_middleware( req: ServiceRequest, srv: &S, ) -> Result<ServiceResponse, Error> where S: actix_service::Service, { let headers = req.headers(); let secret_key = "your_secret_key"; // Replace with actual key or retrieve from config

// Replace this with your actual token validation logic
let token_valid = match check_authorization(headers, secret_key) {
    Ok(_) => true,
    Err(_) => false,
};

if token_valid {
    Ok(srv.call(req).await?)
} else {
    Ok(req.error_response(HttpResponse::Unauthorized()))
}

}

fn check_authorization(headers: &HeaderMap, secret_key: &str) -> Result<String, String> { // Your token validation logic here Ok("user_info".to_string()) // Replace with actual implementation } Integrate the Middleware:

In your Actix-web app setup, register the middleware for the routes that need authorization:

rust Copy code use actix_web::{App, HttpServer, web};

[actix_web::main]

async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .wrap_fn(check_authorization_middleware) // Apply middleware globally .service(web::resource("/admin").route(web::get().to(admin_handler))) // Register other routes }) .bind("127.0.0.1:8080")? .run() .await }

async fn admin_handler() -> &'static str { "Admin area" }

  1. Testing: Unit Testing: Write unit tests for the middleware function to ensure it correctly validates tokens and handles different scenarios (valid tokens, invalid tokens, etc.). Integration Testing: Test the entire application to confirm that the middleware is correctly applied to admin routes and does not interfere with other routes.
  2. Documentation and Refactoring: Update Documentation: Ensure that the documentation reflects the new middleware-based approach. Refactor Routes: Remove the old macro-based authorization from the routes and ensure all admin routes use the new middleware.
  3. Deploy and Monitor: Deploy: Push the changes to your staging environment and then to production. Monitor: Keep an eye on application logs and performance to ensure the middleware is functioning as expected.
Benjtalkshow commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

Hi @Marchand-Nicolas

I'm available to work on replacing the current admin auth macro with a middleware solution. My name is Benjamin, and I have extensive experience in middleware development and authorization systems. My background includes implementing and optimizing authentication and authorization mechanisms for secure web applications.

Understanding the Issue

Currently, any admin route uses a macro to check token validity. We want to replace this approach with a middleware system to streamline authorization checks and improve maintainability.

How I plan on tackling this issue

Implement Middleware for Authorization

  • Middleware Function: I will develop a middleware function to handle authorization checks. This middleware will intercept requests, validate tokens, and manage authorization logic.

Implementation Steps

  1. Create Middleware Function:

    • I will extract the authorization token from the request headers.
    • I will validate the token against a blacklist and decode it using the JWT decoding key.
    • If the token is valid, store the user's claims in the request extensions and proceed with the request. If invalid, return an unauthorized response.
  2. Integrate Middleware:

    • I will add the newly created middleware to route handlers to replace the existing macro-based authorization checks.
  3. Testing:

    • I will verify that the middleware correctly handles token validation and authorization.
    • I will test for scenarios with missing or invalid tokens to ensure proper error handling.
LukePereyra commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

I'm a Software Engineer SSR experienced with Rust, but not in web3, this is one of my firsts contributions.

How I plan on tackling this issue

I will use the code provided to replaced the macro, I will try to implemented it as a middleware

ShantelPeters commented 2 months ago

I am applying to this issue via OnlyDust platform.

My background and how it can be leveraged

I have extensive experience with Rust and middleware implementation in web frameworks. I’ve previously worked on refactoring authentication systems and integrating middleware to streamline route authorization. This background will help me efficiently replace the macro-based authorization with a middleware solution, ensuring cleaner and more maintainable code.

How I plan on tackling this issue

To approach this problem, I would:

  1. Implement Middleware: Create a middleware function to handle authorization checks. This function will extract and validate the token from request headers, similar to the provided example.

  2. Update Routes: Modify the admin routes to use this middleware instead of the current macro-based authorization check. This involves integrating the middleware into the route handler configuration.

  3. Test: Thoroughly test the new middleware to ensure it correctly validates tokens and integrates seamlessly with existing routes.

onlydustapp[bot] commented 2 months ago

The maintainer Marchand-Nicolas has assigned Ugo-X to this issue via OnlyDust Platform. Good luck!