Jerry Ji
Jerry Ji

Reputation: 386

How to Support Flask-SSE Access Control

Flask-SSE doc --

https://flask-sse.readthedocs.io/en/latest/advanced.html#access-control

has a small Access Control example --

@sse.before_request 
def check_access():
    if request.args.get("channel") == "analytics" and not g.user.is_admin():
        abort(403)

My use case is: I have two types of SSE endpoints, one type is public, say under route /sse/public/notice, which does not require authentication check; and also private ones with routes /sse/private/<user_id>/balance, which I must check both flask_login.current_user.is_authenticated and flask_login.current_user.get_id() == user_id

From Flask-SSE's simple example, I'm not sure how I can achieve supporting both types of sse endpoints.

Any pointer will be much appreciated.

Upvotes: 2

Views: 308

Answers (1)

singingwolfboy
singingwolfboy

Reputation: 5556

I am the author of Flask-SSE. Why not do something like this?

@sse.before_request 
def check_access():
    channel = request.args.get("channel") or "sse"
    if channel.startswith("private."):
        if current_user.is_anonymous:
            abort(401)
        user_id = channel[8:]
        if current_user.get_id() != user_id:
            abort(403)

Upvotes: 2

Related Questions