Limiting ajax call only to user login in Flask

I am trying to restrict ajax call to registered users only. A typical use case is blogging, only registered users can post, otherwise the user must be redirected to the / login endpoint. I use flash security. I can do the same without using ajax. Can anyone suggest me how to implement such a function.

+4
source share
1 answer

Assuming you are trying to get data from / ajax like this:

$.getJSON("/ajax", function(data){
    ...
});

init.py login_required:

from flask.ext.security import login_required     

@app.route('/ajax')
@login_required
def ajax():
    data = get_data()  # Get your data
    return json.dumps(data)

:

from flask.ext.security import current_user

@app.route('/ajax')
def ajax():
    if current_user.is_authenticated:
        data = get_data()  # Get your data
        return json.dumps(data)
    else:
        return 'Not allowed'
+2

Source: https://habr.com/ru/post/1626047/


All Articles