I am trying to restrict a ajax call only to logged in users. Typical use case is posting blogs, only logged in user can submit posts, else user should be redirected to /login endpoint. I am using flask security. I can do the same by not using ajax. Can anybody suggest me how to implement such feature.
Asked
Active
Viewed 1,597 times
4
-
1In the Ajax-handling method in the backend, check if the user is logged in or not. If they aren't, return a custom message or code. Check for that in the JS and redirect to a page as appropriate. – Celeo Jan 26 '16 at 19:14
-
So i need to pass user_id into every request for backend to determine whether this user is logged in or not – ankur singh Jan 26 '16 at 19:37
-
also note that you may want to check if the request is AJAX and if so, return 401 versus redirecting (301), as depending on how things are handled, you may end up with your ajax request getting the login html as its answer – Foon Jan 27 '16 at 03:13
1 Answers
2
Assuming you trying to get your data from /ajax like this:
$.getJSON("/ajax", function(data){
...
});
Simply protect that route in your init.py with login_required decorator:
from flask.ext.security import login_required
@app.route('/ajax')
@login_required
def ajax():
data = get_data() # Get your data
return json.dumps(data)
Or you can also do this:
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'

Steven Than
- 396
- 1
- 2
- 6