Skip to content

route-level middleware for authentication #13

@ndortega

Description

@ndortega

Thanks for choosing Oxygen to build your package!

I like to take a look at real-world use cases and see if there's any patterns that could be added to the package and shared with others. While I was doing so, I found a potential pattern upgrade that could simplify your code!

I noticed you had a clever macro based authentication to protect select resources. Below is a partial snippet of one of your "/user" routes from the user.jl module

root = router("/user", tags=["user"])

@get root("/") @admin_required function (request::HTTP.Request)
    return json(get_users(); status=HTTP.StatusCodes.OK)
end

While this does work perfectly fine, you can also use route-level middleware to have logic that's only executed on this select route

#### Middleware 

function admin_required(handle::Function)
    function(req::HTTP.Request)
        global _DEARDIARY_APICONFIG
        if _DEARDIARY_APICONFIG.enable_auth
            user = request.context[:user]
            if !user.is_admin
                return json(
                    ("message" => "Admin privileges required");
                    status=HTTP.StatusCodes.FORBIDDEN,
                )
            end
        else
            @warn "Authentication is disabled. Handlers will be injected with the default admin user."
        end
        return handle(req)
    end
end

#### Routes

root = router("/user", tags=["user"])

# Now all requests who hit this specific endpoint will have to pass through the `admin_required` middleware function 
@get root("/", middleware=[admin_required]) function (request::HTTP.Request)
    return json(get_users(); status=HTTP.StatusCodes.OK)
end

If you don't like this pattern - no worries, feel free to close this issue. Your code works as is, and this is just a suggestion

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions