Add CSRF protection to every API call
This commit is contained in:
parent
2e3be90054
commit
21ac1c9210
3 changed files with 28 additions and 1 deletions
|
@ -1,5 +1,8 @@
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
|
||||||
|
from flask import request, make_response, jsonify, abort, url_for, session
|
||||||
from flask.ext.login import login_user, UserMixin
|
from flask.ext.login import login_user, UserMixin
|
||||||
from flask.ext.principal import identity_changed
|
from flask.ext.principal import identity_changed
|
||||||
|
|
||||||
|
@ -46,3 +49,22 @@ def common_login(db_user):
|
||||||
else:
|
else:
|
||||||
logger.debug('User could not be logged in, inactive?.')
|
logger.debug('User could not be logged in, inactive?.')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def csrf_protect():
|
||||||
|
if request.method != "GET" and request.method != "HEAD":
|
||||||
|
token = session.get('_csrf_token', None)
|
||||||
|
found_token = request.args.get('_csrf_token', request.form.get('_csrf_token', None))
|
||||||
|
|
||||||
|
# TODO: add if not token here, once we are sure all sessions have a token.
|
||||||
|
if token != found_token:
|
||||||
|
abort(403)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_csrf_token():
|
||||||
|
if '_csrf_token' not in session:
|
||||||
|
session['_csrf_token'] = base64.b64encode(os.urandom(48))
|
||||||
|
return session['_csrf_token']
|
||||||
|
|
||||||
|
app.jinja_env.globals['csrf_token'] = generate_csrf_token
|
||||||
|
|
|
@ -2204,6 +2204,10 @@ quayApp.directive('ngBlur', function() {
|
||||||
|
|
||||||
quayApp.run(['$location', '$rootScope', 'Restangular', 'UserService', 'PlanService', '$http', '$timeout',
|
quayApp.run(['$location', '$rootScope', 'Restangular', 'UserService', 'PlanService', '$http', '$timeout',
|
||||||
function($location, $rootScope, Restangular, UserService, PlanService, $http, $timeout) {
|
function($location, $rootScope, Restangular, UserService, PlanService, $http, $timeout) {
|
||||||
|
|
||||||
|
// Handle session security.
|
||||||
|
Restangular.setDefaultRequestParams({'_csrf_token': window.__token || ''});
|
||||||
|
|
||||||
// Handle session expiration.
|
// Handle session expiration.
|
||||||
Restangular.setErrorInterceptor(function(response) {
|
Restangular.setErrorInterceptor(function(response) {
|
||||||
if (response.status == 401) {
|
if (response.status == 401) {
|
||||||
|
|
|
@ -67,6 +67,7 @@
|
||||||
|
|
||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
window.__endpoints = {{ route_data|safe }}.endpoints;
|
window.__endpoints = {{ route_data|safe }}.endpoints;
|
||||||
|
window.__token = '{{ csrf_token() }}';
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script src="static/js/app.js"></script>
|
<script src="static/js/app.js"></script>
|
||||||
|
|
Reference in a new issue