Add CSRF protection to every API call

This commit is contained in:
Joseph Schorr 2013-12-28 14:07:44 -05:00
parent 2e3be90054
commit 21ac1c9210
3 changed files with 28 additions and 1 deletions

View file

@ -1,5 +1,8 @@
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.principal import identity_changed
@ -46,3 +49,22 @@ def common_login(db_user):
else:
logger.debug('User could not be logged in, inactive?.')
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

View file

@ -724,7 +724,7 @@ quayApp = angular.module('quay', ['ngRoute', 'chieffancypants.loadingBar', 'rest
otherwise({redirectTo: '/'});
}]).
config(function(RestangularProvider) {
RestangularProvider.setBaseUrl('/api/');
RestangularProvider.setBaseUrl('/api/');
});
@ -2204,6 +2204,10 @@ quayApp.directive('ngBlur', function() {
quayApp.run(['$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.
Restangular.setErrorInterceptor(function(response) {
if (response.status == 401) {

View file

@ -67,6 +67,7 @@
<script type="text/javascript">
window.__endpoints = {{ route_data|safe }}.endpoints;
window.__token = '{{ csrf_token() }}';
</script>
<script src="static/js/app.js"></script>